Modifying String/Integer object and check if it affects a class object which has the object as its parameter

StackOverflow https://stackoverflow.com/questions/20452391

문제

public static void main(String[] args)
{
    String name = "john";
    StringTest obj = new StringTest(name);
    name = "peter";
    System.out.println(obj.name);
}

}

class StringTest{
String name;
StringTest(String name)
{
    this.name = name;
}

}

Now, since the string name has been reassigned from "john" to "peter" i expect it to print peter but it prints john. Has string being immutable causes a new object to be created when it is reassigned or what is the correct explanation for this?

Also when i try this with Integer object, the behaviour is same! Anyone please explain the reason for this behaviour

도움이 되었습니까?

해결책

Java uses pass-by-value, which means that you pass the value of name, not the reference.
Changing the value of name after you already created the StringTest instance won't affect your StringTest in any way.

다른 팁

I think what throws you off here is the fact that you do not have to use the "new" keyword to create the strings. The code reads more like creating a primitive type like int or long instead of object creation. Which is what is actually taking place. An equivalent way of creating the two strings is

String name = new String(new char[] {'j','o','h','n'});
StringTest obj = new StringTest(name);
name = new String(new char[] {'p','e','t','e','r'});

Written that way I think it is more clear why you do not achieve a side effect on the string referenced in StringTest. It has nothing to do with the fact that strings are indeed immutable.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top