Sub topic 4
Whole Numbers: byte, short, int, and long
Java has four types for integer values, such as -5, 0, and 42. A type says what kind of value a variable can hold. A variable is a named place to store a value.
The four integer types are byte, short, int, and long. They differ in how large or small their values can be. All four can hold negative values.
Sizes and ranges
Each type uses a fixed number of bits. A bit is a unit of information that can be 0 or 1. More bits allow a wider range of values.
| Type | Bits | Smallest value | Largest value |
|---|---|---|---|
| `byte` | 8 | -128 | 127 |
| `short` | 16 | -32,768 | 32,767 |
| `int` | 32 | -2,147,483,648 | 2,147,483,647 |
| `long` | 64 | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
The commas make the numbers easier to read in this table. Do not put commas inside a number in Java code.
A worked example
This program stores four counts. It then adds one to the number of visits and prints all four values.
Save the code in a file named WholeNumbers.java:
class WholeNumbers {
public static void main(String[] args) {
byte chairs = 100;
short seats = 20000;
int visits = 2000000;
long totalVisits = 8000000000L;
visits = visits + 1;
System.out.println(chairs);
System.out.println(seats);
System.out.println(visits);
System.out.println(totalVisits);
}
}Run these commands from the folder containing the file:
javac WholeNumbers.java
java WholeNumbersThe program prints these values, one per line:
1002000020000018000000000
Each first line inside main creates a variable and gives it a value. For example, int visits = 2000000; creates an int variable named visits. The later line reads its value, adds one, and stores the result back in visits.
Why does the long value have an L?
A literal is a value written directly in code. For example, 100 is an integer literal.
Java normally treats a whole-number literal without a suffix as an int. A suffix is a character added to the end. Add L to write a long literal, as in 8000000000L. This matters here because eight billion is too large for an int.
Choosing a type
For most whole-number values, start with int. Choose long when the value may be outside the int range. Use byte or short when a program needs those smaller types.
A value must fit its type. For example, Java rejects byte chairs = 128; because the largest byte value is 127.
Calculations also have limits. If an integer calculation produces a result outside its type’s range, it can overflow: the stored result wraps around instead of holding the expected value. Choose a type that can hold the results you expect, not just the starting values.
Exercise
You need a variable named distance to hold 3000000000. Which type should you use, and how would you create the variable?
Show answer
Use long: long distance = 3000000000L; The value is too large for int.