0

So I am obviously missing something completely obvious here. I have a button and an actionlistener hooked up to it. When I click the button, I want run an if statement that takes the contents of a TextArea and compares it to a String. Like So:

String a = "hello";
JTextArea area = new JTextArea("type something");
JButton button = new JButton("Go");

button. [insert actionlistener crap]

    //here's the important part:
    if (area.getText() == "hello"){
        //this will not be executed
    }

It's really weird. I even went through the debugger and at that if statement, both of those items are "hello". But it skips over it! What am I doing wrong?

EDIT: a lot of you are saying "use .equals". Can anyone tell me why?

0

5 Answers 5

5

You should do area.getText(), this is a method, not a property.

Also you should compare them with equals not with ==.

So

"hello".equals(area.getText())

is the way to go.

3
  • That first was a mistake as I was typing the q, i didnt do that in the actual code. Jan 5, 2014 at 23:27
  • 1
    +1 for being the first respondent to mention BOTH bugs. Jan 5, 2014 at 23:28
  • 1
    @IsaiahTaylor The == checks for identity, equals checks for equality of the two values. For more details, visit the link provided by Teeg as a comment under your question. Jan 5, 2014 at 23:30
3

You need to use String.equals() to compare the two. Not ==.

That should solve the problem.

3

You need compare String with help of method equals().

2

You compare strings in java with equals(), not ==.

1

As others are pointing out String.equals is needed.

The reason for this is that, == will check whether both objects are in fact the same object i.e. have the same memory address.

1
  • Use trim() method to skip white space in the textarea if (area.getText().trim().equals("hello"))
    – PHPFan
    Jan 6, 2014 at 7:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.