May occur any exception in coding for checking string is null or not ? Please help.
String code ;
if (!code.equals(null)) {
}
else
{
}
May occur any exception in coding for checking string is null or not ? Please help.
String code ;
if (!code.equals(null)) {
}
else
{
}
Here is how you can check if String value is null or not
if(code != null){
}else{
}
You can not us !code.equals(null)
because, equals
is used to compare same object type. null
is not any object type and code is String
. If you consider null as String
, then you can use !code.equals("null")
String can be checked like this:
if(code.equals("null") || code.equals("")) {
// code to do when string is null.
}
else {
// code to do when string is not null.
}
equals()
is use to check the similarity of two String
, and ==
or !=
is use to check the condition. In your case you are checking the similarity of string.
if (!code.equals(null)) {
//code checks that String code is equal to null or not
}
else
{
}
another
if (code != null) {
//code checks if code is not equals to null (condition checking)
}
else
{
}
There are many ways to check if String is empty in Java, but what is the right way of doing it? right in the sense of robustness, performance and readability. If robustness is your priority then using equals() method or Apache commons StringUtils is the right way to do this check. If you don't want to use third party library and happy of doing null check by yourself, then checking String's length is the fastest way and using isEmpty() method from String is most readable way. By the way, don't confuse between empty and null String, if your application treat them same, then you can consider them same otherwise they are different, as null may not be classified as empty. Here are three examples of checking String is empty or not by using JDK library itself.
You can't use .equals(null)
to make a null check, because the API description for Object#equals
states that:
For any non-null reference value x, x.equals(null) should return false.
Not only would this be a useless check (since it always returns false
), it would also throw a NullPointerException
if code
actually was null
, because a null
value does not define an equals
method.
Object x = null;
boolean isNull = x.equals(null); // NullPointerException on .equals
The only practical way to do a null check is to use:
if (code != null) {
}
If you want to check whether string is empty i.e. null
or ""
then use
if(TextUtils.isEmpty(code)){
}else{
}
equals
checks the value exists in string.