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() ? 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() ?" Watch "intern() ?" New topic

intern() ?

Muthuvel Ramamoorthy

Joined: Jun 08, 2006
Posts: 20
The following program returns,
can explain, what the method intern() does ?
Thank you

public class ObjectTest {

public static boolean compare1(String input) {
return (input == "Test");

public static boolean compare2(String input) {
return (input.equals("Test"));

public static boolean compare3(String input) {
String testString = new String("Test");
return (testString.intern() == input);

public static void main(String[] args) {
String input = "Test";
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Check String SDK:
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
When a String literal is used, that String object is placed into a pool. If another reference is pointed to the same String literal, then instead of creating a new object, that reference points to the String literal in the pool.

When you call intern() on a String, it searches the String pool. If the String that you call intern() on appears as a String literal in the pool, then the intern method will return a reference to that String literal.

That is why you get true when you call intern() on the String object that is created.

Because "Test" is in the pool already, and the parameter refers to it.
Muthuvel Ramamoorthy

Joined: Jun 08, 2006
Posts: 20
Thank you.
I agree. Here's the link:
subject: intern() ?
It's not a secret anymore!