javavariablesscopeinitializationdisambiguation

Java variable visibitlity


I have the following code:

public class Java0102
{
    public static void main(String[] args)
    {
        int x = 2;
        int y = 10;
        if (x == 2)
        {
            x = 5;
            int w = y * x;
        }
        System.out.println("W="+w);
        int W = x*y*w;
        y = x;
        System.out.println("New W="+w);
        System.out.println("X="+x);
        System.out.println("Y="+y);
    }
}

when i try to compile it on bluej it says cannot find symbol - variable w but since the if statement runs because x == 2 shouldn't java presume the variable w is initialized and so exists?


Solution

  • The variable w is declared inside the if block code, which means it will be accesible only in that scope: the block code of the if statement. After that block, the variable w doesn't exist anymore, thus the compiler error is valid.

    To solve this, just declare and initialize the variable before the if statement.

    int w = 1;
    if (x == 2) {
        x = 5;
        w = y * x;
    }
    

    From your comment in the question:

    I tought that the scope changes if a method is called and inside the method a declared variable is local so not visible outside. Is it the same thing with if statements? it changes scope?

    You're confusing the concepts of class variable i.e. a field and local method variable (commonly known as variable). The fields in the class will be initialized when you create an instance of the class, while the variables in a method have a specific scope that depends of the block code they are declared.

    This means, you can have this code compiling and running (doesn't mean you have to write code like this):

    public class SomeClass {
        int x; //field
        public void someMethod(int a, int b) {
            int x = a + b;
            //this refers to the variable in the method
            System.out.println(x);
            //this refers to the variable in the class i.e. the field
            //recognizable by the usage of this keyword
            System.out.println(this.x);
        }
    }