Check if at Least Two Out of Three Booleans Are True in Java

06 May 2023 Balmiki Mandal 0 Core Java

Check if at Least Two Out of Three Booleans Are True in Java

At times, we may want to check if at least two out of three boolean values evaluate to true. You can check this easily in Java using the following methods.

Using Logical OR Operator (||) and Logical AND Operator (&&)

We can use the logical OR operator (||) to check if at least two out of three booleans are true. Here, we will check if either A||B or B||C evaluates to true. If both of them evaluate to true then surely at least two out of three booleans are true.

if(A || B || C) { 
  // At least two out of three booleans are true 
}

Another way to check if at least two out of three booleans are true is by using the logical AND operator (&&). Here, we will check if both A&&B and B&&C evaluates to true. If both of them evaluate to true then again at least two out of three booleans are true.

if(A && B && C) { 
  // At least two out of three booleans are true
}

Using Arrays

We can also check if at least two out of three booleans are true by using an array. We will create an array of the three booleans and then check the number of true values in the array. If there are two or more true values in the array, then it confirms that at least two out of three booleans are true.

boolean[] values = {A, B, C}; 
int count = 0; 

for(boolean value: values) { 
  if(value) { 
    count++; 
  } 
} 

if(count >= 2) { 
  // At least two out of three booleans are true 
}

Conclusion

In this tutorial, we discussed various ways of checking if at least two out of three booleans are true in Java. Using these methods, you can easily check if a given set of boolean values contains at least two true values.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.