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 |
|
|
1 |
–128 to +127 |
|
|
2 |
–32,768 to +32,767 |
|
|
4 |
–2 billion to +2 billion |
|
|
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.
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;
long xLong = 58473882;
xLong = 58_473_882;
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access