I read this Software Engineering note in Deitel and Deitel, ed3, p459. "In most cases, it is not necessary to make a copy of an existing String object. String objects are immutable--their character contents cannot be changed after they are created. Also, if there are one or more references to a String object (or any object for that matter) the object cannot be reclaimed by the garbage collector. Thus, a String reference cannot be used to modify a String object or to delete a String object from memory as in other programming languages such as C or C++" Question: Does this mean we should normally preferr using Char[ ] in place of String? Question: If the note is true, why does this work? String a = new String("hi"); a = "world"; Thanks! qionghua
a = "world"; is as good as saying a = new String("world");
I don't totally agree to this. Because, a="world" is a way of creating strings through literals and there are lot of chances that objects will be put in a common memory pool. On the other hand, if u create a string using a new operator, eventhough the contents of the string may be the same, they will be assigned a distinct memory.
Hi qionghua, Java creates a seperate area in memory (the String pool) to store literal String objects. Strings objects created using the 'new' operator or at runtime are stored on the 'heap'. The garbage collector only monitors the 'heap' memory; so String objects in the String pool are not garbage collected. For example,
Now, after I've said all that, for exam purposes, you only need to remember that any Object that is no longer being referenced is eligible for gc. The way garbage collection is implemented depends on the operating system and the exam does present you with questions that are system dependent; so it's unlikely you'll get any gc questions involving String literals. Hope that helps. ------------------ Jane Griscti Sun Certified Java 2 Programmer "When ideas fail, words come in very handy" -- Goethe