Integer Data Types

An integer is a whole number — that is, a number with no fractional or decimal portion. Java has four integer types, which you can use to store numbers of varying sizes.

Type

Number of Bytes

Range of Values

Byte

1

–128 to +127

Short

2

–32,768 to +32,767

Lint

4

–2 billion to +2 billion

Long

8

–4,000 trillion to +4,000 trillion

The most commonly used integer type is int. You can use short or even byte when you know the variable won’t need to store large values, and you can use long when your program will require large values — for example, when calculating the federal deficit.

tip.eps Java allows you to promote an integer type to a larger integer type. In other words, you can assign the value of a shorter integer type to a longer integer variable, like this:

int xInt;

long yLong;

xInt = 32;

yLong = xInt;

Java does not allow the converse, however. The following code is not valid:

int xInt;

long yLong;

yLong = 32;

xInt = yLong;

tip.eps In Java 7, you can include underscores to make longer numbers easier to read. Thus, the following statements all assign the same value to the variable xLong:

long xLong = 58473882;

xLong = 58_473_882;

Get Java For Dummies Quick Reference 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.