Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42768

Is it possible short circuit evaluation happens in the following case

public class JavaApplication11 {

    static boolean fun() {
        System.out.println("fun");
        return true;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        boolean status = false;
        status = status & fun();
        status = fun() & status;
    }
}

Will Java thought, since status is already false, it will not executed fun method? I tested, in both case, fun will be executed. But, is it guarantee across Java spec?

Upvotes: 2

Views: 63

Answers (3)

SLaks
SLaks

Reputation: 887857

The && operator is guaranteed to be short-circuiting.
The & operator is guaranteed not to.

Upvotes: 1

Jeffrey
Jeffrey

Reputation: 44808

Short circuit evaluation does not happen here because you are using the bitwise and operation (&) instead of the logical and operation (&&).

Upvotes: 6

juergen d
juergen d

Reputation: 204884

double & is for short circuit operations. Use

status = status && fun();

Upvotes: 1

Related Questions