Large Numbers


The integer primitive type with the largest range of value is the long, from -263 to 263-1. If you need greater or lesser values, you have to use the BigInteger class in the package java.math. A BigInteger object can represent any integer (as large as the RAM on the computer can hold) as it is not mapped on a primitive type. Respectively, you need to use the BigDecimal class for great decimal numbers.

However, as these perform much slower than primitive types, it is recommended to use primitive types when it is possible.

BigInteger

The BigInteger class represents integers of almost any size. As with other objects, they need to be constructed. Unlike regular numbers, the BigInteger represents an immutable object - methods in use by the BigInteger class will return a new copy of a BigInteger.

To instantiate a BigInteger, you can create it from either byte array, or from a string. For example:

Example Code section 3.23: 1 quintillion, or 10^18. Too large to fit in a long.
1 BigInteger i = new BigInteger("1000000000000000000");

BigInteger cannot use the normal Java operators. They use the methods provided by the class.

Example Code section 3.24: Multiplications and an addition.
1 BigInteger a = new BigInteger("3");
2 BigInteger b = new BigInteger("4");
3 
4 // c = a^2 + b^2
5 BigInteger c = a.multiply(a).add(b.multiply(b));

It is possible to convert to a long, but the long may not be large enough.

Example Code section 3.25: Conversion.
1 BigInteger aBigInteger = new BigInteger("3");
2 long aLong = aBigInteger.longValue;

BigDecimal

The BigInteger class cannot handle decimal numbers. The BigDecimal class represents a floating point value of arbitrary precision. It is composed of both a BigInteger, and a scale value (represented by a 32-bit integer).

Clipboard

To do:
Add some exercises like the ones in Variables


  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.

Java_Programming/Large_numbers
 



 

Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.


Manage research, learning and skills at defaultlogic.com. Create an account using LinkedIn to manage and organize your omni-channel knowledge. defaultlogic.com is like a shopping cart for information -- helping you to save, discuss and share.


  Contact Us