HOME HTML EDITOR C JAVA PHP

Java Booleans: Logic & Decision Making

In programming, you often need a data type that can only have one of two values, like YES / NO, ON / OFF, or TRUE / FALSE. In Java, we use the boolean data type for this.

Quick Fact: Unlike some other languages (like C++), a Java boolean is not an integer. You cannot use 1 for true or 0 for false; you must use the keywords true and false.

1. What is a Boolean?

A boolean type is declared with the boolean keyword and can only take the values true or false. This is the foundation of all conditional logic in Java.

Common uses for booleans:

2. Boolean Expressions

A Boolean expression returns a boolean value: true or false. You can use comparison operators, such as the greater than (>) operator, to find out if an expression is true.

3. Difference: Comparison vs Logical Operators

Understanding how to combine boolean values is key to building complex logic:

Comparison (==)

Checks if two values are equal. For example, 10 == 10 returns true.

Logical AND (&&)

Returns true only if both statements are true. (e.g., x < 5 && x < 10)

Logical OR (||)

Returns true if at least one of the statements is true.

4. Important Boolean Methods

While the primitive boolean is simple, the Boolean wrapper class provides utility methods:

  1. parseBoolean(): Converts a String to a boolean value.
  2. valueOf(): Returns a Boolean instance representing the specified boolean value.
  3. toString(): Converts a boolean value to a String ("true" or "false").
  4. logicalAnd() / logicalOr(): Static methods to perform logical operations.

5. Truth Table Comparison

A B A && B (AND) A || B (OR)
True True True True
True False False True
False False False False

6. Code Example

public class BooleanDemo {
  public static void main(String[] args) {
    boolean isJavaFun = true;
    boolean isFishTasty = false;

    System.out.println(isJavaFun); // Outputs true
    System.out.println(10 > 9);    // Outputs true
  }
}

Final Verdict

Booleans are the brain of your program. Without them, your code wouldn't be able to make decisions or handle different scenarios dynamically.

Next: Learn If...Else Statements →