Java Tutorial Java Advanced Java References

Java - Booleans



There are many instances in the programming, where a user need a data type which represents True and False values. For this, Java has a boolean data type, which takes either True or False values.

Boolean Values

A boolean variable is declared with boolean keyword and can only take boolean values: True or False values. In the example below, a boolean variable called MyBoolVal is declared to accept only boolean values.

public class MyClass {
  public static void main(String[] args) {
    boolean MyBoolVal = true;
    System.out.println(MyBoolVal); 

    MyBoolVal = false;
    System.out.println(MyBoolVal);   
  }
}

The output of the above code will be:

true
false

Boolean Expressions

A boolean expression in Java is an expression which returns boolean values: True or False values. In the example below, comparison operator is used in the boolean expression which returns true when left operand is greater than right operand else returns false.

public class MyClass {
  public static void main(String[] args) {
    int x = 10;
    int y = 25;
    System.out.println(x > y); 
  }
}

The output of the above code will be:

false

A logical operator can be used to combine two or more conditions to make complex boolean expression like && operator is used to combine conditions which returns true if all conditions are true else returns false. See the example below:

public class MyClass {
  public static void main(String[] args) {
    int x = 10;
    System.out.println(x > 0 && x < 25); 
  }
}

The output of the above code will be:

true