Search code examples
javastaticclass-level

Behaviour of local and class variables in java


I am new in Java Programming language.
I am familiar with C and C++ but unable to understand the behaviour of the below program.

public class Test {
    static int x = 11;
    private int y = 33;
    public void method1(int x) {
        Test t = new Test();
        this.x = 22;
        y = 44;    
        System.out.println("Test.x: " + Test.x);
        System.out.println("t.x: " + t.x);
        System.out.println("t.y: " + t.y);
        System.out.println("y: " + y);
    }    
    public static void main(String args[]) {
        Test t = new Test();
        t.method1(5);
    }
}

Correct Output:

Test.x: 22
t.x: 22
t.y: 33
y: 44

Output expected:

Test.x: 22
t.x: 22
t.y: 44   // As variable y is modified inside the function.
y: 44

Even changing the line from y = 44; to this.y = 44; is not giving the expected output.


Solution

  • The problem is you are not referring to the actual object created. You are reffering the variable from other instance which have fresh variables.

            Test t = new Test();
            this.x = 22;
            y = 44;
    
            System.out.println("Test.x: " + Test.x);
            System.out.println("t.x: " + t.x);
            System.out.println("t.y: " + t.y);
            System.out.println("y: " + y);
    

    If you look close at very first line Test t = new Test();

    you are not calling method1 on that particular instance where y is assigning to 44. Hence you seeing the top level value.

    It will be more clear if you rename your instances. Instead of t always.

    That is the reason for the confusion and also, you call method1() inside that might lead to you a endless loop.