How to use the boolean data type in Java?

In Java, the boolean type is used to represent values of true or false.

Boolean type can be used in the following ways:

  1. Declare and initialize a boolean variable.
boolean isTrue = true;
boolean isFalse = false;
  1. Performing conditional checks using boolean expressions.
boolean isTrue = true;
boolean isFalse = false;

if (isTrue) {
    System.out.println("This statement is true.");
}

if (!isFalse) {
    System.out.println("This statement is also true.");
}
  1. The boolean type can be used as the return type for a method.
public boolean isEven(int num) {
    return num % 2 == 0;
}

// 调用方法
boolean result = isEven(5);
System.out.println(result);  // 输出:false
  1. Boolean type variables can be used as the condition for a loop.
boolean isTrue = true;
int count = 0;

while (isTrue) {
    System.out.println("This statement is true.");
    count++;
    
    if (count == 5) {
        isTrue = false;
    }
}

In summary, boolean types are mainly used for representing conditional statements and logical operations. They can be used by declaring and initializing variables, utilizing boolean expressions, as return types for methods, and as conditions for loops.

bannerAds