Chapter 5. Numbers

5.0 Introduction

Numbers are basic to just about any computation. They’re used for array indices, temperatures, salaries, ratings, and an infinite variety of things. Yet they’re not as simple as they seem. With floating-point numbers, how accurate is accurate? With random numbers, how random is random? With strings that should contain a number, what actually constitutes a number?

Java has eight built-in, or primitive types, seven of which can be used to represent numbers, summarized in Table 5-1 with their wrapper (object) types, as well as two numeric classes that do not represent primitive types. The eighth primitive, boolean and its wrapper Boolean, aren’t numeric and can’t be treated as such. Note that unlike languages such as C or Perl, which don’t specify the size or precision of numeric types, Java—with its goal of portability—specifies these exactly and states that they are the same on all platforms.

Table 5-1. Numeric types
Built-in type Object wrapper Size of built-in (bits) Contents

byte

Byte

8

Signed integer

short

Short

16

Signed integer

int

Integer

32

Signed integer

long

Long

64

Signed integer

float

Float

32

IEEE-754 floating point (single precision)

double

Double

64

IEEE-754 floating point (double precision)

char

Character

16

Unsigned Unicode character

n/a

BigInteger

unlimited

Arbitrary-size immutable integer value

n/a

BigDecimal

unlimited

Arbitrary-size-and-precision immutable floating-point value

As you can see, Java ...

Get Java Cookbook, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.