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.o
This is an implementation detail that is not specified by the JLS.
The reference equality operator ==
checks to see whether two variables point to the same actual object, whereas the equals
method checks to see whether two variables' values are "equal" in some way that may be determined by the programmer. In this case, it appears that the 1.4 JVM is taking advantage of the fact that String
s are immutable to reuse the same copy of the string "3"
when you call valueOf
and the 1.5 JVM is not. Both options are perfectly legal, and you should not depend on any particular such behavior.