Store the Largest Number You Can in Java

Yes, you can store the largest number YOU can think of. So, what is the largest number that came into your mind, right now? Think of adding it, subtracting it, multiplying or at least dividing it with something? I am so curious about this. Aren't you?

So, let's have some questions, what is the maximum number a long type variable can store? It is 263 - 1, signed. In Java SE 8, for unsigned long it is 264 - 1. Now I do need big numbers than that? Why suspense? You might already have looked into the program, by the time you are reading this? Am I right?

But wait, let us know at least a bit about the java.math.BigInteger class. One of its constructors takes a String as parameter which I'll use in the program for now. That string can contain the largest number you want, it is on which operations are done. Just as in the String class, operations on BigInteger cannot take place on itself, instead a new BigInteger object is created as a result.

import java.math.*;
class BigInt
{
    public static void main(String args[])
    {
        BigInteger b=new BigInteger("99983938302383039");
      
        // print the value
        System.out.println("The value is "+b);
      
        // To add value
        // A new value is returned but the original
        // isn't modified, just as in String
        System.out.println("Sum "+b.add(new BigInteger("90908977686")));
      
        // To subtract
        // calling big integer - parameter big int
        System.out.println("Difference "+b.subtract(new BigInteger("1000000")));
      
        // To multiply
        // calling * parameter
        System.out.println("Product "+b.multiply(new BigInteger("1000000")));
      
        // To divide
        // calling / parameter
        System.out.println("Division "+b.divide(new BigInteger("10000000000000000")));
      
        // To power, for this time only int, now with BigInteger :(
        System.out.println("Power "+b.pow(10));
    }
}

There are still a lot of methods in the BigInteger class that you need to explore. Check out other articles in this blog, there are over 300+, there will at least be 50 which WILL help you in the future.

Please share this post, if you got what you are here for.


Posted by at on

Tags: Playing with Numbers,