Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String intern()

 
Ram Reddy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 557
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bert Bates
author
Sheriff
Posts: 8898
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FYI, the intern() method is not on any current version of the SCJP exam.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it . Thanks to all.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic