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".
"3".equals(str)
and not with==
operator. – EscobarString
comparison works in Java. Check out the link provided in my previous comment – Clarkequals
, using == if they are refering to the same object... if they were interned then that's you get true. – IncidentString.valueOf
implementation of the different JDKs and it is not a duplicate of the linked-to-question, it's more specific. Reading that other question will certainly help understand the answers here, but they don't themselves answer it. – Tellurionif (str == "3")
is invalid and will never likely be equal – Clark