AP® Computer Science A · Unit 1 · Topic 1.2

int, double, and boolean

int, double, and boolean are three primitive types in Java, each reserving a different amount of memory and holding a different kind of value: whole numbers, decimal numbers, and true/false.

Java is statically typed, which means every variable declares its type before it ever holds a value. That promise tells the compiler exactly how much memory to set aside and what operations make sense. An int reserves 4 bytes for a whole number, a double reserves 8 bytes for a number with a fractional part stored in a binary approximation of decimal form, and a boolean holds only true or false, nothing numeric at all. The compiler uses this upfront information to catch mistakes before the program ever runs, like trying to add a boolean to a number.

You can usually tell a literal's type just by looking at it. 42 has no decimal point, so it is an int. 3.14 has a decimal point, so it is a double. true is one of exactly two boolean values. This matters because 5 and 5.0 are not interchangeable to Java: 5 is stored as an exact integer, while 5.0 is stored as a double, using a completely different bit pattern and a different amount of memory, even though they represent the same mathematical value.

This sets up the next idea: when an int and a double meet in an expression, Java promotes the int to a double so no decimal information gets lost, which is why 0.1 plus 0.2 prints something like 0.30000000000000004 instead of a clean 0.3. That odd output is not a bug. It is a preview of how binary storage of decimals works, a thread that keeps running through later topics on expressions and casting.

Key terms

primitive type
A basic data type built into Java, like int, double, or boolean, that stores a raw value rather than an object reference.
static typing
A language rule requiring every variable's type to be declared and fixed before the program runs.
literal
A fixed value written directly in code, such as 42, 3.14, or true.
type promotion
Java's automatic conversion of a smaller or less precise type, like int, to a larger one, like double, within an expression.

Watch it explained

  1. How it worksHow do int, double, and boolean take up different room in memory and hold different things?
  2. Worked exampleFind which of int, double, and boolean fits each of 42, 3.14, and true.
  3. Common mistakeWhy isn't 5 the same value to Java as 5.0?
  4. Going furtherWhat changes when you store 0.1 plus 0.2 in a double and then print it?

Check yourself

Your turn1 of 2
Which declaration correctly matches each value to its natural Java type: 42, 3.14, true?

End of topic.