Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java vs Objective C in case of nullpointer exception

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
}
like image 702
Ruban Avatar asked Aug 08 '13 13:08

Ruban


2 Answers

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.

like image 138
Pete B. Avatar answered Oct 14 '22 02:10

Pete B.


Ultimately, the only way to completely solve this problem is by using a different programming language:

  • In Objective-C, you can do the equivalent of invoking a method on nil, and absolutely nothing will happen. This makes most null checks unnecessary but can make errors much harder to diagnose.
  • In Nice, a Java-derivated language, there are two versions of all types: a potentially-null version and a not-null version. You can only invoke methods on not-null types. Potentially-null types can be converted to not-null types through explicit checking for null. This makes it much easier to know where null checks are necessary and where they aren't.
like image 36
ArunMak Avatar answered Oct 14 '22 04:10

ArunMak