I'm running this code with JDK 1.4 and 1.5 and get different results. Why is it the case?
String str = "";
int test = 3;
str = String.valueOf(test);
System.out.println("str[" + str + "]\nequals result[" + (str == "3") + "]");
if (str == "3") {
System.out.println("if");
} else {
System.out.println("else");
}
outputs:
on jdk 1.4
str[3] equals result[true] if
on jdk 1.5
str[3] equals result[false] else
According to this page, the
Integer#toString
method (which is called byString#valueOf(int)
) is implemented like this in 1.4:That would explain your result because the string literal
"3"
is interned and"3" == "3"
always returns true.You can try with 10 and 11 to verify this.
Note: as already mentioned, the javadoc of
Integer#toString
does not say whether the returned string will be interned or not so both outputs in your question are equally valid.