2.2. Integer Data Types

There are four types of variables that you can use to store integer data. All of these are signed; that is, they can store both negative and positive values. The four integer types differ in the range of values they can store, so the choice of type for a variable depends on the range of data values you are likely to need.

The four integer types in Java are:

Data TypeDescription
byteVariables of this type can have values from −128 to +127 and occupy 1 byte (8 bits) in memory
shortVariables of this type can have values from −32768 to 32767 and occupy 2 bytes (16 bits) in memory
intVariables of this type can have values from −2147483648 to 2147483647 and occupy 4 bytes (32 bits) in memory
longVariables of this type can have values from −9223372036854775808 to 9223372036854775807 and occupy 8 bytes (64 bits) in memory

Although I said the choice of type depends on the range of values that you want to be able to store, in practice you'll be using variables of type int or type long to store integers most of the time, for reasons that I'll explain a little later. Let's take a look at declarations of variables of each of these types:

byte smallerValue;
short pageCount;
int wordCount;
long bigValue;

Each of these statements declares a variable of the type specified.

The range of values that can be stored by each integer type in Java, as shown in the preceding table, is always the same, regardless of what kind of computer you are using. This is also true of the other ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 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.