0

immutable objects cannot be altered,whereas in line 3 x contains xyzabc.

I want to know what exactly is happening with the string object. Thanks in advance

Edited by JamesCherrill: Changed type to discussion

2
Contributors
3
Replies
11
Views
4 Years
Discussion Span
Last Post by JamesCherrill
0

You are confusing objects with reference variables. When you say
String s = "ABC";
"ABC" is an immutable String object, and s is a (not immutable) reference to a String. The current value of s is a reference to the "ABC" object.
s = s + "DEF";
You now have 3 String objects, "ABC", "DEF", and "ABCDEF", all immutable. The reference variable s has been updated to refer to the "ABCDEF" object.

Edited by JamesCherrill

0

I dont know if i am wrong. "ABC" is a value stored in s. Is "ABC" also called immutable object. If you can tell what exactly is the difference between immutable object and reference variable with example,it is really useful.Thanks in advance.

0

"ABC" is NOT a value stored in s. This is where you are going wrong.
"ABC" is a value stored somwhere in the Java VM's heap memory. The "value" stored in s is a reference (you can think of it as a pointer if you like) to the place where "ABC" is stored. The reference value in s can be changed at any time, but the "ABC" value in teh heap cannot be changed.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.