So we know that Java
uses pass by value, i.e. it passes a copy of the reference to the methods.
I am wondering why is it then, that when I test the parameter reference (param
in my example) with the original reference (string
in my example) is says they are the same?
Shouldn't the following code return false
, i.e. the references are not the same, because a copy reference (i.e. a new reference) is passed by value?
public class Interesting {
private String string;
public Interesting(final String interestig) {
super();
string = interestig; // original reference is tested against copy reference and it says they are the same
}
public boolean isItTheSame(final String param) {
return param == string;
}
public static void main(final String args[]) {
Interesting obj = new Interesting("String");
System.out.println(obj.isItTheSame(obj.string)); //copy of reference is created here
}
}
A reference is a value of its own. The string "String"
lives at a specific memory location, say 0x01ab64e. Therefore, the value of any reference referring to that string is 0x01ab64e. There can be no reference to that string with a different value, because then it will not be referring to that string, it will be referring to a different string.
"Pass by value" refers to passing the reference by value, not passing the actual referenced object (the string) by value. So, the exact same reference is passed. That's why it is the same.
To verify that the reference is passed by value, (and that the value is a copy,) try this:
String s = null;
foo( s );
assert s == null;
void foo( String s )
{
s = "not null";
}
The assertion does not fail, which means that the reference s
held by the caller was not altered. Which means that the reference s
was passed by value, (which is always a copy,) so foo()
only changed the value of its own copy of the reference, leaving the copy of the caller unaffected.