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
globalVariable.MAX_SIZE 
globalVariable.MIN_SIZE 

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!...

13 comments:

  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: http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367

    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.

    ReplyDelete
    Replies
    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.

      Delete
  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.

    ReplyDelete
    Replies
    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.

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

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

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

    ReplyDelete
  6. It was very easy to find my way around and very user friendly Good job to your designer and dev of your site. I hope your rate was doing well.
    토토
    경마
    온라인경마

    ReplyDelete
  7. I can read all the opinions of others as well as i gained information to each and everyone here on your site. Just keep on going dude. Check over here:
    majortotositepro
    racesitepro
    oncasinositenet
    totopickpro

    ReplyDelete