Java has eight primitive types, and choosing the wrong one is a quiet source of bugs. A counter overflows at the wrong moment. A price loses its cents. A character is stored as a number when you expected text. There are only eight of them, so it is worth learning all eight properly.
This is the first lesson in the module, and the next lesson in this module is about "How Do Variables, Constants and var Work in Java?", which covers how you declare a value and give it a name.
What are the eight primitive types?
Four of them hold whole numbers of different sizes. Two of them hold numbers with a fraction. One of them holds a single text character. And one of them holds either true or false. That is the whole list.
public class Sizes {
public static void main(String[] args) {
System.out.println("byte : " + Byte.MIN_VALUE + " .. " + Byte.MAX_VALUE);
System.out.println("short : " + Short.MIN_VALUE + " .. " + Short.MAX_VALUE);
System.out.println("int : " + Integer.MIN_VALUE + " .. " + Integer.MAX_VALUE);
System.out.println("long : " + Long.MIN_VALUE + " .. " + Long.MAX_VALUE);
System.out.println("float : " + Float.MIN_VALUE + " .. " + Float.MAX_VALUE);
System.out.println("double : " + Double.MIN_VALUE + " .. " + Double.MAX_VALUE);
System.out.println("char : " + (int) Character.MIN_VALUE + " .. " + (int) Character.MAX_VALUE);
System.out.println("boolean: " + Boolean.FALSE + " .. " + Boolean.TRUE);
}
}
Two of those lines look noisy on purpose. The char line prints numbers, because a char really is a number underneath. Every other line prints the way that you would expect.
Which type should I use for whole numbers?
int is the default, and it is the right answer more often than people expect. It holds roughly two billion in each direction. That is enough for counters, for array indexes, for timestamps measured in seconds, and for almost every quantity that you will ever hold.
byte and short exist for tables that use a lot of memory and for values that come out of a binary file. long is for identifiers, for timestamps measured in nanoseconds, and for anything that honestly goes past the range of an int.
long requestId = 8_000_000_000L; // the L suffix makes it a long literal
int count = 2_000_000_000; // still fits in an int
short small = 32000; // fits in a short
int overflow = 2147483647 + 1; // wraps around to a negative number
System.out.println(overflow);
Java wraps around when a whole number gets too large, and it does not throw an error. That is why the last line prints a negative number instead of failing. For money, and for anything that must not change quietly, keep the value in a long that holds the small unit, such as cents instead of pounds, or use a type that was built for money.
What about numbers with a fraction?
float and double store binary approximations of decimal numbers, and that is the reason that money and floating point do not mix well together. double is the default, and it is the only sensible choice for ordinary arithmetic. float uses half as much memory, and it is occasionally required by an interface that you do not control.
double total = 0.1 + 0.2;
System.out.println(total); // 0.30000000000000004
System.out.println(total == 0.3); // false
System.out.println(Math.abs(total - 0.3) < 1e-9); // true
System.out.printf("%.2f%n", total); // 0.30
The first line is not a bug in Java. It is a fact about binary floating point, because 0.1 has no exact representation in binary, so the sum lands a tiny distance away from 0.3. This is why comparing floating point numbers with == is almost always wrong. Compare them with a small tolerance instead, or format the value for display, which is what the last two lines do.
Why is char not a number?
A char holds a single UTF-16 code unit. You write it with single quotes. Doing arithmetic on it surprises people, because adding to a char gives you an int, since the compiler has to promote it before it can do the sum.
char initial = 'A';
int code = initial + 1; // 66
char next = (char) (initial + 1); // 'B', and the cast is required
System.out.println(initial + next); // 131, not AB
System.out.println("" + initial + next); // AB
Look at the empty string in the last line. Without it, the + would do arithmetic instead of joining text together. Also notice that a char holds only one code unit, so characters outside the basic multilingual plane, and many emoji, need two char values to represent them. For ordinary text, use a String instead.
What about booleans?
A boolean holds either true or false, and it cannot be turned into a number. In some older languages you will see 0 and 1 standing in for false and true. Java does not allow that, and that strictness removes a whole family of comparison bugs.
boolean ready = true;
if (ready) {
System.out.println("starting");
}
// int flag = 1; // does not compile: incompatible types
How do I choose?
- Counters, indexes and most whole numbers: use int.
- Identifiers, timestamps in nanoseconds and very large quantities: use long.
- Measurements and general arithmetic: use double.
- Money: keep the value in a long that holds the small unit, or use a type built for money.
- Text: use String, and not an array of char values.
- A yes or a no: use boolean.
One more thing is worth knowing. Every primitive type has a matching object form. The object form of int is Integer, and the same is true for all of the others. Java converts between the two forms on its own when it needs to, which is the reason an int can be added to a list of objects without any complaint. That automatic conversion is called autoboxing, and it is the bridge between the simple types and the parts of the standard library that work with objects.
Why do the defaults matter?
Two defaults shape most of the Java code that you will read. A whole number literal is an int, so long x = 5; needs no cast while int y = 5L; does not compile. And a number with a decimal point is a double, which is why float f = 0.5f; carries an f suffix.
Both defaults are on purpose. The wider type is the one that is rarely wrong, and widening costs nothing.
int a = 5; // int
long b = 5; // long, widened from an int literal
long c = 5L; // long, stated explicitly
double d = 0.5; // double
float e = 0.5f; // float, stated explicitly
short s = 5; // short, narrowed only because the target says so
The rule to remember is this. A literal takes the narrowest type that can hold it, and a variable takes the type that you wrote down. When those two disagree, the compiler either widens the value for free or asks you for an explicit cast.
Quick reference
- There are eight primitives: byte, short, int, long, float, double, char and boolean.
- int is the default, and a long literal needs an
Lsuffix. - Whole number overflow wraps around quietly, so size your types on purpose.
- Never compare floating point numbers with ==. Use a tolerance instead.
- A char is a number in disguise, and it holds one code unit.
- Primitives box themselves into their object forms automatically.
Try it yourself: write a program that prints the smallest and largest value of each primitive using the constants above. Then work out a total price as a double and print it with two decimal places. Finally, add 0.1 + 0.2 to the total and print the raw value, so that you can see the representation error appear in your own output.