GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String intern() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String intern()" Watch "String intern()" New topic
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, T.Srinivasan
SCWCD 1.4(89%), SCJP 5.0(75%)
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8815
    
    5
FYI, the intern() method is not on any current version of the SCJP exam.


Spot false dilemmas now, ask me how!
(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.
 
GeeCON Prague 2014
 
subject: String intern()