What are static variables? Why it is used? What is it’s use? – A Common Interview Question.

By | November 7, 2014

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

  • If you declare any variable as static, it is known static variable.
  • The static variable can be used to refer the common property of all objects (that is not unique for each object)
  • The static variable gets memory only once in class area at the time of class loading.
  • 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

  • If you apply static keyword with any method, it is known as static method
  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.
  • 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.

    Leave a Reply

    Your email address will not be published. Required fields are marked *