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