Data Types: Choosing the Right Box
Brew Bar's program now needs to remember things: how many cups were ordered, what a latte costs, whether the customer has a loyalty card. Java insists that you say what kind of value each thing is before you store it. Choose well and the compiler protects you; choose badly and you get strange rounding or a refusal to compile.
The rule
Eight primitive types hold plain values; everything else is a reference.
The eight primitive types store the value itself:
| Type | Holds | Brew Bar example |
|---|---|---|
int |
whole numbers up to about ±2.1 billion | int cups = 3; |
long |
much larger whole numbers, suffix L |
long allTimeCups = 4_500_000_000L; |
double |
numbers with a fraction | double tempC = 68.5; |
float |
smaller, less precise fractions, suffix f |
float rating = 4.5f; |
boolean |
true or false |
boolean hasCard = true; |
char |
one character, in single quotes | char size = 'L'; |
byte, short |
small whole numbers, to save memory | rarely needed |
Anything else, such as text, arrays or your own classes, is a reference type: the variable holds a reference that points to an object somewhere else in memory. The one you will use constantly is String, written in double quotes:
String drink = "Flat white";
int priceCents = 320;
boolean iced = false;Notice priceCents. Brew Bar stores money as a whole number of cents, because double cannot represent most decimal fractions exactly: 0.1 + 0.2 prints 0.30000000000000004. For money, use cents in an int or long, or the BigDecimal class.
Two defaults explain many compile errors. A whole-number literal such as 42 is an int. A literal with a decimal point, such as 4.5, is a double. That is why long values beyond the int range need an L, and float values need an f. Underscores, as in 4_500_000_000L, are allowed purely for readability.
The shortcut
Ask "What does this value look like?" and read the answer off:
- a count →
int(longif it could pass two billion) - a measurement with a fraction →
double - yes or no →
boolean - exactly one character →
char, single quotes - words →
String, double quotes
Number of cups
A small count:
int cups = 2;
Drills
Answer fast — trust the rule.
Why does char size = "L"; fail to compile?
Which of these is NOT a primitive type?
What happens with float rating = 4.5;?
Which line compiles?
Remember
- Eight primitives hold values;
String, arrays and objects are references. - Ask what the value looks like: count, fraction, yes or no, one character, words.
- Traps:
doublefor money,"L"versus'L', and missingLorfsuffixes.
