Java if statement is skipped
In the following Java code, the if statement conditional does not evaluate to true and its block is skipped.
public void options(String input)
{
if(input == "x")
System.exit(0);开发者_运维百科
}
Input has the right value, so why is the System.exit(0) skipped?
You're comparing two string references for identity, not whether they refer to equal strings. It's not skipping the if
statement - it's evaluating the condition, and finding that it's false, so it's not going into the body. Try this:
if (input.equals("x"))
Or if input
might be null and you don't want that to cause an exception:
if ("x".equals(input))
This isn't just true of strings - whenever you have ==
, it will compare the values of the two expressions... and if those values are references, it simply compares whether those two references are equal, i.e. whether they refer to the same object. equals
, on the other hand, is applied polymorphically - so the object it's called on can determine what constitutes equality for that class.
As another example:
Integer x = new Integer(1000);
Integer y = new Integer(1000);
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
This is a classic. Don't use "==" for comparing Strings, use String.equals().
Try using
"x".equals(input)
==
tests whether they refer to the same object not the content of the string.
Do not use ==
for comparing strings, use equals
.
if(input.equals("x"))
System.exit(0);
Try "X".equals(input)
. For String comparison use equals method.
You need to use .equals()
, not ==
.
Using ==
will always fail: Unlike javascript, in java ==
tests if the two operands are the same exact object, which they aren't (one is a String constant, the other was user input)
.equals()
test if the two objects "have the same value" (class-dependant implementation).
Use == for comparing primitives and object references.
equals for content comparisons(provided it is implemented). String has the equals implemented for content comparison and you should use that.
精彩评论