Search code examples
javastringswingactionlistenerjtextarea

textarea.getText() is not working properly in Java


I have a JTextArea, and I'm trying to do a stupid test using textarea.getText()

if(textarea.getText() == "")
{
    System.out.println("empty string");
}

When I do this I don't get anything on the screen even if I leave the textarea empty or I type something inside of it.

if(textarea.getText() != "")
{
    System.out.println("empty string");
}

But when I do this one I get the "empty string" message in all cases.

What's the problem here ?


Solution

  • When comparing strings you should use equals instead of ==:

    if("".equals(textarea.getText()))
    {
       System.out.println("empty string");
    }
    

    == will compare references, it will only work in case it's the exact same String instance. If you want to check whether the content of the String is the same, you should use equals method.