Scope of variables in Java

void doStuff() {

      for (int i = 0; i < 4; i++) {

           boolean flag = false;

           if (i == 3) { flag = true; }

}

System.out.println(flag);

}

I’m sure the compiler will do this :

Compiler will say that I have no memory of such a variable called flag. It will give an error with a message “flag cannot be resolved to a variable”

 

Examine the class below :

public class Test { // class

     static int a = 29; // static variable

     int b; // instance variable

 

{             // initialization block

b = 7;

                 int d = 5;

}

 

Test() {    // constructor

b += 8;

                 int e = 6;

}

 

     void doSomething() { // method

          int c = 0; // local variable

          for (int i = 0; i < 4; i++) { // for code block

c += i + b;

}

}

}

 

 

a          is static variable

b          is an instance variable

c          is a local variable

i           is a block variable

d          is an init block variable, a flavor of local variable

e          is a constructor variable, a flavor of local variable

 

There are 4 basic scopes:

  • Static variable has the longest scope. They are created when the class is loaded and they survive as long as the class stays loaded in the JVM.
  • Instance variables are the next most long-lived. They are created when a new instance(object) is created in the heap, and they live until the instance is removed.
  • Local variables are the next one. They live as long as their method remains on the stack.
  • Block variables live only as long as the code block is executing.

 

Saju Pappachen

About the author: Saju Pappachen is the Chief Consultant of jThread IT Training & Consultancy. He has more than 20 years of experience in Java technology.

He can be reached at saju@jthread.com

26 thoughts on “Scope of variables in Java

Leave a Reply to Aysha Dilna Cancel reply

Your email address will not be published. Required fields are marked *