Java - Variables

These code snippets show the different types of variables and how they are used.

Instance Variables - Non-Static Fields

Instance variables are fields which are not declared with the static keyword. Its values are unique for an instance. The value of a field changed in one instance of a class is not reflected in another instance of the same class.
  1. class SimpleVariables {   
  2.     public String instanceVar =  "Hello World";   
  3.        
  4.     public static void main(String args[]) {   
  5.         SimpleVariables instance1 = new SimpleVariables();   
  6.         SimpleVariables instance2 = new SimpleVariables();   
  7.         instance2.instanceVar =  "Hello all";   
  8.            
  9.         System.out.println(instance1.instanceVar);   
  10.         System.out.println(instance2.instanceVar);   
  11.     }   
  12. }  

Class Variables - Static Fields

A class variable is a field which has been declared as static and there is only ever one copy of the field throughout its existence. Its value can be changed but it will be reflected anywhere the variable has been used.
  1. class SimpleVariables {   
  2.     public static String staticVar =  "Hello World";   
  3.        
  4.     public static void main(String args[]) {   
  5.         SimpleVariables instance1 = new SimpleVariables();   
  6.         SimpleVariables instance2 = new SimpleVariables();   
  7.            
  8.         instance2.staticVar =  "Hello all";   
  9.            
  10.         System.out.println(instance1.staticVar);   
  11.         // Prints Hello all   
  12.     }   
  13. }  

Local Variables

Local variables are defined within a method and are only available and visible by the method which defined it. Once the method has terminated the local variables will go out of scope.
  1. class SimpleVariables {   
  2.   
  3.     public static void main(String args[]) {   
  4.         string localVar =  "Hello World";   
  5.         System.out.println(localVar);   
  6.     }   
  7. }  

Parameter Variables

Parameter variables are those that are used in the signature of a method/construct. In the examples above the parameter variable is String args[] where args[] is the variable name.

No comments:

Post a Comment