Site Search:

Define the scope of variables

Back OCAJP


There are three types of variables: local variables, instance variables and class variables.

local variables are defined inside a function or code block, they can not be accessed outside the method or code block it is defined.

Instance variables are also called fields, they are defined in the class itself and not in constructor or methods. Instance variables have the same lifetime as the object it is belongs to. Each instance have its own copy of the instance variable.

Class variables has the keyword static before it. Class variables are shared among all objects of the class. Class variable have the same lifetime as the java program.

Local variables need to be initialized before using, instance variables and class variables don't need programer to initialize. They have the following default values:

  • boolean -- false
  • byte, short, int, long -- 0
  • float, double -- 0.0
  • char NULL('\u0000')
  • object null


The following example shows the difference:



OCAJP>cat ScopeTest.java
public class ScopeTest {
  static int classVariable;
  int instanceVariable;
  public ScopeTest() {int local1 = 2;}
  public ScopeTest(int local2) {instanceVariable = local2;}
  public static void main(String[] local3) {
    int local4 = 0;
    ScopeTest st1 = new ScopeTest();
    System.out.println(classVariable);
    System.out.println(st1.classVariable);
    System.out.println(st1.instanceVariable);
    ScopeTest st2 = new ScopeTest(1);
    st2.setClassVariable(2);
    System.out.println(st1.classVariable);
    System.out.println(st1.instanceVariable);
    System.out.println(st2.classVariable);
    System.out.println(st2.instanceVariable);
  }
  void aMethod(int local5) {
    int local6 = 0;
    if(instanceVariable == 0) {
      int local7 = local6;
    }
    //local6 = local7; //not compile
    //System.out.print(local3[0]); //not compile
  }
  void setClassVariable(int local8) {classVariable = local8;}
}
OCAJP>javac ScopeTest.java
OCAJP>java ScopeTest
0
0
0
2
0
2
1



Back OCAJP