Search code examples
javathisvariable-assignment

Is there a difference between "one declaration per line" and "multiple variable assignments per line" in Java? or how can the behavior be explained?


public class ThisKeywordDemo1 {
    int x = 10;
    int y = 20;
    
    public static void main(String[] args) {
        ThisKeywordDemo1 tkd = new ThisKeywordDemo1();
        tkd.getData();
    }

    public void getData(){
        //int a = x = 50;
        //int b = y = 40;

        int x = 50;
        int y = 40;
        int a = 50;
        int b = 40;

        System.out.println(a + b);
        System.out.println(x + y);
        System.out.println(this.x + this.y);

    }
}

In the above code snippet the output is 90 90 30, which is expected.

        int a = x = 50;
        int b = y = 40;

        //int x = 50;
        //int y = 40;
        //int a = 50;
        //int b = 40;

But when commented lines are uncommented and one line declarations are commented the output becomes 90 90 90, Could any of you explain the behavior ?


Solution

  • Those are two cases

    Case: A

        int a = x = 50; // int a = this.x = 50;
        int b = y = 40; // int b = this.y = 40;
    

    Case: B

        int x = 50; // introduce method local x, this.x stays 10
        int y = 40; // introduce method local y, this.y stays 20
        int a = 50;
        int b = 40;
    

    So, in the second case you shadow class fields with local variables.

    The inline assignment will be like:

        int a = 50, x = 50; // int a = 50, int x = 50;
        int b 40, y = 40; // int b = 40, int y = 40;