Difference between static and non-static variables in Java

In this post, we will discuss the difference between static and non-static variables in Java.


 

In the previous post, we have discussed the difference between static and non-static methods in Java. This post provides an overview of differences between static and non-static variables in Java.

 

  1. Similar to static methods, a static variable belongs to the class itself and a non-static variable belongs to each instance of a class. Therefore, the value of a static variable remains same for each instances of the class, but same cannot be said for non-static variable.
     
  2. Non-static variables cannot be accessed inside a static method without an instance of its class. A static method can only access static variables while a non-static method can access both static and non-static variables.
     
  3. Static variables reduces the memory footprint of the program. This is because the memory is allocated only once for static variable during the time of class loading while for a non-static variable, memory is allocated every time instance of the class is created.
     
  4. Static variables are usally declared as final in Java. This ensures the value never get changed after its initialization. This is very useful when we need a single copy of variable to be shared across all instances of the class.
     
  5. Static variables can be accessed using the class name while a reference to a non-static variable needs an instance of the class. For example, the standard output stream out is declared static in System class which is called using System.out.
     

 
Finally consider below program, which has a counter static variable to store number of instances of the Util class created so far. To demonstrate the difference between static and non-static member variables, remove static keyword from counter variable and note the difference in output:

 

Download   Run Code

Output:

No. of Util instances so far: 1
No. of Util instances so far: 2
No. of Util instances so far: 3

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of