Tutorials

Java Variables


Java Static Variable


Java Static Variable is declared using static keyword.

 

Important points related to static variable

  • Static variable is also known as class variable because they belongs to a class. 
  • Static variable is shared among different instances of a class. So static variables requires less storage memory space than instance variables.
  • Static variable can be directly accessed using class name. For example, if you have declared static variable x in class A, then you can directly access it using dot (.) operator → A.x
  • You donot need to create instance of the class to access its class variable. See 3rd point again for example.

 

Example of static variable

Source file: Human.java

package variables;

public class Human {

   public String name;  //instance variable
   public static String belongsTo; //class variable

   //overriding toString()
   public String toString(){
         return name;

        }

}

Source file: InstanceVariable.java


	
package variables;

public class InstanceVariable {

            public static void main(String[] args) {

                        //assign different value to name(instance variable)of each instance
                        Human male = new Human();
                        male.name = "Rajneesh";

                        Human female = new Human();
                        female.name = "Shweta";

                        System.out.println("Name of male:"+ " " + male); //instance variable h1 : Rajneesh

                        System.out.println("Name of female:"+ " " + female); //instance variable h1 : Shweta



                        System.out.println(male+ "belongs to"+ male.belongsTo); //male belongs to : Homo-Sapiens
                        System.out.println(female+ "belongs to"+ female.belongsTo); //female belongs to : Homo-Sapiens

            }

}

OUTPUT:

Name of male: Rajneesh
Name of female: Shweta
Rajneesh belongs to Homo-Sapiens
Shweta belongs to Homo-Sapiens
 
From the above code, it is crystal clear that both the instance variable male and female of the class Human shared the static/class variable 'belongsTo'.
 
To access a class/static variable we have written:
System.out.println(male+ "belongs to"+ male.belongsTo);
System.out.println(female+ "belongs to"+ female.belongsTo);
 
You can access it easily by writing:
Human.belongsTo
Replace male.belongsTo and female.belongsTo with Human.belongsTo and run the code. You will get the same output.
Our point is that in case you want to access class variable then you can directly call it using class name as explained above. You don't neccessarily need to call it by creating instance of the class. 


Please Share this page
Views : 65