0

(I really don't know how to phrase the question any better. I'm sure there is a concept involved here that I'm unaware of, so please suggest a better phrasing if you can--or direct me to an answered question if this turns out to be a duplicate)

I've been playing around in Java and found some behavior I can't explain. In the following code, I'd expect a 0 to be printed. However, nothing is printed. The only possible explanation I can come up with is that the main method ends before the printstream is flushed, but it doesn't make sense to me why that might be. In short, whats up with this code printing nothing instead of 0?

class Test {
    public static void main (String [] args) {

        if(false && method()){

        }
    }
    public static boolean method(){
        System.out.println(0);
        return true;
    }
}
marcman
  • 3,233
  • 4
  • 36
  • 71

1 Answers1

1

Because the method is not called. The false causes the and to short-ciruit.

if(false & method()){ // <-- body will not execute, but the evaluation
                      //     does not short circuit.

or

if(false || method()){ // <-- body will execute, method() is true

or

if(method() && false){ // <-- body will not execute, because of false.

will work as you expected.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Ah it really is that simple... Why would the first example `false & method` be any different? Because it's bitwise? It'll still always lead the argument to be false – marcman Apr 15 '17 at 02:04
  • Because it is [eager](https://en.wikipedia.org/wiki/Eager_evaluation), the second short-circuits. They are different operators. – Elliott Frisch Apr 15 '17 at 02:06
  • Oh ok, thank you for the explanation – marcman Apr 15 '17 at 02:12