Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the output is different between JDK 1.4 and 1.5?

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
    
like image 547
omgeeeee Avatar asked Aug 01 '13 04:08

omgeeeee


1 Answers

According to this page, the Integer#toString method (which is called by String#valueOf(int)) is implemented like this in 1.4:

public static String toString(int i) {  
    switch(i) {  
        case Integer.MIN_VALUE: return "-2147483648";  
        case -3: return "-3";  
        case -2: return "-2";  
        case -1: return "-1";  
        case 0: return "0";  
        case 1: return "1";  
        case 2: return "2";  
        case 3: return "3";  
        case 4: return "4";  
        case 5: return "5";  
        case 6: return "6";  
        case 7: return "7";  
        case 8: return "8";  
        case 9: return "9";  
        case 10: return "10";  
    }  
    char[] buf = (char[])(perThreadBuffer.get());  
    int charPos = getChars(i, buf);  
    return new String(buf, charPos, 12 - charPos);  
}

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.

like image 122
assylias Avatar answered Dec 24 '22 03:12

assylias