0

I want to make it so that the text I enter into the JTextField fruit is read on button press, and prints "apple" if the entered text is apple, and "not apple" if the entered text is not.

However, even when I enter "apple" it runs through the else statement and prints "not apple" and I cannot figure out why this is happening. My code is below:

submit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                String enter = fruit.getText();
                String fruit2 = enter.toUpperCase();

                if (fruit2 == "APPLE") {
                    System.out.println("apple");
                } else {
                    System.out.println("not apple");
                }
            }
        });
  • 2
    NEVER compare `String` with `==`. Use `equals` method. Also you can skip that part of `toUpperCase()` and use `equalsIgnoreCase` instead of `equals` – KunLun Nov 30 '20 at 16:19

2 Answers2

1
if (fruit2 == "APPLE") {

Don't use "==" to compare objects. The "==" checks if it is the same instance of an object, not if the "value" of the object is the same.

Instead use the equals(...) method:

if (fruit2.equals("APPLE")) {
camickr
  • 321,443
  • 19
  • 166
  • 288
0

The == (two equal) sign only can be used to check for equality of primitive types and for object values check whether they are same instance of an object or point to same reference or not. to check objects for example String values you need to call the equals methods:

if("APPLE".equals(fruit2)) {
 
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36