Java – Booleans

Many times in programming, a user will want a data type that represents True and False values. Java includes a boolean data type for this, which accepts True or False values.

Boolean Values

The boolean keyword is used to declare a variable that can only handle boolean values: True or False. A boolean variable named MyBoolVal is declared in the example below 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 following is the result of the aforementioned code:

true
false

Boolean Expressions

In Java, a boolean expression is an expression that yields boolean values, such as True or False. The comparison operator is employed in the boolean statement below, which returns true when the left operand is greater than the right operand and false otherwise.

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 create a complicated boolean expression, such as the && operator, which returns true if all conditions are true and false otherwise. Take a look at the sample 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:

Leave a Reply

Your email address will not be published. Required fields are marked *