Java Static Variables and Static Methods

The static keyword in java is used primarily for memory management. Static keyword can be used with class, variable, method and blocks. The static keyword belongs to the class than instance of the class. This means if you make a member static, you can access it without object. In this tutorial post we will be specifically studying in detail about static variables and static methods in java

The static can be:

  • variable (also known as class variable)
  • method (also known as class method)
  • block
  • nested class
What is Static Variable in Java?

If you declare any variable as static, it is known static variable. Static variable in Java is variable which belongs to the class and initialized only once at the start of the execution.

Some Properties & Characteristics of static variables

  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • A single copy to be shared by all instances of the class
  • The static variable gets memory only once in class area at the time of class loading.
  • Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables
  • It is a variable which belongs to the class and not to object(instance)
  • A static variable can be accessed directly by the class name and doesn’t need any object

Lets take Program example to demonstrate the working of static variable being used as a counter which keeps count of number of objects of the class.

Java Static Variable program example
public class Cube {

    int side;
    static int objectCount=0;
    
    Cube()
    {
        objectCount++;
    }
    Cube(int x)
    {
        side=x;
        objectCount++;
    }
    
    public static void main(String[] args) {
        // TODO code application logic here
        
        Cube c1=new Cube(5);
        Cube c2=new Cube(8);
        Cube c3=new Cube(10);
        
        System.out.println("Number of Cube Objects: "+objectCount);
    }
    
}
Output
Number of Cube Objects: 3
Program Explanation –
 static variables in java diagram

In this above program, each Cube object has its own individual side instance variable. However, the static variable named objectCount is a class level variable which is common to all the objects of the Cube class. As you can see it is created only once even before the object is created and hence initialized in the class itself. Also you can see that in order to access the value of this static variable objectCount, we didn’t require to use object and the (.) operator. We simply could use the static variable directly as it is a class level variable and not object level. This program is used to maintain the count of objects created o Cube type this used as a counter.

What is Static Methods in Java?

When a method is declared with static keyword, it is known as static method. The most common example of a static method is main( ) method. A static method can access only static data.

Some Properties & Characteristics of static methods in java –

  • It is a method which belongs to the class and not to the object(instance)
  • A static method can access only static data. It can not access non-static data (instance variables)
  • A static method can call only other static methods and can not call a non-static method from it.
  • A static method can be accessed directly by the class name and doesn’t need any object
  • A static method cannot refer to “this” or “super” keywords in anyway
Java Static Method program example
public class Cube {

    static int calculateCube(int side)
    {
        return (side*side*side);
    }
    
    
    public static void main(String[] args) {
        
        int x=5;
        int cube = Cube.calculateCube(x);
       
        System.out.println("Cube value of 5 is: "+cube);
    }
}
Output
Cube value of 5 is: 125
Why java main method is static?

The main reason why java main() method is made static is because object is not required to call static method. If it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.

Static Blocks in Java

If you need to do computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded.

So in general static block –

  • Is used to initialize the static data member.
  • It is executed before main method at the time of classloading.
Java Static Block Program Example
class A2{  
  static{System.out.println("static block is invoked");}  
  public static void main(String args[]){  
   System.out.println("Hello main");  
  }  
}
Output
Output:static block is invoked
Hello main
Static Class in Java

A class can be made static only if it is a nested class.

  1. Nested static class doesn’t need reference of Outer class
  2. A static class cannot access non-static members of the Outer class
Java Static Class Program Example
class JavaExample{
   private static String str = "SimpleSnippets";

   //Static class
   static class MyNestedClass{
	//non-static method
	public void disp() {

	   /* If you make the str variable of outer class
	    * non-static then you will get compilation error
	    * because: a nested static class cannot access non-
	    * static members of the outer class.
	    */
	   System.out.println(str); 
	}

   }
   public static void main(String args[])
   {
       /* To create instance of nested class we didn't need the outer
	* class instance but for a regular nested class you would need 
	* to create an instance of outer class first
        */
	JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
	obj.disp();
   }
}
Output
SimpleSnippets
Watch it on YouTube

 

Leave a Reply

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