I read this excellent article and it make sense: Java is strictly pass by value; when an object is a parameter, the object’s reference is passed by value.
However, I’m totally confused as to why the following snippet could possibly work.
Foo has a String member variable a which is immutable and needs to be burned in every time.
The first method of burning (commented out) should work fine and it does.
The second method set’s a‘s reference to the value that was passed. It should not work if newstr is a temporary variable. The expected output results are:
Totally temp
NULL
However, I get
Totally temp
Totally temp
Why? Is it just pure luck that the temporary variable reference is still good?
public class Foo {
String a;
public Foo(){}
public void burna(String newstr){
// a = new String(newstr);
a = newstr; /*this should not work: */
}
}
public class foobar {
Foo m_foo;
public foobar(){};
public void dofoo(){
String temp = new String("Totally temp\n");
m_foo.burna(temp);
System.out.print(m_foo.a);
}
}
public static void main(String[] args) {
Foo myfoo = new Foo();
foobar myfoobar = new foobar();
myfoobar.m_foo = myfoo;
myfoobar.dofoo();
System.out.print(myfoo.a);
}
The problem appears to be that you don’t understand how garbage collection works. As long as at least one reference to an object remains valid, that object will not be collected.