Static Keyword – Static Variable and Static Method in Java

HOME

public class Student {

    int rollNo;
    String name;
    static String college = "Trinity"; // Static Variable

    Student(int r, String n) // Constructor
    {
        rollNo = r;
        name = n;
    }

    void displayInformation() {
        System.out.println("Roll_No: " + rollNo + ", Name: " + name + ", College: " + college);
    }

    public static void main(String[] args) {

        Student S1 = new Student(111, "Tom");
        Student S2 = new Student(222, "Terry");
        S1.displayInformation();
        S2.displayInformation();
    }
}

What is the Static Method

If any method is declared static, then it is called a static method. A static method belongs to the class not to the object of the class. 

A static method can be accessed without creating the object of the class.

The static method can access data members and can change their value of it.

public class Student {

    int rollNo;
    String name;
    static String college = "Trinity"; // Static Variable

    Student(int r, String n) // Constructor
    {
        rollNo = r;
        name = n;
    }

    static void change() {
        college = "CITM";
    }


    void displayInformation() {
        System.out.println("Roll_No: " + rollNo + ", Name: " + name + ", College: " + college);
    }

    public static void main(String[] args) {
        change();    // Calling Static method
        Student S1 = new Student(111, "Tom");
        Student S2 = new Student(222, "Terry");
        S1.displayInformation();
        S2.displayInformation();
    }

Leave a comment