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
Huang Jin
Greenhorn
Joined: Feb 01, 2001
Posts: 3
posted
0
You create a new string object called "Hello" and make a refer to it. You didn't change String object "Hi".
venkat_alladi
Greenhorn
Joined: Jan 31, 2001
Posts: 12
posted
0
a = "world"; is as good as saying a = new String("world"); Hope this helps. Venkat
qionghua yang
Ranch Hand
Joined: Oct 31, 2000
Posts: 68
posted
0
Thanks guys. But I still don't know what it is related to the memory and garbage collection. qionghua
natarajan meghanathan
Ranch Hand
Joined: Feb 01, 2001
Posts: 130
posted
0
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.
Sun Certified Programmer for Java 2 Platform
Jane Griscti
Ranch Hand
Joined: Aug 30, 2000
Posts: 3141
posted
0
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