-6
public class Test {
    public Integer num = 1;

    public void change(Integer n) {
        n = null;
    }

    public void print() {
        System.out.println(num);
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.change(test.num);
        test.print();
    }
}

Why I can not change the value of the object "num" in above code? How to revise it to achieve the operation.

Fergus
  • 1
  • Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Lino Apr 11 '18 at 14:14

2 Answers2

3
public void change(Integer n) {
    n = null;
}

n is a local variable.

Change it to num = null

If you want to make the value of num to null (as you said in the comments), there is no need to pass anything as a parameter. This will do.

public void makeNull() { //or call it setNull
    num = null;
}

Also, don't make num public. Make it private. It is a good practice (and a must follow one IMO unless you have a strong reason)

Michael
  • 41,989
  • 11
  • 82
  • 128
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
0

In addition to what is provided in other answers, Java is pass-by-value. When you call a function with primitive variables as arguments, called function will use its own local copy of the variable you used as argument. It will only extract the value of that variable. Changes to the parameter variable in the called function will not effect the original variable.

Emre Dalkiran
  • 401
  • 3
  • 9