February 2, 2011

Scope of Variables in Java

Static variables have the longest scope - they are created when the class is loaded by the JVM Classloader and survive as long as the class stays loaded.
Instance variables are created when a new instance of the class is created and live until the instance is removed.

Local variables are created when execution enters the method and live as long as the method remains on the stack (or the method completes execution).
Block variables live only as long as the code block is executing.

public class Test {
   private int i;          // instance variable
   private static int j;   // static variable

   public void m1() {
      int k=0;       // local variable

      if (true) {
         int m=0;    // block variable

1 comment:

  1. This comment has been removed by a blog administrator.