Difference of null and other proposition using this null object

3

If I have a code, for example:

if(window!=null && window.isOpen()){
   //todo
}

If window is null , will it still try to call the second proposition or not check anymore? Because if it tries to call, then it will give NullPointerException .

    
asked by anonymous 25.08.2016 / 14:06

3 answers

10

The second will not be called. This is called short circuit evaluation (in Portuguese ). When the expression already obtains a final guaranteeing value, it does not have to continue to check the rest and the execution terminates. In case the relational operator is an AND and the two operands must be true to result in true , if the first one is already false , it is already known that the expression is false .

This is equivalent to:

if (window != null) {
    if (window.isOpen()) {
       //todo
    }
}

But it's a more concise form.

This is the correct, well-used technique to ensure that the object is not null. First it is verified if it is null and after an "And" operator does what it wants, that will only be executed if the first one is true. You can be creative with a lot of things there and use the same technique for various things.

There are cases where || is used. in this case if the first one is true the second one will not be executed, since in an "OR" operator a true one is enough to neither need to check the other operand.

    
25.08.2016 / 14:10
4

In order to get into if, both conditions must be true, if the first one is false (that is, windows == null ), it ignores the second and will not enter if.

See this example:

String b = null;

if(b != null && b.equals("")){
    System.out.println(b);
}else{
    System.out.println("b não atende as condições do if");
}

The output will be only the display of the message b não atende as condições do if , since b is null.

See working at ideone .

    
25.08.2016 / 14:08
1

I do not know if it does, but my college professor said that if you use & (one &) it checks both, and if you use & & (two &) it checks the first and if it gives deny it does not check the second.

Reference: link

    
25.08.2016 / 14:31