-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
  • 34,340
  • 9
  • 58
  • 100
user7
  • 14,505
  • 3
  • 35
  • 62
  • @Michael `num = n` would be just a setter. I don't get what do you mean by `value is just set to the same value every time` – user7 Apr 11 '18 at 14:08
  • Actually, I would like to change the num into "null". I am implementing a tree data structure. I would like to use the similar function to delete each node of the tree. – Fergus Apr 11 '18 at 14:13
  • @Michael oh yes. You are right – user7 Apr 11 '18 at 14:14
  • @Fergus In that case, just make it null. See my EDIT – user7 Apr 11 '18 at 14:16
  • 1
    @Michael Thanks. I usually do it to denote something (maybe not that important/relevant here) was added after my initial answer based on comments/edit to the OP – user7 Apr 11 '18 at 14:25
  • @Michael@user7 Thank you for the help! – Fergus Apr 11 '18 at 14:29
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
  • 381
  • 2
  • 8