KnowledgeBoat Logo
|

Computer Applications

How does Java resolve variables having same name? Give code example.

Encapsulation & Inheritance in Java

2 Likes

Answer

Java resolve variables having same name to the most local scope available. Therefore, if a local variable is having the same name as that of a global class element, the most local variable with the same name will be considered. The global variable will be hidden by the local variable.

Consider the example given below:

public class VarHiding
{
    // global variable "globalVar" is set to 0 
    public static int globalVar = 0;

    public void checking( )
    {
        test(5);
        System.out.println("First test :" + globalVar); 
        setGlobal(7);
        System.out.println("Second test :" + globalVar);
    }
    public static void test(int globalVar) 
    
    // globalVar is local to method test
    // test uses the same name as our globalVar variable
    
    {
        // All of these refer to local globalVar

        globalVar = globalVar;

        // Here local variable namely globaLVar will be 
        // considered
        // Global variable having same name i.e., 
        // globaLVar remains hidden, here 

        System.out.println("Inside of test :" + globalVar);
    }
    public static void setGlobal(int value)
        // test two uses a different name. To resolve 
        // variable globalVar, we must go higher in the 
        // "stack"
    {
        // Refers to global globalVar
        globalVar = value;

        // Here global variable - globalVar will be considered. 
        System.out.println("Inside of test2 :" + globalVar) ;
    }
}

The output produced by checking( ) function is as follows:

Inside of test :5
First test :0
Inside of test2 :7
Second test :7

Answered By

1 Like


Related Questions