0

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Benji
  • 47
  • 1
  • 2
  • 6

7 Answers7

13

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
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

This is a classic. Don't use "==" for comparing Strings, use String.equals().

2

Try using

"x".equals(input)

== tests whether they refer to the same object not the content of the string.

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
Polymorphix
  • 1,066
  • 1
  • 12
  • 29
1

Do not use == for comparing strings, use equals.

if(input.equals("x"))
    System.exit(0);
Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
1

Try "X".equals(input). For String comparison use equals method.

Vaandu
  • 4,857
  • 12
  • 49
  • 75
0

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).

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

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.

java_mouse
  • 2,069
  • 4
  • 21
  • 30