Basic introduction to Boolean types in Java

  • 2020-04-01 04:16:25
  • OfStack

Java has a simple type that represents logical values, called a Boolean. It can only be either true or false. It is all such as a that 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 result of this program is as follows:


b is false 
b is true 
This is executed. 
10 > 9 is true 

There are three interesting things to note about this program. First, you've seen that when the method println () outputs 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 the if statement like this:


if(b == true) ... 

Third, relational operators (for example, <) The result is a Boolean value. That's why the expression 10> The display value of 9 is "true". In addition, in the expression 10> The extra parenthesis on both sides of 9 is because the plus sign "+" operator is bigger than the operator ">" Have a high priority.

The difference between logical and bitwise operations for JAVA Boolean types
From the results, the results of the two operations are the same, but there will be a "short circuit" in the logical operation, there is no bitwise, and bitwise than the logical operation more "or" function.

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 ampersand operation does not need to be performed to know the result, JAVA will "short circuit" to the following operation, which will improve the performance.


boolean f_2 = br.f2()||br.f1()||br.f3();

So, true, same f2() is true, same thing.
It seems convenient and efficient, but there are still disadvantages.


boolean f_3 = br.f2()||br.f3()&&br.f1();

The result is true, the correct should be false, this is the "short circuit" caused by the error, to get the correct answer need to add parentheses:


f_3=( br.f2()||br.f3())&&br.f1();

 
Bitwise provides xor functionality that logic does not:


boolean f = true^true;

F = false;


Related articles: