Hi JSK 1.3 for the java.lang.String class states: Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared
I am just reviewing and preparing for the exam now. I am still a bit confused with the subject of String.
Suppose you have the following
String str = "Hello"; str = "dog";
then, I would assume that a reference to the string "dog" is assigned to str, but a reference to string "hello" still lives on the heap.
Now the string object having the value of hello will be eligible for garbage collection, Because the reference varible str is now refering to the string object having the value of dog. So the first string object will be remain in the heap until the garbage collector destroy it.
String in java are objects. When a string is created, the heap is checked to see if that String object exit on the heap. If it does, the ref points to it. And if it does't a new String object is created.eg
String str = "abcd"; // place abcd on the heap --> str str = "hit"; // str --> hit, and abcd for gc str = str + "def"; // new String is created "hitdef" //and hit for gc Hope it helped. cheers
SCJA(Beta) SCJP 1.4 SCWCD 1.4 SCBCD 1.3 SCBCD 5.0 beta <br />The more practice we get, the better we are at the exams and in life in general. Pls join me at My DEN.
Sanju Thomas
Ranch Hand
Joined: Dec 29, 2004
Posts: 243
posted
0
String in java are objects. When a string is created, the heap is checked to see if that String object exit on the heap. If it does, the ref points to it. And if it does't a new String object is created.eg
In this case you are right,
String str ="hello"; String str1 = "hello"
But in this case, a new String object will be created.
String str = "hello"; String str1 = new String("hello");
String created with new String("hello") will follow normal GC rules. All string using primitive references (str = "hello" will be part of the pool and unloaded with the class loader I believe.