Home >Java >javaTutorial >boolean usage in java

boolean usage in java

下次还敢
下次还敢Original
2024-05-08 06:18:17861browse

Boolean is a type that represents true and false values ​​in Java, and the value is true or false. Its usage includes: conditional judgment, logical operation and Boolean return value of method. The declaration usage method is boolean variable name = true/false. Use == or != for comparison. Logical operators include AND, OR, and NOT. Example: Check if a number is even and display a message based on the result.

boolean usage in java

Usage of boolean type in Java

Boolean is a data type in Java that represents true and false values. It has only two possible values: true or false.

Usage

The boolean type is mainly used in the following situations:

  • Conditional judgment: Used in Conditions are judged in control structures such as if, while, and for.
  • Logical operations: Used to perform logical operations such as AND (&&), OR (||), and NOT (!). These operators combine multiple boolean values ​​to form a new boolean value.
  • Boolean return value of the method: Some methods return a boolean value indicating the result of the operation. For example, the equals() method of the String class compares strings for equality and returns true or false.

Declaration

To declare a boolean variable, you can use the boolean keyword, followed by the variable name:

<code class="java">boolean isTrue = true;</code>

Assignment

Boolean variables can be assigned values ​​through the assignment operator (=):

<code class="java">isTrue = false;</code>

Comparison

Boolean values ​​can be assigned through the equality operator (== ) or the inequality operator (!=) for comparison:

<code class="java">if (isTrue == true) {
    // 执行代码块
}</code>

Logical operations

Java provides the following logical operators:

  • AND (&&): When both operands are true, return true; otherwise, return false.
  • OR (||): When one of the operands is true, return true; otherwise, return false.
  • NOT (!): Invert the Boolean value of the operand.

Application Example

The following is a practical application example of the boolean type:

<code class="java">// 检查一个数字是否为偶数
boolean isEven = (number % 2 == 0);

// 根据布尔值显示消息
if (isEven) {
    System.out.println("该数字是偶数。");
} else {
    System.out.println("该数字是奇数。");
}</code>

The above is the detailed content of boolean usage in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn