If statement with String comparison fails [duplicate]
In your example you are comparing the string objects, not their content.
Your comparison should be :
if (s.equals("/quit"))
Or if s
string nullity doesn't mind / or you really don't like NPEs:
if ("/quit".equals(s))
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object:
In Java there are many string comparisons.
String s = "something", t = "maybe something else";if (s == t) // Legal, but usually WRONG.if (s.equals(t)) // RIGHTif (s > t) // ILLEGALif (s.compareTo(t) > 0) // also CORRECT>
String
s in java are objects, so when comparing with ==
, you are comparing references, rather than values. The correct way is to use equals()
.
However, there is a way. If you want to compare String
objects using the ==
operator, you can make use of the way the JVM copes with strings. For example:
String a = "aaa";String b = "aaa";boolean b = a == b;
b
would be true
. Why?
Because the JVM has a table of String
constants. So whenever you use string literals (quotes "
), the virtual machine returns the same objects, and therefore ==
returns true
.
You can use the same "table" even with non-literal strings by using the intern()
method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:
String a = new String("aa");String b = new String("aa");boolean check1 = a == b; // falseboolean check1 = a.intern() == b.intern(); // true
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.