0

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?

st_ahmed
  • 2,293
  • 1
  • 12
  • 8

8 Answers8

3

Try to use equals method like this:

   if (value != null && !"".equals(value)) {
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
2

Strings are not compared like this:

value != ""

Use equals:

!"".equals(value)

or isEmpty:

!value.isEmpty()

Because String is immutable

1

When using == you are comparing the references which are not equal, that's why the expression evaluates to true.

You can use StringUtils.isNotEmpty

if (StringUtils.isNotEmpty(value)) {
...
}

true - if the String is not empty and not null

Reference

KAD
  • 10,972
  • 4
  • 31
  • 73
1

You should compare with value.isEmpty(). According to the source code, it will also compare the length.

What you are doing with != is comparing references, not equality.

Marcelo
  • 4,580
  • 7
  • 29
  • 46
0

String is an Object in java, so you can't use == and != with it, because == and != comparing references, which is not equal. Use "".equals(value)

TEXHIK
  • 1,369
  • 1
  • 11
  • 34
0
value != ""

check for reference equality not the value equality.

if value is created like this:

String  value=new String("");

then there is a high chance that the condition will fail.

For example if you have another String value2

String value2=new String("");

then

  value==value2  // is false.

Have a look at this How do I compare strings in Java?

Community
  • 1
  • 1
Saif
  • 6,804
  • 8
  • 40
  • 61
0

This is because you might have created value variable using new operator:

String value = new String();

So now if you use following :

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

It will print hi as value is from heap and literal "" is from string pool and you are making reference comparison. Use equals method instead .

Kunal Surana
  • 659
  • 5
  • 14
0

Your best bet is to use value != null && !value.isEmpty(), although you can ace this with the Yoda Expression

"".equals(value)

which saves you typing out the explicit check for null.

You can't use == since that would compare the object reference values (which might be different even if the string looks the same), not the string contents.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483