Possible Duplicate:
intern() behaving differently in Java 6 and Java 7
While doing example for this question
I noticed a strange behaviour of intern()
method when I call intern()
method on String
thereafter I can use ==
operator for the Original String.
JavaDoc of intern()
method:
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
andt
,s.intern() == t.intern()
is true if and only ifs.equals(t)
is true.
Above Javadoc does not say that the orginal string gets changed. So why this program prints okay
when test
is the input.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String username;
System.out.print("username: ");
username = user_input.next();
// Even if I do not assign returned string for comparison still it compares
// okay else it does not compare
username.intern();
if (username == "test") {
System.out.println("okay");
}
else {
System.out.println("not okay");
}
}
}