Card 04/ 09

ConceptDifficulty: Beginner1 min

Java's Eight Primitive Types

An age, a balance and a yes or no: three sizes, and Java makes you choose before it stores any of them.

Java has exactly eight primitive types, the types that hold a value directly: boolean, byte, short, int, long, float, double and char. Each has a fixed size, which decides what fits, and a default value that a field holds until you assign one.

You need to store someone's age, their account balance, and whether they have confirmed their email address. Three quantities of different sizes, and Java makes you say which type each one is before it will store any of them. Everything else in Java is an object built on top of these eight.

The eight primitive types, their size, and their value before you assign one
TypeHoldsSizeDefault in a field
booleantrue or falseone bit of meaningfalse
byte−128 to 1278 bits0
shortabout ±32 thousand16 bits0
intabout ±2.1 billion32 bits0
longabout ±9.2 quintillion64 bits0L
floatdecimals, roughly 7 digits32 bits0.0f
doubledecimals, roughly 15 digits64 bits0.0
charone character16 bits'\u0000'

Two of those columns matter more than the others. Size decides what fits: an int cannot hold the number of milliseconds since 1970, which is why timestamps are long. Default decides what a field (a variable belonging to an object) holds before anyone assigns it: a field is always initialised, to the value in the table.

So int for whole numbers, long when they get large, double for decimals and boolean for a yes or no covers almost everything you will write. The other four are for when you know exactly why you want them.