Java Numbers
Java numbers are the numeric values a program counts and measures with. Whole numbers use int or long, and decimal numbers use float or double.
Whole numbers
The int variable holds a small count. The long variable holds a large distance.
public class Main {
public static void main(String[] args) {
int count = 25;
long distance = 9000000000L;
System.out.println(count);
System.out.println(distance);
}
}Decimal numbers
The float variable carries the letter f. The double variable holds a price with two decimal places.
public class Main {
public static void main(String[] args) {
float temperature = 36.5f;
double price = 19.99;
System.out.println(temperature);
System.out.println(price);
}
}Scientific notation
The first value uses e3 and prints as 3500.0. The second value uses e-2 and prints as 0.025.
public class Main {
public static void main(String[] args) {
double big = 3.5e3;
double small = 2.5e-2;
System.out.println(big);
System.out.println(small);
}
}Example
public class Main {
public static void main(String[] args) {
int items = 120;
long totalItems = 4500000000L;
double length = 2.5e2;
System.out.println(items);
System.out.println(totalItems);
System.out.println(length);
}
}Key points
- int holds whole numbers in the range most programs need.
- long holds larger whole numbers and its values carry the letter L.
- double holds decimal numbers with more precision.
- float holds decimal numbers and its values carry the letter f.
- Scientific notation writes a number with the letter e.
- In 3.5e3, the e3 part moves the decimal point three places.
In this example, an int holds a count of 120 and a long holds a much larger count. The length variable uses scientific notation with e2. The value 2.5e2 prints as 250.0.
Note
A decimal value with no letter is a double by default.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does the value 3.5e3 print as?