java - Why the output is different between JDK 1.4 and 1.5? -
i'm running code jdk 1.4 , 1.5 , different results. why 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] ifon jdk 1.5
str[3] equals result[false] else
according this page, integer#tostring method (which called string#valueof(int)) implemented 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 explain result because string literal "3" interned , "3" == "3" returns true.
you can try 10 , 11 verify this.
note: mentioned, javadoc of integer#tostring not whether returned string interned or not both outputs in question equally valid.
Comments
Post a Comment