Concept Explanation
In Java, we have to be careful about how much memory we use. It's like choosing the right size box to ship a gift. If you're shipping a single ring, you don't use a refrigerator box!
Java provides 8 Primitive Types for basic data, and Reference Types for complex objects.
The 8 Primitives
| Category | Type | Size | range |
|---|---|---|---|
| Wholes | byte | 1 byte | -128 to 127 |
short | 2 bytes | -32,768 to 32,767 | |
int | 4 bytes | ~2 Billion | |
long | 8 bytes | Massive (use L suffix) | |
| Decimals | float | 4 bytes | 6-7 digits (use f suffix) |
double | 8 bytes | 15 digits (Preferred) | |
| Logic | boolean | 1 bit | true / false |
| Text | char | 2 bytes | single Unicode character |
Common Mistakes
- The Floating 'f': Writing
float price = 10.50;will error. You MUST write10.50f. Java defaults all decimals todouble. - The Long 'L': Same for long:
long count = 9000000000L;. - String vs char: Using double quotes for characters (
char c = "A";) is wrong. Char uses single quotes ('A').
Best Practices
- Default to 'int' and 'double': Unless you have a specific reason (like very low memory), stick to these two for numbers.
- Precision over size: Always use
doublefor currency or scientific math to avoid rounding errors common infloat.
Practice Exercises
- The Memory Counter: Research why a
byteonly goes up to 127. Hint: It has to do with "Bits" and "Binary." - The Precise Scientist: Calculate the area of a circle using
floatand thendouble. Print both results to see the difference in precision. - The Type Matcher: Write a list of 5 real-world items (Temperature, Distance to Mars, Is Valid, Grade, Item Count) and identify the perfect Java type for each.