Java boolean type

Introduction

Java boolean type is for logical values.

It can have only one of two possible values, true or false.

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

boolean is the type required by the conditional expressions such as if and for.

Here is a program that demonstrates the boolean type:


// Demonstrate boolean values.
public class Main {
  public static void main(String args[]) {
    boolean b;// w  ww .ja v  a 2  s  .c  om

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

    // a boolean value can control the if statement
    if(b){
       System.out.println("This is executed.");
    }

    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));
  }
}

When a boolean value is output by println(), "true" or "false" is displayed.

The value of a boolean variable by itself can control the if statement.

There is no need to write an if statement like this:

if(b == true){
   
}



PreviousNext

Related