JiafanZhou
版主
发贴: 736
积分: 61
|
于 2008-07-03 17:09
ok, I think this topic is really really *complicated* by us, and will really really confuse others.
To all the Java beginners, if you want to use Strings in Java, you can use any of the ways provided above, disregarding how many Object instances have been created whether in the stack or in the heap or the pool of string. (i.e. It is the JVM to handle all these magic things behind scene, we don't have to care about these at all, unless there is a specific reason you want to optimize and profile your application -- my 2 cent)
So as a general rule if you don't understand this issue, forget about this article and just go ahead and use the magic Java String.
----------------------------------------------------------------------------------------------------------- To all the Java language syntax experts who want to know more about this issue like "臧圩人" and "andy_wang_5". After I read about the Javadoc of the String.intern(), I found something interesting:
intern() method is a native method and it will return a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings. In other words, it returns the object reference from the *pool of string* in the heap. (A pool of strings, initially empty, is maintained privately by the String object.)
Hence, talking about how the Object instances are allocated in the memory, they are outlined as follows:
- new String() creates an object instance in the heap and returns an object reference to the instance in the heap. - "xyz" (create string) creates an object instance in the "pool of string" (pool of string is also objects so created in the heap) and returns an object reference to the instance in the "pool of string". (Assuming no same strings created in the pool of string) - intern() method returns the object reference in the pool of string which has the same string content created in the heap. Otherwise this string object is added to the pool and a reference to this String object is returned. (NB. different object reference from the one in the memory heap I have all overlooked it)
When I was a kid I used to pray every night for a new bike. Then I realized that The Lord doesn't work that way, so I stole one and asked him to forgive me.
|