• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

String intern (); method

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello everybody!

What wiil be output and why?
What kind of intern (); method?


public class Lsdksdksdjkjksdkdjdsjdkjkjsdkjsdk {

public static void main(String[] args) {
String s1 = "JavaWorld";
String s2 = ("Java" + new String ("World")).intern ();
System.out.println(s1);
System.out.println(s2);
System.out.println(s2 == s1);
}
}
 
Ranch Hand
Posts: 380
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


System.out.println(s2 == s1);



This will print true.
Reason is when you execute the intern() method it returns the referance of one of the objects that are existing in the String pool mantained by the JVM for reuse .

So,
First s1 is created pointing to "JavaWorld" and also a referance of this object is kept in JVM String pool.
Next a new String object is created s2 - but then an intern() is performed on it which forces it to look for object referances kept in the pool.
So it points that referance in the pool instead of the newly created object.


Since now both s1 and s2 point to the same memory location they return true.

-----
Shivani.
 
Ranch Hand
Posts: 657
Spring VI Editor Clojure
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String literals
 
reply
    Bookmark Topic Watch Topic
  • New Topic