For Boolean type boolean
, always only true
and false
two values.
Boolean operations is a relational operators, including the following categories:
- Comparison
>
operators:>=
,<
,<=
,==
, ,!=
- AND operation
&&
- OR
||
- Non-operational
!
boolean isGreater = 5 > 3; // true int age = 12; boolean isZero = age == 0; // false boolean isNonZero = !isZero; // true boolean isAdult = age >= 18; // false boolean isTeenager = age >6 && age <18; // true
Operational priorities:
Short circuit calculation
An important feature of Boolean operations are short-circuit operation. If the expression is a Boolean operation result can be determined in advance, the subsequent calculations are no longer performed, the direct result is returned.
Because false && x
the result is always false
, whether it x
is true
or false
, therefore, the operation in the first determination value false
, the calculation does not continue, but directly returned false
.
public class Main { public static void main(String[] args) { boolean b = 5 < 3; boolean result = b && (5 / 0 > 0); System.out.println(result); } }
If there is no short-circuit operation, &&
the latter due to the expression divisor 0
and error, but in fact the statement was not an error, because the operation is short-circuit operator, calculated in advance the results false
.
If the variable b
value is true
, the expression goes true && (5 / 0 > 0)
. Because you can not short-circuit operation, the expression must be due to the divisor 0
and error, you can self-test.
Similarly, for ||
operation, as long as the first value is determined true
, the subsequent calculations are no longer performed, but directly returnedtrue。
Ternary operator
Ternary operator b ? x : y
, which according to the result of a Boolean expression, return the calculated result of a subsequent one of the two expressions. Example:
public class Main { public static void main(String[] args) { int n = -100; int x = n >= 0 ? n : -n; System.out.println(x); } }
Above statement means that the judge n >= 0
is established, if it is true
, then returns n
otherwise -n
. This is actually an absolute value of an expression.
We note that the ternary operator b ? x : y
will first calculate b
, if b
is true
, only the calculation x
, otherwise, only the calculation y
. In addition, x
and y
the type must be the same , because the return value is not boolean
, but x
and y
one.