Why the output is different between JDK 1.4 and 1.5?

后端 未结 4 879
清酒与你
清酒与你 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:58

    If you are using "==" operator on operation of String literals, then it depends on the whether the string literal value is present on "String Pool" or not, in your case variable "str" is a string JVM first checks on "String Pool" if it is found then it returns TRUE else FALSE. Try the following code with the intern() method, to make the string literal available on "String Pool"

     String str = "";
     int test = 3;
    
     str = String.valueOf(test).intern();
    
     System.out.println("str[" + str + "]\nequals result[" + (str == "3") + "]");
    
     if (str == "3") {
         System.out.println("if");
     } else {
         System.out.println("else");
     }
    

    according to documentation for intern() method: intern() method searches an internal table of strings for a string equal to this String. If the string is not in the table, it is added. Answers the string contained in the table which is equal to this String. The same string object is always answered for strings which are equal.

    Well "==" operation is not recommended for string comparison. use equals() or equalsIgnoreCase() method().

    I tried even in java 1.7 without intern() the output is

    str[3]
    equals result[false]
    else
    

    with intern() the output comes to:

    str[3]
    equals result[true]
    if
    

    This is not the problem of jdk 1.4 and 1.5 this is a "logical error".

提交回复
热议问题