Why can't my Java method change the passed variable?

I was a little puzzled when I saw that the following code was not working properly.

I thought Java always passed variables by reference to functions. So why can't a function reassign a 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 prints null .

+6
java variables pass-by-reference pass-by-value null
source share
4 answers

Object references are passed by value in Java, so assigning a local variable within a method does not change the original variable. Only the local variable s points to a new line. This may be easier to understand with a little ASCII art.

You initially have this:

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

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

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

Then rewrite s:

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

And then leave the method:

 ------------ | nullTest | ------------ | null 
+21
source share

Java does not follow the link, it passes the value of the link. When you assign s="not null" , you reassign this value.

+2
source share

I was hoping to do something like setNotNull (MyObject o) without using o = setNotNull (o)

You just can't. The closest you get is something like this:

 public class MyRef<T> { private T obj; public T get() { return obj; } public void set(T obj) { this.obj = obj; } public void setNotNull(T obj) { if (this.obj == null) { this.obj = obj; } } } MyRef<MyObj> ref = new MyRef<MyObj>(); ref.setNotNull(xyz); System.err.println(ref.get()); 

which is pretty awkward and probably not worth the effort.

+1
source share
 s = 

that's why. you assign s without changing the object you are pointing to.

0
source share

All Articles