Card 04/ 09
All 9 cards
ConceptDifficulty: Beginner1 min
The Eight Types Everything Else Is Built From
You need to store someone's age, their account balance, and whether they have confirmed their email address. Three quantities, three different sizes, and Java makes you say which before it will store any of them.
There are exactly eight types that hold a value directly. Everything else in Java is an object built on top of them.
| 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 holds before anyone assigns it — a field is always initialised, always to the value above.
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.