Java BigInteger is Immutable.

Big integer in java is a get around of solving problems that requires numbers bigger than the long datatype can hold. One thing that one should know about these numbers is that they are Immutable. That means once you perform an operation on them, you have to assign the result back to the same variable.

Here is an example.


Java Program to add two big integer – Wont work as expected.


import java.math.BigInteger;
public class AddBigInteger{
public static void main(String [] args){
BigInteger sum = new BigInteger("0");
BigInteger num1 = new BigInteger("10");
BigInteger num2 = new BigInteger("20");
sum.add(num1);
sum.add(num2);
System.out.println(sum.toString());
}
}

Java Program to add two big integer – How it should be done.


import java.math.BigInteger;
public class AddBigInteger{
public static void main(String [] args){
BigInteger sum = new BigInteger("0");
BigInteger num1 = new BigInteger("10");
BigInteger num2 = new BigInteger("20");
sum = sum.add(num1);
sum = sum.add(num2);
System.out.println(sum.toString());
}
}

Keep coding. Have a nice day!!!

Leave a Reply

Your email address will not be published. Required fields are marked *