Home> Java> javaTutorial> body text

boolean usage in java

下次还敢
Release: 2024-05-08 06:18:17
Original
746 people have browsed it

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:

boolean isTrue = true;
Copy after login

Assignment

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

isTrue = false;
Copy after login

Comparison

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

if (isTrue == true) { // 执行代码块 }
Copy after login

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:

// 检查一个数字是否为偶数 boolean isEven = (number % 2 == 0); // 根据布尔值显示消息 if (isEven) { System.out.println("该数字是偶数。"); } else { System.out.println("该数字是奇数。"); }
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!