On this document we will be showing a java example on how to use the xor() method of BigInteger Class. Basically this method returns a BigInteger whose value is (this ^ val). (This method returns a negative BigInteger if and only if exactly one of this and val are negative.)

Basically the xor() method just do mathematical ‘xor’ operation on this BigInteger and the method argument. Remember that xor operation deals with binary. So the xor() method does the conversion internally and perform the mathematical xor and returns the equivalent BigInteger of the result.

Method Syntax

public BigInteger xor(BigInteger val)

Method Argument

Data Type Parameter Description
BigInteger val value to be XOR’ed with this BigInteger.

Method Returns

The xor() method returns this ^ val


Requires Java 1.1 and up

Java BigInteger xor() Example

Below is a java code demonstrates the use of xor() method of BigInteger class. The example presented might be simple however it shows the behavior of the xor() method.


import java.math.BigInteger;
import java.util.Scanner;

 * A java example source code to demonstrate
 * the use of xor() method of BigInteger class

public class BigIntegerXorExample {

	public static void main(String[] args) {	
		// get user input		 
		System.out.print("Enter the first value:");
		Scanner s = new Scanner(;
		String firstInput = s.nextLine();
		System.out.print("Enter the second value:");		
		String secondInput = s.nextLine();
		// convert the first String Input to BigInteger
		BigInteger val1 = new BigInteger(firstInput);
		// convert the second String Input to BigInteger
		BigInteger val2 = new BigInteger(secondInput);
		 *  get the result of xor() operation of first value 
		 *  and second value
		BigInteger val3 = val1.xor(val2);
		System.out.println("Result = "+val3);


This example is a lot simpler than it looks. Basically we ask for user input and converted this value into BigInteger. The two values entered by the user which has been converted to BigInteger is evaluated using the xor() method. The result of the xor operation is printed at the end of the code.

Sample Output

Below is the sample output when you run the above example.

BigInteger xor() example output