Why does Java frequently throw null pointer exception if I try to access null values while Objective C does not?
Java:
public class SubscribeEmailActivity {
String status;
public static void main(String[] args){
if(Status.equals(null)||status.equals(""){
// i am getting error here
}
}
}
Objective C:
//in .h file
NSString *exp;
//in .m file
if ([exp isEqualToString:NULL] ||[exp isEqualToString:@""])
{
// i am not getting any error
}
The problem is in your evaluation in java, it should be:
if(status == null||status.equals("")) {
//Do not try to dereference status....
It should be noted that this only works because Java, and other languages, allow short cuts in logical evaluations. Some simple boolean algebra in this case:
true || ??? => true
Once the first term evaluates to true, we know that the OR conditional will also evaluate to true, there is no need to examine the second term.
Additionally you can use Apache Commons isEmpty()
or roll your own:
public static final boolean isEmpty(String arg0) {
if(arg0 == null) return true;
if(arg0.trim().length() < 1) return true;
return false;
}
The version shown is akin to isBlank
in Apache Commons.
Ultimately, the only way to completely solve this problem is by using a different programming language:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With