Java Boolean logicalXor() Method
The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands.
Syntax:
public static boolean logicalXor (boolean a, boolean b)
Parameters:
The parameters ‘a’ and ‘b’ represents first and second operands.
Return Value:
The logicalXor () method returns the result after implementing logical AND operation on the parameters ‘a’ and ‘b’.
- It returns true, if the parameters ‘a’ and ‘b’ are different.
- It returns false, if both the parameters are identical.
Example 1:
public class JavaBooleanLogicalXorMethodExample1 { public static void main(String[] args) { Boolean b1 = true; Boolean b2 = false; // return boolean value after implementing logical XOR operator Boolean b3 = Boolean.logicalXor(b1,b2); Boolean b4 = Boolean.logicalXor(b1,b1); Boolean b5 = Boolean.logicalXor(b2,b2); Boolean b6 = Boolean.logicalXor(b2,b1); System.out.println("1. "+b1+" "+b2+" = "+b3); System.out.println("2. "+b1+" "+b1+" = "+b4); System.out.println("3. "+b2+" "+b2+" = "+b5); System.out.println("4. "+b2+" "+b1+" = "+b6); } }
Output:
1. true false = true 2. true true = false 3. false false = false 4. false true = true
Example 2:
public class JavaBooleanLogicalXorMethodExample2 { public static void main(String[] args) { //it will return an exception if we pass a null value Boolean b1 = null; Boolean b2 = false; boolean b3 = Boolean.logicalOr(b1,b2); System.out.println(b3); } }
Output:
Exception in thread "main" java.lang.NullPointerException at com.interf.JavaBooleanLogicalXorMethodExample2.main(JavaBooleanLogicalXorMethod Example2.java:10)
Example 3:
import java.util.Scanner; public class Boolean_logicalXorMethodExample3 { public static void main(String[] args) { Scanner scanner =new Scanner(System.in); System.out.println("Q How many hours are there in a day?"); System.out.print("Ans: "); int a = scanner.nextInt(); Boolean b1 = false; Boolean b2 = false; if(a==24){ b1 = true; } Boolean bool = Boolean.logicalXor(b1,b2); if(bool == true){ System.out.println("Answer is right."); } else{ System.out.println("Answer is wrong."); } } }
Output:
Q How many hours are there in a day? Ans: 24 Answer is right.