user1608396
user1608396

Reputation:

How to check if String is empty?

I am using following code to check if the String is empty

if( !Index2.toString().isEmpty()){
  ....
}

But I run into following error

java.lang.NullPointerException

Upvotes: 1

Views: 17932

Answers (6)

csk
csk

Reputation: 576

Check for String not to be null as well check for the empty space in a String because even if we have a space in a String as myString=" "; myString.isEmpty() will return false . so please considering the case above i will suggest as :

  if (myString != null && myString.trim().length() != 0 ) 
               return true;

Upvotes: 3

Ravi A
Ravi A

Reputation: 525

isEmpty() and null has nothing to do with each other. First checks the value of String if its equal to "" - OR you can say it will return true if its length is only and only 0. And second is checking for its initialization.

You should check for both of these condition if needed, like this,

if( str != null && !str.isEmpty() ) { ... }

OR

if( str != null && !str.equals("") ) { ... }

OR use this in your case,

if(index2 != null) { if( index2.toString() != null && !index2.toString().isEmpty() ) { ... } }

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85809

Your Index2 variable has null value. That's why you get the error. Specifically, the error is here:

Index2.toString()

Assuming your Index2 variable is different from null, your code will work. In order to make your code to work, you can validate that your Index2 is different from null or add a try/catch block that handles NullPointerException.

First way:

if( Index2 != null && !Index2.toString().isEmpty()){
    //...
}

Second way:

try {
    if( !Index2.toString().isEmpty()){
      //...
    }
} catch (NullPointerException npe) {
    //handle the Exception...
}

IMHO I would use the first way.

Upvotes: 4

Pete
Pete

Reputation: 10938

There's a StringUtils class in the apache.commons package that has lots of useful methods, like

StringUtils.isEmpty(theString)

Which will do both comparisons, != null and isEmpty and looks better.

Upvotes: 2

anubhava
anubhava

Reputation: 786289

This is how you should check empty for your case:

 if( Index2 == null || Index2.toString() == null || 
     Index2.toString().length() == 0)
     // it is empty

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41240

Check Null also.

if( Index2!=null && !Index2.toString().isEmpty()){
  ....
}

Upvotes: 2

Related Questions