Java has a simple type that represents logical values called Boolean. Its value can only be one of two values: true or false. It is all such as a The following program illustrates the use of Boolean types:
// Demonstrate boolean values. class BoolTest { public static void main(String args[]) { boolean b; b = false; System.out.println("b is " + b); b = true; System.out.println ("b is " + b); // a boolean value can control the if statement if(b) System.out.println("This is executed."); b = false; if(b) System.out.println("This is not executed."); // outcome of a relational operator is a boolean value System.out.println("10 > 9 is " + (10 > 9)); } }
The results of running this program are as follows:
b is false b is true This is executed. 10 > 9 is true
There are 3 interesting things to note about this program. First, you have seen that when you use the method println () to output a boolean value, it displays "true" or "false". Second, the value of the Boolean variable itself is sufficient to control the if statement. There is no need to write if statements like this:
if(b == true) ...
Third, the result of a relational operator (such as <) is a Boolean value. This is why the expression 10>9 displays "true". In addition, the extra parentheses are added on both sides of the expression 10>9 because the plus sign "+" operator has higher precedence than the operator ">".
The difference between logical operations and bitwise operations on JAVA Boolean types
In terms of results, the results of the two operations are the same, but the logical operation will have a "short circuit" phenomenon, while the bitwise operation does not, and the bitwise operation has more "XOR" functions than the logical operation.
short circuit phenomenon
class br { static boolean f1() { return false; } static boolean f2() { return true; } static boolean f3() { return true; }} boolean f_1 = br.f1()&&br.f2()&&br.f3 ();
The result is false. When f1() is false, then the result of the subsequent && operation is known without having to perform it. JAVA will "short-circuit" the subsequent operation and improve the performance.
boolean f_2 = br.f2()||br.f1()||br.f3();
The result is true. Similarly, f2() is true, and there is no need to perform any further operations.
It seems very convenient and efficient, but it still has shortcomings.
boolean f_3 = br.f2()||br.f3()&&br.f1();
The result becomes true, which should be false. This is an error caused by "short circuit". If you want to get the correct answer, you need to add parentheses:
f_3=( br.f2()||br.f3())&&br.f1();
Bitwise operations provide XOR functionality that logic does not:
boolean f = true^true;
Result f = false;