Java Program to Check if Two of Three Boolean Variables are True
Last Updated :
27 Nov, 2020
Boolean values are true/false. In this program, we need to check if any two out of three boolean values are true or not.
We will be discussing two major approaches to do it:
- using an if-else.
- using the ternary operator.
Approach 1: Using if-else condition
We initialize three boolean variable flags, with either a boolean FALSE or a TRUE value.
The counter approach can be used to check if two out of these three boolean variables are TRUE, by incrementing the counter value for each TRUE value.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
boolean flag1 = true ;
boolean flag2 = true ;
boolean flag3 = false ;
int cnt = 0 ;
if (flag1)
cnt += 1 ;
if (flag2)
cnt += 1 ;
if (flag3)
cnt += 1 ;
if (cnt == 2 )
System.out.println( "Two flags are true!" );
else
System.out.println( "Two flags are not true!" );
}
}
|
Output
Two flags are true!
- Time Complexity: O(1)
- Space Complexity: O(1)
Another Method: Here, we will check if flag1 is true, then the ans should be true if either of flag2 or flag3 is true. Otherwise, if flag1 is false, then ans will be true when both flag2 and flag3 are true.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
boolean flag1 = true ;
boolean flag2 = true ;
boolean flag3 = false ;
boolean ans = false ;
if (flag1) {
ans = flag2 || flag3;
}
else {
ans = flag2 && flag3;
}
if (ans)
System.out.println( "Two flags are true!" );
else
System.out.println( "Two flags are not true!" );
}
}
|
Output
Two flags are true!
- Time Complexity: O(1)
- Space Complexity: O(1)
Approach 3: Using the ternary operator
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
boolean flag1 = true ;
boolean flag2 = true ;
boolean flag3 = true ;
boolean ans = false ;
ans = flag1 ? flag2 || flag3 : flag2 && flag3;
if (ans)
System.out.println( "Two flags are true!" );
else
System.out.println( "Two flags are not true!" );
}
}
|
Output
Two flags are not true!
- Time Complexity: O(1)
- Space Complexity: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...