سؤال

I have such code:

if(object != null && object.field != null){
    object.field = "foo";
}

Assume that object is null.

Does this code result in nullPointerException or just if statement won't be executed?

If it does, how to refactor this code to be more elegant (if it is possible of course)?

هل كانت مفيدة؟

المحلول

Java does have short circuit evaluation, i.e. your code should be ok

نصائح أخرى

&& does short circuit while & would not.

But with simple questions like this, it is best to just try it (ideone can help when you don't have access to a machine).

&& - http://ideone.com/LvV6w & - http://ideone.com/X5PdU

Finally the place to check for sure would be the JLS §15.23. Not the most easy thing to read, the relevent section states: The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.

Best way to find out would be try it, especially for a single line question. Would have been faster, too.

The answer is that Java will not execute the body of the "if".

This will not throw any NullPointerException . The condition will be evaluated from left to right and the moment first false expression is found it will not evaluate remaining expression.

One way to know it! Test it! How? Well, make a method which prints out something:

public static boolean test(int i)
{
    System.out.println(i);
    return false;
}

...

if (test(1) && test(2) && test(3))
{
    // not reached
}

This prints:

1

So the answer on your question is "no".

Maybe this other question helps you:

Differences in boolean operators: & vs && and | vs ||

Java has short circuit evaluation, so it will be fine.

The code looks ok to me, but do you actually need to check object.field != null? I think that test can be omitted as you never use the variable, just set it.

On a side-note, most programmers wouldn't access fields directly (object.field) but rather through getters/setters (object.setField(x);). Without any more context to go on, I can't say if this is appropriate in your case.

&& and || conditions stops at the point they can decide whether the condition is true/false, in your case, the condition will stop right after object != null and I think that your code is just fine for this case

If you want all of your boolean expressions evaluated regardless of the truth value of each, then you can use & and | instead of && and ||. However make sure you use these only on boolean expressions. Unlike && and ||, & and | also have a meaning for numeric types which is completely different from their meaning for booleans. http://ibiblio.org/java/course/week2/46.html

Although short circuiting would work here, its not a guarantee that (like I have done many times) you'll get the order wrong when writing another, it would be better practice to nest those if statements and define the order you want the boolean checks to break:

if(object != null) 
{
    if(object.field != null)
    {
        object.field = "foo";
    }
}

This does exactly the same as you're essentially saying, if the first boolean check fails don't do the second; it is also nullPointerException safe as object.field will not be checked unless object is not null

Using short-circuiting on booleans can become annoying later on as when you have a multiple bool if statement it becomes trickier to efficiently debug which part short circuited.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top