top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Java: What is the use of intern() method present in Object class?

+4 votes
Java: What is the use of intern() method present in Object class?
posted Oct 11, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

intern method is used to assign the string to String pool whenever you create a string using the new operator

String s= new String("xnsf"); //memory assigned in heap
s.intern() ; //sends it to the string pool.

answer Oct 13, 2014 by Vikalp Kumar
+1 vote

When you call intern() method, jvm will check if the given string is there, in string pool or not. If it is there, it will return a reference to that, otherwise it will create a new string in pool and return reference to that. In case : System.out.println(new String("ABC").intern()==new String("ABC").intern());

The first new String("ABC").intern() will create a string "ABC" in pool.When you call new String("ABC").intern() second time, jvm will return the reference to previously created string.That is the reason you are getting true when comparing both(both are pointing to same reference).

answer Oct 16, 2014 by Balakrishnan S
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.