Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java check all arguments in "&&" (and) operator even if one of them is false?

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)?

like image 363
pixel Avatar asked Nov 12 '10 10:11

pixel


People also ask

Is args null in Java?

The arguments can never be null . They just wont exist. In other words, what you need to do is check the length of your arguments.

Does Java evaluate and or or first?

With three exceptions ( && , || , and ?: ), Java evaluates every operand of an operator before the operation is performed. For the logical AND ( && ) and logical OR ( || ) operators, Java evaluate the second operand only if it is necessary to resolve the result. This is known as short-circuit evaluation.

What is arguments in Java?

An argument is a value passed to a function when the function is called. Whenever any function is called during the execution of the program there are some values passed with the function. These values are called arguments.

How is && evaluated in Java?

Note that we use logical operators to evaluate conditions. They return either true or false based on the conditions given. The symbol && denotes the AND operator. It evaluates two statements/conditions and returns true only when both statements/conditions are true.


1 Answers

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".

like image 163
Martijn Courteaux Avatar answered Sep 29 '22 09:09

Martijn Courteaux