Whole numbers: int and long
16 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A whole number has no decimal point, like 85, 0 or -3. Java stores whole numbers in int, or in long when they are very big.
int: the usual whole number
Marks, age, cricket runs and class sizes are whole numbers, and none of them gets near a billion. For values like these, Java programmers use int almost every time.
Example 1 · Add whole numbers
public class Runs { public static void main(String[] args) { int firstInnings = 287; int secondInnings = 254; int totalRuns = firstInnings + secondInnings; int temperature = -3; System.out.println("Total runs: " + totalRuns); System.out.println("Temperature: " + temperature); }}Total runs: 541 Temperature: -3
What this code does
- Between two numbers,
+adds them, sototalRunsstores 541. - An
intholds negative numbers too, like-3. - An
intholds numbers from about minus 2.1 billion to plus 2.1 billion; the exact largest value is2147483647.
long: for very big numbers
The world population is about 8 billion, which is more than an int can hold: int people = 8000000000; does not compile. A long holds numbers up to about 9 billion billion.
Example 2 · Numbers past 2.1 billion
public class Population { public static void main(String[] args) { long worldPopulation = 8000000000L; long totalViews = 2100000000L + 900000000L; System.out.println("World population: " + worldPopulation); System.out.println("Total views: " + totalViews); }}World population: 8000000000 Total views: 3000000000
What this code does
- A whole-number literal such as
85is anintby default. So a literal past theintrange needsLat the end:8000000000L. Without theL, the error isinteger number too large. - The total, 3 billion, is past the
intrange too, so it is stored in along. TheLis not printed.
L. A small l looks like the digit 1.byte and short: the smaller boxes
Java has two smaller whole-number types too. Memory is measured in bytes (one byte is 8 bits, 0s and 1s), and each type uses a fixed number of them. More bytes hold bigger numbers.
byte and short save memory but do not make code faster, and beginners rarely need them: use int unless you have a reason. Type a number in the meter below and see which boxes it fits in.
Experiment
Range meter
Type a whole number. Each line says whether it fits in that type.
- fits in byte?
- false
- fits in short?
- false
- fits in int?
- true
- largest int
- 2147483647
byte big = 200; gives incompatible types: possible lossy conversion from int to byte.Underscores make big numbers easy to read
Is 2500000000 250 million or 2.5 billion? In Java you can put _ between the digits, the way you would add commas in normal writing.
public class BigViews { public static void main(String[] args) { long views = 2_500_000_000L; System.out.println(views); }}2500000000
Java ignores the underscores: it is the same number, and they do not appear when you print it.
Next step
Check your understanding
8 quick questions