How do String objects work in Java? How does term “immutable” exactly apply to string objects? Why don’t we see modified string after passing through some method, though we operate on original string object value?
How do String objects work in Java? How does term immutable exactly apply to
Share
a String has a private final
char[]. when a new String object is created, the array is also created and filled. it cannot be later accessed [from outside] or modified [actually it can be done with reflection, but we’ll leave this aside].it is “immutable” because once a string is created, its value cannot be changed, a “cow” string will always have the value “cow”.
We don’t see modified string because it is immutable, the same object will never be changed, no matter what you do with it [besides modifying it with reflection]. so “cow” + ” horse” will create a new String object, and NOT modify the last object.
if you define:
and you call:
the
strwhere the call is is not modified [since it is the original reference to the same object!] when you changedarg, you simply changed it to reference another String object, and did NOT change the actual original object. sostr, will be the same object, which was not changed, still containing"cow"if you still want to change a String object, you can do it with reflection. However, it is unadvised and can have some serious side-affects: