File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes intern() method. 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 "intern() method." Watch "intern() method." New topic

intern() method.

Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
Can anyone explain me how intern() method works?

But if I replace line 1 with ("ja"+s2).intern(), then answer is true.
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
String s3 = ("ja"+s2).intern();

If this line is executed,
1) it first creates new String("java") on the heap.

2) Then it will call new String("java").intern().

3) Calling intern() means saying jvm to search String constant pool and find reference of String referenced by current calling object and return that reference,
means find reference of "java" in String constant pool and return that reference to s3.
Now s3 will refer to a String literal "java".

4)String s4 ="java"; and s4 also takes reference of "java" from string constant pool.

5) so both s3 and s4 are referring to same object that is referred string constant pool reference, so s3==s4 becomes true.
[ December 30, 2008: Message edited by: punit singh ]

Shwetha Sharma
Ranch Hand

Joined: Jun 01, 2008
Posts: 34

The intern method converts duplicated Strings to shared ones.When called on any string object it makes all other String objects with the same value(checked through the equals method) point to the same object in the String pool.
This method return of the value of the String
Also for any two strings a and b a.intern() == b.intern() is true if and only if a.equals(b) is true.

Like we have
String a = "ja"
String b = "va"
String c = "ja"+b;
String d = "java";

Now calling c==d should return true

But i tried Abhi's example
It wasnt giving expected results

The output of the above prg is :
1. java
2. java

Can someone explain this unusual behaviour ?or there is some problem in my understanding of the intern method

SCJP6:80%, OCWCD 88 %
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952

System.out.println("\n\n Checking str equality ::: "+s3==s4);

This is the culprit which is making you surprised.

it is actually doing

("\n\n Checking str equality ::: "+s3)==s4 //that is false

Now I think you got the solution.
Shwetha Sharma
Ranch Hand

Joined: Jun 01, 2008
Posts: 34

Thanks a ton Punit for the catch
I agree. Here's the link:
subject: intern() method.
It's not a secret anymore!