| Author |
String intern()
|
Ram Reddy
Ranch Hand
Joined: Feb 20, 2007
Posts: 88
|
|
class MyClass6 { public static void main (String args[]) { String str = new String("SCJP"); String str2 = ""; //blank string System.out.println(str == (str + str2).intern()); } } the out put is "false" please explain me in detail. And also when it will return true. please give me example
|
 |
Srinivasan thoyyeti
Ranch Hand
Joined: Feb 15, 2007
Posts: 557
|
|
Hi Rami, Good One. Here we go... 1) String str = new String("SCJP"); When you create a String with "new" key word, Two String Objects will be created. One in Heap and other in Constant Pool. Both Object references are different. 2)(str + str2).intern() (str + str2) ---> "SCJP", which will be found in pool. So pool Object reference is taken here. 3) str == (str + str2).intern() Here str on left hand side represents Heap Object. (str + str2).intern() on RHS represents Pool Object. As both the references are different. You got false. All the Best Rami.
|
Thanks & Regards,<br />T.Srinivasan,<br />SCWCD 1.4(89%),SCJP 5.0(75%)<br />"That service is the noblest which is rendered for its own sake." - Mahatma Gandhi
|
 |
Bert Bates
author
Sheriff
Joined: Oct 14, 2002
Posts: 8712
|
|
|
FYI, the intern() method is not on any current version of the SCJP exam.
|
Eliminate fossil fuel subsidies. (If you're not on the edge, you're taking up too much room.)
|
 |
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
|
|
class MyClass6 { public static void main (String args[]) { String str = new String("SCJP"); String str2 = ""; //blank string System.out.println(str == (str + str2).intern()); } } the out put is "false" please explain me in detail. And also when it will return true. please give me example
You little misinterpreted the use of intern() What intern does: if you intern you call the intern() method on a String reference, if the object referenced by it already exists in the memory, the reference to the existing String object will be returned otherwise it will return the same object reference that is new. try this out:
|
cmbhatt
|
 |
Srinivasan thoyyeti
Ranch Hand
Joined: Feb 15, 2007
Posts: 557
|
|
Hi Rami, On Basic point: How to know new String("xxx") will create different Heap and Pool Objects. String str = new String("Hello"); if ( str != str.intern()){ System.out.println("Heap Object reference and Pool Object reference are different"); } Hope this will make good foundation to understand your doubt.
|
 |
Ram Reddy
Ranch Hand
Joined: Feb 20, 2007
Posts: 88
|
|
|
I got it . Thanks to all.
|
 |
 |
|
|
subject: String intern()
|
|
|