English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java program checks if two of the three boolean variables are true (true)

Java Examples Comprehensive

In this example, we will learn how to check if two of the three boolean variables are true in Java.

To understand this example, you should understand the followingJava programmingTopic:

Example: Check if two of the three boolean variables are true

//Java program checks if there is2variable
//one of these variables is true
import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    
    //create3boolean variables
    boolean first;
    boolean second;
    boolean third;
    boolean result;
    //Get boolean input from the user
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the first boolean value: ");
    first = input.nextBoolean();
    System.out.print("Enter the second boolean value: ");
    second = input.nextBoolean();
    System.out.print("Enter the third boolean value: ");
    third = input.nextBoolean();
    //check if there are two that are true
    if(first) {
      // if the first is true
      // one of the second and third is true
      // then result is true
      result = second || third;
    }
    else {
      // if the first is false
      // the second and third are both true
      // then result is also true
      result = second && third;
    }
    if(result) {
      System.out.println("There are two boolean values that are true.");
    }
    else {
      System.out.println("There are two boolean values that are not true.");
    }
    input.close();
  }
}

Output1

Enter the first boolean value: true
Enter the second boolean value: false
Enter the third boolean value: true
There are two boolean values that are true.

Output2

Enter the first boolean value: false
Enter the second boolean value: true
Enter the third boolean value: false
There are two boolean values that are not true.

In the above example, we have three boolean variables named first, second, and third. Here, we checked if two of the three boolean variables are true.

We have used the if...else statement to check if two boolean variables are true (true).

if(first) {
  result = second || third;
}
else {
  result = second && third;
}

In this case, in addition to the if...else statement, we can also use the ternary operator.

result = first ? second || third : second && third;

Java Examples Comprehensive