BigInteger Basic Math Tutorial

In this tutorial I am going to discuss the .add(), subtract(), multiply(), and divide() methods. The basic arithmetic operators +,-,*, and / do not work with BigInteger objects. Because you are working with immutable objects, you must invoke methods on a BigInteger object in order to get back a reference to a new BigInteger object containing the result. Just a heads up, the .divide() method should rarely, if ever, be used. I will discuss the reason why in the video. Let's get started...



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md BIBasicMath
C:\Java>cd BIBasicMath
C:\Java\BIBasicMath>Notepad BIBasicMath.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


import java.math.*;

class BIBasicMath {

    public static void main(String args[]) {
		
        BigInteger biOne = new BigInteger("10000000000000000000000000000000000000000");
        BigInteger biTwo = new BigInteger("2222222222222222222222222222222222222222");
        BigInteger biFive = new BigInteger("5");

        BigInteger biResult = biOne.add(biTwo);
        System.out.println("biResult = " + biResult + "\n");
 
        biResult = biOne.subtract(biTwo);
        System.out.println("biResult = " + biResult + "\n");

        biResult = biOne.multiply(biFive);
        System.out.println("biResult = " + biResult + "\n");

        biResult = biOne.divide(biFive);
        System.out.println("biResult = " + biResult + "\n");

        biResult = biOne.divide(new BigInteger("3")); // use .divideAndRemainder() instead
        System.out.println("biResult = " + biResult + "\n");
    }
}

Now switch back to the command prompt (CMD) and type in javac BIBasicMath.java and press Enter.
Now type in java BIBasicMath and press Enter.


C:\Java\BIBasicMath>javac BIBasicMath.java
C:\Java\BIBasicMath>java BIBasicMath
See video for results and more...


Final thoughts

Stay tuned for my next tutorial where I will discuss the .divideAndRemainder(), toString(), toString(int radix), and the compareTo() methods.


Tutorials