static keyword


The java static keyword can be applied with variables, methods, blocks and nested class.

We can use the static variables and methods without having any instance of the class.


static variable

A static variable is declared with static keyword and its properties are shared to all objects i.e. only one copy of static variable is maintained.

It can be used to refer to the common property of all objects and gets memory only once in the class i.e. at the time of class loading.

It makes our program memory efficient i.e. they save memory.

We can use the static variables and methods without having any instance of the class.


Example: Suppose there are 1000 students in a college, now all the instance data members will get memory each time when an object is created. All students have their unique rollNo and name but they have same college. So, we can make the college variable as static so that it will get memory only once and not 1000 times.

class Student
{
    int rollNo;
    String name;
    static String college ="KMV";

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

    void display ()
    {
        System.out.println(rollNo+" "+name+" "+college);
    }

    public static void main(String args[])
    {  
        Student s1 = new Student(7,"Abhishek");  
        Student s2 = new Student(21,"Raj");  
        s1.display();
        s2.display();
    }
}

Output:

7 Abhishek KMV
21 Raj KMV

static Method

A static method is declared with the static keyword. It cannot access non static/instance data member because a static method is never associated with any instance.

It can’t directly invoke a non-static method but it can access non-static methods by means of declaring instances and using them.

It can’t be overridden but can be redefined in a subclass.

We can use the static variables and methods without having any instance of the class.


Example:

class Student
{
    int rollNo;  
    String name;  
    static String college = "KMV";         

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

	Student(int r, String n)
    {
		rollNo = r;  
		name = n;
    }
    
	void display ()
    {
    System.out.println(rollNo + " " + name + " " + college);
    }

	public static void main(String args[])
    {
		Student s1 = new Student (7,"Abhishek");  
		Student s2 = new Student (21,"Raj");  
		s1.display();
		Student.change();   //now college is changed to DU
		s2.display();
	}
}

Output:

7 Abhishek KMV
21 Raj DU

static Block

A static block is executed before main method at the time of class loading and it is used to initialize the static data members.


Example:

class StaticBlockExample
{
    Static
    {
        System.out.println("static block is executed before main");
    }

    public static void main(String args[])
    {
        System.out.println("main is executed");  
    }
}

Output:

static block is executed before main
main is executed