posted 16 years ago
void method1(){
String fruit = "apple"; //1
transform(fruit); //2
System.out.println(fruit);//6
}
void transform( String fruit){ //3
fruit = "orange" //4
}//5
Within transform(), there are two items to consider: a -reference- and an "object that reference points to." The local reference, named -fruit- exists only within transform(), while "apple", pointed to by -fruit- still exists within scope of method1().
In line 8, the reference, -fruit- is reassigned to a new string literal, "orange." The original object, "apple" remains untouched. Additionally, Strings have no way of being altered, as they are "immutable" (unchangeable).
A walkthrough (see line numbers above):
1. The String literal "apple" is assigned to reference -fruit-
2. transform() is called with a COPY of the reference, -fruit-
3. the COPY of the reference to "apple" is created, also named -fruit-
4. A new string literal, "orange" is assigned to the new local reference -fruit-
5. transform() ends, and the local copy of the -fruit- reference is gone
6. The original reference, -fruit- remains untouched, as only a copy of the reference was manipulated within transform(). "apple" is printed.
If these were StringBuffer objects, and instead of variable reassignment we saw fruit.append("orange") - the object would be changed to "appleorange". But because this was only a local variable reassignment, the object remained untouched.
I hope that helps. Let me know - good luck!