Java Data Type Tutorial - Java boolean Data Type








The boolean data type has only two valid values: true and false.

These two values are called boolean literals.

We can use boolean literals as

boolean done;   // Declares a boolean variable named done 
done  = true; // Assigns true to done

A boolean variable cannot be cast to any other data type and vice versa.

boolean is the type returned by all relational operators, as in the case of a < b.

boolean is the type required by the conditional expressions that govern the control statements such as if and for.

Example

Here is a program that demonstrates the boolean type:

public class Main {
  public static void main(String args[]) {
    boolean b;/*  w  w  w  .  java 2s .co  m*/

    b = false;
    System.out.println("b is " + b);
    b = true;
    System.out.println("b is " + b);

    b = false;
    if (b)
      System.out.println("This is not executed.");

    // outcome of a relational operator is a boolean value
    System.out.println("10 > 9 is " + (10 > 9));
  }
}

The code above generates the following result.