Primitives
int, long, double, boolean, and why char is not a string.
A primitive holds the value itself, not a reference. int is an integer up to roughly two billion; long is larger and takes the suffix L. double is an approximate number with a decimal point: 0.1 + 0.2 does not have to be exactly 0.3. Money is not counted in double. boolean is only true or false, with no numbers in their place, unlike old C.
char is a single UTF-16 character, not a string. Text of several letters is a String, and String is already an object. Adding an int to an int gives an int: 5 / 2 equals 2, and the fractional part is dropped. If you need a double, one of the operands must be a double: 5 / 2.0.
You cannot read a local variable until it has been assigned. A field of a primitive type becomes zero or false on its own. This difference shows up later in constructors: a forgotten field silently equals 0 rather than "empty".
Choose the narrowest type you actually need. long for an identifier, int for a counter, boolean for a flag. Do not start a service with double for everything: rounding errors cannot be fixed with an if later.
Practice
Integer division
What does the expression 5 / 2 equal as an int?
- 2.5
- 2
- 3
- a compile error
The long suffix
What suffix goes on a long literal? One letter.
Clamp to a range
Write static int clamp(int n, int lo, int hi): return n, but not less than lo and not greater than hi.