Logical operators and short-circuit evaluation

To understand short-circuit evaluation, you must first understand what logical operators are.

Logical Operators 

Before understanding the operator, we must first know that the result of the logical operator in JAVA is a value of type Boolean

Logical AND "&&"

expression1 && expression2

 Logical AND means that the result is true only if the expressions on both sides of the operator are true .

expression 1 expression 2 result
real real real
real Fake Fake
Fake real Fake
Fake Fake Fake

logical OR "||"

expression1 || expression2

 Logical AND means that the result is false only if both expressions are false .

expression 1 expression 2 result
Fake Fake Fake
Fake real real
real Fake real
real real real

Logical NOT "!" 

! expression 1

And, or, not among the three logical expressions, only not is a unary operator .

When expression 1 is true, the result is false ;

When expression 1 is false, the result is true .

expression 1 result
real Fake
Fake real

 


short circuit evaluation

After understanding the logical operators, let's learn about short-circuit evaluation

First of all, you can think about the output of the following code.

 

 Answer:

The results of both questions are:

Why is this so?

  • For && , if the value of the expression on the left is false, the result of the expression must be false, and there is no need to calculate the expression on the right.
  • For ||, if the value of the expression on the left is true, the result of the expression must be true, and there is no need to calculate the expression on the right.

If you want to write code without short-circuit evaluation anyway  .

Then in JAVA, the bitwise operator "& |" can also act as a logical operator when the expressions on both sides of them return a value of Boolean.

& and | also represent logical operations if the result of the expression is boolean. But compared with && ||, they do not support short-circuit evaluation.

Guess you like

Origin blog.csdn.net/2302_76339343/article/details/131961162