class OtherObject {
String innerString;
OtherObject(String x) {innerString = x;}
}
class Playground {
public static void mutate(OtherObject toMutate) {
toMutate.innerString = toMutate.innerString.substring(toMutate.innerString.length()/2);
}
public static void mutate(String toMutate) {
toMutate = toMutate.substring(toMutate.length()/2);
}
public static void main(String[] args) {
String helloWorld = new String("Hello, World!");
OtherObject helloWorld2 = new OtherObject("Hello, World!");
mutate(helloWorld);
mutate(helloWorld2);
System.out.println(helloWorld);
System.out.println(helloWorld2.innerString);
}
}
In this example, I have set two objects through method mutate
and only one of the objects changed, as shown in this output:
Hello, World!
World!
Process finished with exit code 0
This confuses me because if I remember correctly:
- Objects, when passed into methods are passing references, therefore even without returning, the object itself can be changed
- This is the same reason I can pass an ArrayList into a method and manipulate it without having to return the same ArrayList and assigning it to the previous ArrayList in
main
. - String is an Object.
Why didn't the String helloWorld change?