textarea.getText() is not working properly in Java
Solution 1
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.
Solution 2
Your code should use .equals() :
if(textarea.getText().equals(""))
{
System.out.println("empty string");
}
== compares the object reference rather than the object value
Solution 3
Alternatively, you can use isEmpty method in this case:
if(textarea.getText().isEmpty())
{
System.out.println("empty string");
}
Solution 4
Please use "".equals(textarea.getText()) instead of reference comparison. Operator == compares object references.
Wassim AZIRAR
https://www.malt.fr/profile/wassimazirar I am not looking for permanent contract (no need to contact me for that) I develop 💻 in .NET Core, JavaScript, Angular and React ⚛
Updated on January 04, 2020Comments
-
Wassim AZIRAR over 4 years
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 ?