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
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
You are confusing objects with reference variables. When you sayString 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.
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.
"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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.