Understanding the Java boolean Keyword with Examples

使用 GPT-4o-mini 回答Java Q&A Hub

問題:

Introduce Java boolean Keyword and give examples

答案:

In Java, the boolean keyword is a primitive data type that can hold one of two values: true or false. It is commonly used for conditional statements, loops, and flags to indicate the state of a condition.

Declaration and Initialization

You can declare a boolean variable and initialize it as follows:

boolean isJavaFun = true;
boolean isFishTasty = false;

Example Usage

  1. Using boolean in Conditional Statements:
public class BooleanExample {
    public static void main(String[] args) {
        boolean isRaining = false;

        if (isRaining) {
            System.out.println("Take an umbrella!");
        } else {
            System.out.println("No need for an umbrella.");
        }
    }
}

Output:

No need for an umbrella.
  1. Using boolean in Loops:
public class LoopExample {
    public static void main(String[] args) {
        boolean keepGoing = true;
        int count = 0;

        while (keepGoing) {
            System.out.println("Count is: " + count);
            count++;
            if (count >= 5) {
                keepGoing = false; // Stop the loop after 5 iterations
            }
        }
    }
}

Output:

Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
  1. Using boolean in Method Return Types:
public class BooleanMethodExample {
    public static void main(String[] args) {
        System.out.println("Is 10 even? " + isEven(10));
        System.out.println("Is 7 even? " + isEven(7));
    }

    public static boolean isEven(int number) {
        return number % 2 == 0; // Returns true if the number is even
    }
}

Output:

Is 10 even? true
Is 7 even? false

Summary

The boolean keyword in Java is essential for controlling the flow of a program through conditions and loops. It allows developers to create logic that can respond to different states and inputs effectively.