Description

On this document we will be showing a java example on how to use the subtract() method of BigInteger Class. Basically this method performs subtraction of this BigInteger and the method argument. The BigInteger doesn’t conform with the normal mathematical operation such as +, -, /,*. Instead of using the mathematical operators, methods such as subtract() were exposed to provide facility of mathematical operations.

Method Syntax

public BigInteger subtract(BigInteger val)

Method Argument

Data Type Parameter Description
BigInteger val value to be subracted to this BigInteger.

Method Returns

The subtract(BigInteger val) method returns a BigInteger whose value is (this – val).

Compatibility

Requires Java 1.1 and up

Java BigInteger subtract() Example

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

package com.javatutorialhq.java.examples;

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

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

public class BigIntegerSubtractExample {

	public static void main(String[] args) {	
		
		// get user input		 
		System.out.print("Enter the minuend:");
		Scanner s = new Scanner(System.in);
		String firstInput = s.nextLine();
		System.out.print("Enter the subtrahend:");		
		String secondInput = s.nextLine();
		s.close();
		
		// convert the first String Input to BigInteger (minuend)
		BigInteger minuend = new BigInteger(firstInput);
		// convert the second String Input to BigInteger (subtrahend)
		BigInteger subtrahend = new BigInteger(secondInput);
		/*
		 *  get the result of andNot operation of first value 
		 *  and second value
		 */
		BigInteger difference = minuend.subtract(subtrahend);
		System.out.println("Difference = "+difference);

		
	}

}

This example is a lot simpler than it looks. Basically we ask for two values from user. The first one would be the minuend and the second one would be the subtrahend. The difference is derived using the method subtract.

Sample Output

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

BigInteger subtract() example output