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?

Isaiah Taylor
  • 615
  • 1
  • 4
  • 17

5 Answers5

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.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
3

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

alex2410
  • 10,904
  • 3
  • 25
  • 41
3

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

That should solve the problem.

Sully Brooks
  • 425
  • 4
  • 8
  • 21
2

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

Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
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.

splrs
  • 2,424
  • 2
  • 19
  • 29
  • Use trim() method to skip white space in the textarea **if (area.getText().trim().equals("hello"))** – PHPFan Jan 06 '14 at 07:17