When you define a variable in a method then that variable will no longer be useable when the method is over. Consider the code below -

public class foo{
    public void method(){
        int g = 5;
        System.out.println(g);
    }
    public void method2(){
        System.out.println(g);
    }
}

Method 2 will not complile. The reason is that variable g is not defined. Even though it has been defined in method it will not be available in method2. This is the essence of scope. As a rule of thumb a variable will only be available in the code block it was defined in AND any blocks which are inside that block. Consider the next method -

public class foo{
    public method(){
        int g = 3;
        for(int a=0; a<10; a++){
            g = g * a;
        }
        g = g * a;
    }
}

The varibale g is available in both the method and the for loop. The variable a is ONLY available in the for loop. The bold line shows where the compile error will be. As code blocks are nested a variable is not available in a parent block but is available in all child blocks.

next object scope >>

 
Basics
Menu
Search