Boolean operators Java technology -7-

For Boolean type boolean, always only trueand falsetwo 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 && xthe result is always false, whether it xis trueor 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 0and 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 bvalue is true, the expression goes true && (5 / 0 > 0). Because you can not short-circuit operation, the expression must be due to the divisor 0and 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 >= 0is established, if it is true, then returns notherwise -n. This is actually an absolute value of an expression.

We note that the ternary operator b ? x : ywill first calculate b, if bis true, only the calculation x, otherwise, only the calculation y. In addition, xand ythe type must be the same , because the return value is not boolean, but xand yone.

Guess you like

Origin www.cnblogs.com/delongzhang/p/11260278.html