Keith Spriggs
Keith Spriggs

Reputation: 235

Checking for null pointers

I'm looking for a phrase that forces the checking for null values before passing them through to an object and then when the object has been called that the first thing that is checked in the method that within the object is to check for null pointer exception.

I came across the phrase before

Could you help?

Sorry guys that I have not clarified my question.

I had came across in a book before where they had mentioned a phrase where before calling a method there was checking where to prevent the passing of null pointers and the first thing that is done in the called method is to check for null pointers.

Upvotes: 0

Views: 128

Answers (4)

novalagung
novalagung

Reputation: 11502

Null pointer exception is showing up when you have some object which is not initialized (default value of non-initialized object is null).

Thats mean, if you want to check wether object is null or not, you should use comparison operator. like:

if (object == null) {
    // do something
}

Upvotes: 2

Alexis C.
Alexis C.

Reputation: 93842

Just before creating you object, you could check the params using the word assert, i.e :

assert yourValue != null

By default, assertions are disabled at runtime. To enable them, pass the option -enableassertions (or -ea) to the JVM.

Another possibility (since Java 7) is to use the method requireNonNull direclty in your constructor/method, here's an example with the constructor :

public Foo(Bar bar, Baz baz) {
     this.bar = Objects.requireNonNull(bar, "bar must not be null");
     this.baz = Objects.requireNonNull(baz, "baz must not be null");
 }

Otherwise as @Woot4Moo said you could just use an if statement.

Upvotes: 1

Hot Licks
Hot Licks

Reputation: 47699

In theory any instance method of Object would work, though there's not a stand-out one for being cheap. The two most likely would be theReference.hashCode() and theReference.equals(theReference) (or maybe theReference.equals(null). Java standards require that any method call be evaluated for effect, so these calls would not be eliminated by the compiler or JITC.

Upvotes: 1

Woot4Moo
Woot4Moo

Reputation: 24316

defensive coding is the practice.

public void go(String s)  
{  
    if(null == s)  
        //do something
    else
    //  normal execution.
}  

Upvotes: 6

Related Questions