Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 3 ■ DATA TYPES


Table 3-1. Integer primitives

Type Bits Minimum Value Maximum Value

byte 8 -128 127

short 16 -32768 32767

int 32 -2,147,483,648 2,147,483,647

long 64 -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Do you need even bigger numbers? Real-world applications sometimes need numbers even bigger
than the maximum value of long. In those cases, Java provides a class called BigInteger. A number
represented by a BigInteger object can be of any size, because the BigInteger class allocates enough
bytes to store a representation of any number. It's a little tricky to use and operations on BigInteger
objects are slow, but it's sometimes the only way. BigInteger is not a primitive.

Real Primitives


Real numbers have decimal points and values after the decimal point. Even if that value is 0, and even if
you didn't type a decimal point and anything after it, the decimal point and the zeros after it are there
behind the scenes. They must exist so that operations on the value can compare to the full value, so the
JVM (the Java Virtual Machine, which is the program that runs your programs) fills them in even if you
don't.

■ Note 0 and 0.00 are different values in Java. To the average person, they both mean zero. To a scientist or
mathematician, the one indicates greater precision than the other, but they still both mean zero. But to a compiler,
they are different data types and have nothing to do with one another.

Java supports two real primitives, float and double. float gets its name from the idea of a floating
point number. The decimal point can move, so it's said to “float.” double gets its name because it takes
twice the storage space of a float. Table 3-2 shows the details of float and double.

Table 3-2. Real primitives

Type Bytes Minimum Value Maximum Value

float 4 1.40129846432481707e-45 3.40282346638528860e+38

Again, sometimes even that isn't enough. For those cases, Java provides a class called BigDecimal. As
with BigInteger, it can be tricky to use, and operations on it are slow. But when you absolutely have to
have a number bigger than a double, use BigDecimal. As with BigInteger, BigDecimal is not a primitive.
Free download pdf