Card 04/ 09
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.
| Type | Holds | Size | Default in a field |
|---|---|---|---|
boolean | true or false | one bit of meaning | false |
byte | −128 to 127 | 8 bits | 0 |
short | about ±32 thousand | 16 bits | 0 |
int | about ±2.1 billion | 32 bits | 0 |
long | about ±9.2 quintillion | 64 bits | 0L |
float | decimals, roughly 7 digits | 32 bits | 0.0f |
double | decimals, roughly 15 digits | 64 bits | 0.0 |
char | one character | 16 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.
← → move through sections and cards