aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String method 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 method intern()" Watch "String method intern()" New topic
Author

String method intern()

jaysingh solanki
Greenhorn

Joined: Nov 11, 2003
Posts: 14
String s1,s2,s3,s4
s1=new String("hello");
s2=new String("hello");

s1.equals(s2);//ok
s3=s1.intern();
s4=s2.intern();
if(s3==s4)//ok
But if i do:-
if(s1==s3)//not ok(not refer to same object);
if(s2==s4)//not ok
when String method intern is invoke on the
String object,it return a reference to a String object that
is guaranteed to have the same contant,However,String
s1 and String s2 have the same contents,the reference
returned by this call to intern is a reference to the
String object returned by s1.intern() and s2.intern().But s1==s3 and
s2==s4 give that they are not refer to same object,Why?;
Anurag Mishra
Ranch Hand

Joined: Sep 27, 2001
Posts: 133
This Happens because the object address is passed, when you compare s3 with s4 it will not be ok because both the string object will have different address.
Hope this helps!!!
ANURAG
Ray Stojonic
Ranch Hand

Joined: Aug 08, 2003
Posts: 326
s1 = new String("hello") creates a String object with "hello" as the value and enters "hello" into the string literal table.
s2 = new String("hello") also creates a String object with "hello" as the value, "hello" is already in the literal table, no entry made.
As s1 and s2 are different objects: (s1 == s2)==false
s3 = s1.intern() gets the "hello" string object from the literal table and assigns it to s3.
s4 = s2.intern() also gets the "hello" string object from the literal table and assigns it to s4.
s3 and s4 have reference to the same object, so (s3 == s4) == true.
It helps me to remember that s1 (for instance) is a reference to a String object, not the object itself.
given that, (s1==s3) doesn't ask 'is s1 equivalent to s3?' but rather 'is the object that s1 refers to the same object as s3 is referring to?'
if you were to change s1 = new String("hello") to s1 = "hello", then (s1==s3) would == true, because s1 = "hello" both creates a string object and assigns that same object to s1 and the literal table, which would also be assigned to s3 at: s3 = s1.intern()
Does that help?
Bert Bates
author
Sheriff

Joined: Oct 14, 2002
Posts: 8883
    
    5
Note to SCJP candidates: For the exam, it is very important to understand String immutability, and it is important to understand == vs. the equals() method.
But just so no one wastes any time, the intern() method itself is NOT on the exam.
Thanks,
The Focus Police


Spot false dilemmas now, ask me how!
(If you're not on the edge, you're taking up too much room.)
 
wood burning stoves
 
subject: String method intern()