here value of String object (abc)is not changing . Only the reference s indicating seperate String object.We just lost the reference to object abc which was earlier indicating by s. For this reason if you try with just s.concat("de"); System.out.println(s); it will only print abc .
Joined: Nov 17, 2006
Thaks for your reply!!
But can you please tell me why it happens to integers??
[I assume you are referring to int (the primitive type) and not Integer (the wrapper object. In that case...]
An int variable, holds the actual int value, not a reference to an object on the heap. In the examples above, the int is equivalent to the object reference, not the object itself. So just as the bit pattern representing the object reference changed when you assigned a reference to a new string, the bit pattern representing the int value changes when you assign a different int value to the variable.
there are two types of integers, one is the primitive int and the other is the Wrapper class called Integer.
The Wrapper class behaves just like the other class in Java and it is stored in heap. The explanation mentioned above also stands true for wrapper class. When you try to change a value, internally a new object is created.
Not really. The term "wrapper" isn't formally defined anywhere I know of, and it's entirely possible that someone might use the term in a sense that includes mutable objects. For example, a java.util.Date can be thought of as a wrapper around a long. But for some unknown reason (most likely, someone just screwed up) a Date is mutable.
On the other hand, as far as I can see, all the wrapper classes in the java.lang package are immutable. Those are the ones involved in autoboxing and unboxing. If that's what you meant, then yes. But it's not really true in general.