Why using static results in a different output?

I have the following code that prints 20.

import java.util.*;
import java.lang.*;
import java.io.*;

class A {
    public int val = 20; // <- no static
}


class Main {
    public static void main(String[] args) {
        A a = new A();
        updateVal(a);
        
        System.out.println(a.val);
    }
    
    private static void updateVal(A a) {
        a = new A();
        a.val = 50;
    }
}

But if I change val to static then it prints 50. How it works?

import java.util.*;
import java.lang.*;
import java.io.*;

class A {
    public static int val = 20; // <- there is static
}


class Main {
    public static void main(String[] args) {
        A a = new A();
        updateVal(a);
        
        System.out.println(a.val);
    }
    
    private static void updateVal(A a) {
        a = new A();
        a.val = 50;
    }
}

>Solution :

If the field is non-static, each instance has its own val field with its own value. Since Java is pass-by-value, not pass-by-reference, the statement a = new A() inside updateVal does not update the val field of the instance that was created in main.

If the field is static, all instances share the same field. The update inside updateVal is now that one shared field.

Leave a Reply