Java Boolean compare() method
The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result.
Syntax
public static int compare(boolean x, boolean y)
Parameters
The ‘x’ and ‘y’ represents the first and second Boolean parameters which are compared.
Return Value
This method returns an integer value which is as follows:
- It returns an integer value zero, if x and y are equal.
- It returns a positive integer value 1, if x is true and y is false.
- It returns a negative integer value -1, if x is false and y is true.
Example 1:
public class JavaBooleanCompareMethodExample1 { public static void main(String[] args) { Boolean b1 = false; Boolean b2 = true; int b3 = Boolean.compare(b1,b2); System.out.println("Compare method returns : "+b3); if(b3==0){ System.out.println("Both values are equal"); } else if(b3>0){ System.out.println("b1 value is true"); } else{ System.out.println("b2 value is true"); } } }
Output:
Compare method returns : -1 b2 value is true
Example 2:
import java.util.Scanner; public class JavaBooleanCompareMethodExample2 { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("Enter your name and age"); System.out.print("Name : ");String str1 =scanner.next(); System.out.print("Age :"); int age1=scanner.nextInt(); System.out.println(); System.out.print("Name : ");String str2 =scanner.next(); System.out.print("Age :"); int age2=scanner.nextInt(); Boolean b3=(age1>age2)?true:false; Boolean b4=(age1<age2)?true:false; int val= Boolean.compare(b3,b4); if(val==0){ System.out.println(str1+" and "+str2+" are equal in age"); } else if(val>0){ System.out.println(str1+" is elder than "+str2); } else{ System.out.println(str2+" is elder than "+str1); } } }
Output:
Enter your name and age Name : Sonu Age :31 Name : Bhaskar Age :34 Bhaskar is elder than Sonu
Example 3:
import java.util.Scanner; public class JavaBooleanCompareMethodExample3 { public static void main(String[] args) { Boolean b1=false; Boolean b2=false; Scanner scanner=new Scanner(System.in); System.out.println("Enter your name and age"); System.out.print("Name : ");String str =scanner.next(); System.out.print("Age :"); int age=scanner.nextInt(); System.out.println(); if(age>=18){ b1=true; } int val=Boolean.compare(b1,b2); if (val>0){ System.out.println(str+" you are an adult. You are eligible for voting."); } else{ int year=18-age; System.out.println(str+ " you are not an adult. You will be eligible for voting after "+ year +" years."); } } }
Output
Enter your name and age Name : Reema Age :16 Reema you are not an adult. You will be eligible for voting after 2 years.