BigInteger add, subtract, multiply and divide
In this chapter you will learn:
- How to add two BigInteger values together
- How to subtract one BigInteger with another BigInteger
- How to multiply two BigInteger values
- How ot divide one BigInteger from another BigInteger
Add two BigInteger values together
BigInteger add(BigInteger val)
returns a BigInteger whose value is (this + val).
import java.math.BigInteger;
/* j a va2s. co m*/
public class Main {
public static void main(String args[]) {
BigInteger n = new BigInteger("1000000000000");
BigInteger one = new BigInteger("1");
n = n.add(one);
System.out.println(n);
}
}
The output:
Subtract one BigInteger with another BigInteger
BigInteger subtract(BigInteger val)
returns a BigInteger whose value is (this - val).
import java.math.BigInteger;
/* j a v a2 s .com*/
public class Main {
public static void main(String[] argv) throws Exception {
BigInteger bi1 = new BigInteger("1234567890123456890");
BigInteger bi2 = BigInteger.valueOf(123L);
bi1 = bi1.subtract(bi2);
System.out.println(bi1);
}
}
The output:
Multiply two BigInteger values
BigInteger multiply(BigInteger val)
returns a BigInteger whose value is (this * val).
import java.math.BigInteger;
/*from j ava 2 s . c om*/
public class Main {
public static void main(String[] argv) throws Exception {
BigInteger bi1 = new BigInteger("1234567890123456890");
BigInteger bi2 = BigInteger.valueOf(123L);
bi1 = bi1.multiply(bi2);
System.out.println(bi1);
}
}
The output:
Divide one BigInteger from another BigInteger
BigInteger divide(BigInteger val)
returns a BigInteger whose value is (this / val).
import java.math.BigInteger;
// j a va 2 s . co m
public class Main {
public static void main(String[] argv) throws Exception {
BigInteger bi1 = new BigInteger("1234567890123456890");
BigInteger bi2 = BigInteger.valueOf(123L);
bi1 = bi1.divide(bi2);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » BigDecimal BigInteger