What is the usage of boolean in Java?

In Java, boolean is a primitive data type with only two possible values: true and false. It is mainly used to represent logical values for condition checks and control flow.

Boolean variables can be declared, initialized, and assigned a value. For example:

boolean isTrue = true;
boolean isFalse = false;

Boolean variables are commonly used in if statements, loop statements, and logical expressions. For example:

boolean isTrue = true;
if (isTrue) {
    System.out.println("条件成立");
} else {
    System.out.println("条件不成立");
}

boolean isFalse = false;
while (isFalse) {
    // 循环体
}

boolean result = (5 > 3) && (10 < 20);
System.out.println(result);  // 输出:true

Boolean type can also be used as a return value type and parameter type for methods. For example:

public boolean isEven(int number) {
    return number % 2 == 0;
}

public void printStatus(boolean status) {
    System.out.println("Status: " + status);
}

In summary, the boolean type in Java is mainly used to represent true or false values, for use in condition checking and controlling the flow of a program.

bannerAds