Skip to the workspace
Pebellslearn by building
Java Basics  ›  Lesson

Data Types: Choosing the Right Box

Data Types 12 minJava has eight primitive types that store plain values, such as int, double, boolean and char, while text, arrays and objects are reference types.

java / Data Types: Choosing the Right Box

Explore each scene at your own pace.

01 · The rule

The rule

Data Types: Choosing the Right Box

Java has eight primitive types that store plain values, such as int, double, boolean and char, while text, arrays and objects are reference types.

Choose primitive or reference types from the values and operations a program needs.

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.