The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
variable (also known as class variable) method (also known as class method) block nested class
Static variable
For eg:
public class Test { public static String st_var = "I'm a static variable"; }
We can use this in another java class like below
public class Application { public static void main(String[] args) { System.out.println(Test.st_var); // call using Class name itself. } }
One common use of static is to create a constant value that’s attached to a class. The only change we need to make to the above example is to add the keyword final in there, to make ‘st_var’ a constant
Another classic use of static is to keep count of how many objects are created from a given class. Since Memory is allocated only once for a static variable, If you create any number of objects ,then all objects will have only one common static variable. In this way we can count the number of objects created by incrementing the static variable inside that class
If you make it Final, then it is unchangable after initial value.
static method
For Example
Class Test{ static void change(){ st_var = "CHANGED"; } } and call Like this Test.change(); // no need of object creation
Restrictions for static method
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly. this and super cannot be used in static context.
For Example
class A{ int num=50;//non static public static void main(String args[]){ System.out.println(num); } }
The output of above program will be a Compile Time Error.