Chapter 5. Numbers

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 several built-in or “primitive” types that can be used to represent numbers, summarized in Table 5-1 with their “wrapper” (object) types, as well as some numeric types that do not represent primitive types. 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 typeObject wrapperSize 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

double

Double

64

IEEE-754 floating point

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 provides a numeric type for just about any purpose. There are four sizes of signed integers for representing various sizes of whole numbers. There are two sizes of floating-point numbers to approximate real numbers. There ...

Get Java Cookbook, 3rd 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.