| Author |
how many objects with new String statemtn
|
ani jadhao
Ranch Hand
Joined: Dec 23, 2008
Posts: 62
|
|
hello
while reading book of sierra for java , i came to read about below statement that
String str2 = new String("Hello");
there are two objects created . One on heap , referenced by str2 and one in string pool.
After reading , I tried to replicate the same in code, and tried
system.out.println(str2==str2.intern()); --as per book statement , one object created in pool also by new String("Hello"); . So intern should get the value of that object and should return true as intern and str2 supposed to refer the same object in pool.
But i got false as result.
please carify or correct if i am misstating ...
thanks
|
SCJP 1.4 : 91%
SCWCD 5: 96%
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
ani jadhao wrote:
String str2 = new String("Hello");
there are two objects created . One on heap , referenced by str2 and one in string pool.
are you sure?
|
 |
ani jadhao
Ranch Hand
Joined: Dec 23, 2008
Posts: 62
|
|
|
i have read in kathry sierra scjp 1.5 book . I didnt say that , book says that.
|
 |
Muhammad Khojaye
Ranch Hand
Joined: Apr 12, 2009
Posts: 341
|
|
ani jadhao wrote:i have read in kathry sierra scjp 1.5 book . I didnt say that , book says that.
Yes, two object would be created.
intern() method returns the string from the pool. Since str2 is initialize on the heap, while str2.intern() would return object from the pool, the two object would not be same.
however, this will return true.
|
http://muhammadkhojaye.blogspot.com/
|
 |
ani jadhao
Ranch Hand
Joined: Dec 23, 2008
Posts: 62
|
|
intern method try to find a string in pool, if not found it will create new and return string object reference.
there might b a possibility that line 2 would be doing similar kind a stuff.
I am stil not clear that , the Hello string has been picked up from pool . 3rd statemnt compares str2 which might get a NEWLY created string obj Hello from 2nd line .
|
 |
Sherif Shehab
Ranch Hand
Joined: Mar 05, 2007
Posts: 472
|
|
|
check THIS Thread
|
Thanks,
Sherif
|
 |
 |
|
|
subject: how many objects with new String statemtn
|
|
|