Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't my Java method change a passed variable? [duplicate]

I was kind of baffled when I saw the following code did not work as expected.

I thought Java always passed variables by references into functions. Therefore, why can't the function reassign the variable?

public static void main(String[] args) {

  String nullTest = null;

  setNotNull(nullTest);

  System.out.println(nullTest);
}

private static void setNotNull(String s) {
  s = "not null!";
}

This program outputs null.

like image 506
Will Avatar asked Aug 14 '10 00:08

Will


1 Answers

References to objects are passed by value in Java so assigning to the local variable inside the method doesn't change the original variable. Only the local variable s points to a new string. It might be easier to understand with a little ASCII art.

Initially you have this:

------------
| nullTest |
------------
     |
    null

When you first enter the method setNotNull you get a copy of the value of nullTest in s. In this case the value of nullTest is a null reference:

------------    ------------
| nullTest |    |    s     |
------------    ------------
     |               |
    null            null

Then reassign s:

------------    ------------
| nullTest |    |    s     |
------------    ------------
     |               |
    null         "not null!"

And then leave the method:

------------
| nullTest |
------------
     |
    null
like image 91
Mark Byers Avatar answered Oct 06 '22 23:10

Mark Byers