-1

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;
    }
}
ilhan
  • 8,700
  • 35
  • 117
  • 201
  • 1
    When you do `a = new A();` then you are no longer dealing with the `A` you passed in. You are dealing with a new `A`. When you do `a.val = 50` then you are assigning the value of **the new A**. If the value is static then the new A and the old A point to the same static value. Which, an IDE will warn you, should be referenced as `A.val = 50;` to remove confusion. – matt Aug 09 '23 at 14:32
  • 1
    Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – matt Aug 09 '23 at 14:33
  • 1
    In the static case, `a.val` is not really `a.val`, but `A.val` (all instances share the same field) – knittl Aug 09 '23 at 14:56

1 Answers1

4

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.

Rob Spoor
  • 6,186
  • 1
  • 19
  • 20