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
  • 597
  • 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
  • 36,377
  • 12
  • 75
  • 137
3

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

alex2410
  • 10,664
  • 3
  • 23
  • 40
3

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

That should solve the problem.

Sully Brooks
  • 425
  • 4
  • 8
  • 19
2

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

Martin Dinov
  • 8,480
  • 2
  • 27
  • 40
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,404
  • 2
  • 18
  • 28
  • Use trim() method to skip white space in the textarea **if (area.getText().trim().equals("hello"))** – PHPFan Jan 06 '14 at 07:17