Why the output is different between JDK 1.4 and 1.5?

后端 未结 4 887
清酒与你
清酒与你 2021-02-05 22:17

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         


        
4条回答
  •  既然无缘
    2021-02-05 22:59

    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 Strings 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.

提交回复
热议问题