Strange Behavior of Empty String in JAVA

st_ahmed

I am working on a Existing code and i found a Strange Behavior while checking a String is null or Empty. The existing code :

System.out.println("Length: " + value.length());
if (value != null && value != "") {
   //code
}

Output:

Length: 0

But the if statement becomes true and its executing the code.

When i replaced the if statement with this one:

if (value != null && value.length() > 0) {
   //code
}

It works perfectly. Any idea why the previous one failed and Why value != "" returns true?

Abdelhak

Try to use equals method like this:

   if (value != null && !"".equals(value)) {

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related