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

intern() ?

 
Muthuvel Ramamoorthy
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following program returns,
true
true
true
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";
System.out.println(compare1(input));
System.out.println(compare2(input));
System.out.println(compare3(input));
}
}
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic