IT Band of Brothers Grammar Java logical operators

Table 8 shows Boolean logic operation only Boolean operands, all binary logical operators are Boolean combinations of two, and the result is a Boolean type.


Table 8 Boolean operator

ab0b3d8b2f37464cb55e202db9b366fe.png


Boolean operator "&", "|", and "^" are Boolean operation, they operate the same way integer bit mode operation. Boolean NOT operator inverted logic state "!":! True == false and false == true!. Table 9 shows the results of various logical operations.

TABLE 9 Effect logical operation

6d25ab80d094425589ae208c4eaf9c83.png

The following procedures and demonstrated earlier BitLogic procedure is almost the same, but the program value is a Boolean logic operates on bits and not operate.

public class BoolLogic{

    public static void main(String[] args){

         boolean a = true;

         boolean b = false;

         boolean c = a | b;

         boolean d = a & b;

         boolean e = a ^ b;

        boolean f = (!a & b) | (a & !b);

         boolean g = !a;

         System.out.println("        a = " + a);

         System.out.println("        b = " + b);

         System.out.println("      a|b = " + c);

         System.out.println("      a&b = " + d);

         System.out.println("      a^b = " + e);

         System.out.println("!a&b|a&!b = " + f);

         System.out.println("       !a = " + g);

    }

}

Compile and run this program, the console 14 displays information as shown in FIG.

aebe5e3b86164d4fb9a9264435ac756b.png

Run Results FIG 14 BoolLogic


● logical operators shorting

Java provides two interesting that many other computer languages ​​do not provide Boolean operators. They are assisted version with Boolean operators and Boolean OR operators. Commonly referred to as a "short circuit" logical operators. 3.8 As can be seen from the foregoing table, if A is true, regardless of the value of B is, the logical OR of the results are true. Similarly, if A is false, no matter what the value of B is the result of both logic to false. If "||" and "&&" form instead of the operators "|" and "&" form, and if the individual can be determined according to the result of the expression of the left operand, then the calculation will not have a Java value of the operand. In order to get the correct function, when the operands depends on the value of the left operand, this feature very useful. For example, the following code shows how to use a short-circuit a logic operation, to ensure that legitimate prior to re-evaluate the expression:

if(denom != 0 && num/denom > 10)

This is then used as the logical form of the short circuit (&&), so there is no risk of the variable to 0 denom caused abnormal operation. If a single line of code symbols & Formal Logic is prepared, then both sides of the operands to be evaluated, so that when denom is 0, it will cause a run-time exception.


Guess you like

Origin blog.51cto.com/14311187/2416880