Friday, January 3, 2014

Global Variable vs Class Variable vs Instance Variable vs Local Variable in Java

In this post, we'll develop some basic understanding of different kind of variable in java and how they are differ from each other with the help of some examples.

Local variable
A local variable lives only within the method that declared the variable.

Variable's can be used only within the read() method. In other words, the variable is in scope only within its own method. No other code in the class can see.
When you call a same method second time, it recreates the local variables, and reinitialized them.

Before using local variable, it must be initialized.

Local variables, including primitives, always, always, always must be initialized before you attempt to use them.
  • Just don't forget that while the local variable is on the stack, if the variable is an object reference, the object itself will still be created on the heap. There is no such thing as a stack object, only a stack variable.
  • Local variable declarations can't use most of the modifiers that can be applied to instance variables, such as public (or the other access modifiers), transient, volatile, abstract, or static, but local variables can be marked final.

Class Variables
A class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many instances of the class exist.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. 
  • Every instance of the class shares a class variable, which is in one fixed location in memory.
  • Any object can change the value of a class variable.
  • Class variables can also be manipulated without creating an instance of the class.

Sample Output
c1 size : 10 c2 size : 10 c3 size :10
c1 size : 50 c2 size : 50 c3 size :50
Size = 50

The problem is that main() is itself a static method, and thus isn't running against any particular instance of the class, rather just on the class itself.
A static method can't access a nonstatic (instance) variable, because there is no instance!

That's not to say there aren't instances of the class alive on the heap, but rather that even if there are, the static method doesn't know anything about them. The same applies to instance methods; a static method can't directly invoke a nonstatic  method. Think static = class, nonstatic = instance

Instance Variable
  • There are those variable that is associated with object.
  • Instance variables are defined inside the class, but outside of any method, and are only initialized when the class is instantiated.
  • Their values are unique to each instance of a class.
  • An instance variable lives as long as the object does. If object is still alive, so are its instance variables.
You need to know that instance variables
  • Can use any of the four access levels (which means they can be marked with any of the three access modifiers)
  • Can be marked final
  • Can be marked transient
  • Cannot be marked abstract
  • Cannot be marked synchronized
  • Cannot be marked strictfp
  • Cannot be marked native
  • Cannot be marked static, because then they'd become class variables.

Sample Output
c1 size :2 c2 size:0 c3 size:0

c1 price :0 c2 price:100 c3 price:0

Global Variable
There is no direct concept of global variable in java, but you implement the same in different number of ways.

With the help of static keyword and public access modifier.
public class GlobalVariable {  
      public static int MAX_SIZE = 1000;  
      public static int MIN_SIZE = 1;  
Now you can access MAX_SIZE and MIN_SIZE from anywhere by calling like this

With the help of interface
public interface GlobalVariable1 {  
       * Variable are implicitly public, static, and final  
       int MAX_SIZE = 1000;  
       int MIN_SIZE = 1;  
Any class that needs to use these, can implement the interface.
public class GlobalVariable1Demo implements GlobalVariable1{  
      public static void main(String[] args) {  
           System.out.println("Max Size :"+MAX_SIZE);  
           System.out.println("Max Size :"+MIN_SIZE);  

The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.

Related Post
Stack and Heap Memory Concept in java
this keyword in java
Why to override hashCode() and equals() in java

If you know anyone who has started learning java, why not help them out! Just share this post with them. 
Thanks for studying today!...


  1. Good article! But, I'm going to nit pick a bit here.

    It's standard Java convention to capitalize the first letter in Java class names.

    See here:

    So, "public class localVariable" should be "public class LocalVariable"

    The code will run as is, but in my opinion, ignoring conventions is really bad form.

    1. @Trace, you are 100% correct, conventions should not be ignored. While writing the examples I was not concentrating on the conventions. However, I made the changes and thanks for pointing out.

    2. Great Article android based projects

      Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

  2. There is an another problem. The constructor for your caffe class is not public. Your code will work as long as the instanceVariable class is in the same package, but you should probably make the constructor public.

    1. @datguy, you are right. I have created both the classes in the same class that why I haven't written the public access modifier. Now I made the changes. Thanks for pointing out.

  3. What is the different between class variable and instance variable

  4. @pardeepk Nice article it was very clear thanks a lot

  5. Great post! Helped me lots, thanks :)

  6. • Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updatingAzure Online course

  7. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head.
    I am highly impressed with your blog. It is very nicely explained.
    Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

  8. nice blog
    great information.
    Aesthetics Course is an integral part of Cosmetology and is a blooming industry in Beauty and Wellness Industry.
    At VLCC Institute, aspiring Cosmetologist can enroll into different Aesthetic Courses as per their requirements.

  9. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information,
    I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.
    Java training in Btm layout
    Java training in Jaya nagar
    Java training in Electronic city
    Java training in Chennai
    Java training in USA

  10. nice blogs
    great information.
    VLCC Institute the Leaders in Beauty & Wellness training, has successfully trained more than 75000 students so far.
    State-of-the-art infrastructure, market relevant courses, qualified and well-trained faculty, dedicated placement.

  11. I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end. I would like to read newer posts and to share my thoughts with you.Your post is just outstanding! thanks for such a post,its really going great and great work.You have provided great knowledge
    Azure Training in Chennai

    Azure Training in Bangalore

    Azure Training in Hyderabad

    Azure Training in Pune

    Azure Training | microsoft azure certification | Azure Online Training Course

    Azure Online Training

  12. Ucuz, kaliteli ve organik sosyal medya hizmetleri satın almak için Ravje Medyayı tercih edebilir ve sosyal medya hesaplarını hızla büyütebilirsin. Ravje Medya ile sosyal medya hesaplarını organik ve gerçek kişiler ile geliştirebilir, kişisel ya da ticari hesapların için Ravje Medyayı tercih edebilirsin. Ravje Medya internet sitesine giriş yapmak için hemen tıkla:

    İnstagram takipçi satın almak için Ravje Medya hizmetlerini tercih edebilir, güvenilir ve gerçek takipçilere Ravje Medya ile ulaşabilirsin. İnstagram takipçi satın almak artık Ravje Medya ile oldukça güvenilir. Hemen instagram takipçi satın almak için Ravje Medyanın ilgili sayfasını ziyaret et: instagram takipçi satın al

    Tiktok takipçi satın al istiyorsan tercihini Ravje Medya yap! Ravje Medya uzman kadrosu ve profesyonel ekibi ile sizlere Tiktok takipçi satın alma hizmetide sunmaktadır. Tiktok takipçi satın almak için hemen tıkla: tiktok takipçi satın al

    İnstagram beğeni satın almak için Ravje medya instagram beğeni satın al sayfasına giriş yap, hızlı ve kaliteli instagram beğeni satın al: instagram beğeni satın al

    Youtube izlenme satın al sayfası ile hemen youtube izlenme satın al! Ravje medya kalitesi ile hemen youtube izlenme satın almak için tıklayın: youtube izlenme satın al

    Twitter takipçi satın almak istiyorsan Ravje medya twitter takipçi satın al sayfasına tıkla, Ravje medya güvencesi ile organik twitter takipçi satın al: twitter takipçi satın al