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
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.
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;
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() ) { ... } }
if(index2 != null) { if( index2.toString() != null && !index2.toString().isEmpty() ) { ... } }
Index2.toString().isEmpty()should beIndex2!=null && Index2.toString().isEmpty()