Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

intern() method.

 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
Eclipse IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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";
c.intern();

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
false

Can someone explain this unusual behaviour ?or there is some problem in my understanding of the intern method
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 34
Eclipse IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a ton Punit for the catch
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic