Java Numbers
Numbers in Java come in two flavours: integer types for whole numbers and floating-point types for values with a decimal point. Picking the right one keeps your maths both accurate and efficient.
Integer numbers
Integer types hold whole numbers with no fractional part. The four integer types are byte, short, int, and long, differing only in how much they can store. In almost all everyday code you will reach for int, and switch to long only when the numbers grow beyond about two billion.
Working with integers
public class Main {
public static void main(String[] args) {
int population = 1500000;
long distanceToSun = 149600000000L;
System.out.println(population);
System.out.println(distanceToSun);
}
}Floating-point numbers
When you need decimals, use a floating-point type: float or double. A double has roughly twice the precision of a float and is the default choice for decimal work. A float literal must end with an f to tell Java you really mean the smaller type.
Floats and doubles
public class Main {
public static void main(String[] args) {
float temperature = 21.5f;
double pi = 3.14159265;
System.out.println(temperature);
System.out.println(pi);
}
}Integer division versus decimal division
This trips up almost every beginner. When you divide two integers, Java throws away the remainder and gives you a whole number. To get a decimal result, at least one of the values must be a floating-point type.
The division surprise
public class Main {
public static void main(String[] args) {
int a = 7 / 2; // 3, the remainder is dropped
double b = 7.0 / 2; // 3.5, decimal division
System.out.println(a);
System.out.println(b);
}
}Choosing a number type
- You may add underscores to long numbers for readability, such as 1_500_000.
- Use int and double unless you have a clear reason not to.
- Never use double for money; small rounding errors add up. Use BigDecimal instead.
- Integer overflow wraps around silently rather than crashing, so give a growing value enough room.