Data Types: The 8 Primitives

Data Types: The 8 Primitives in Java: 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.

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

CategoryTypeSizerange
Wholesbyte1 byte-128 to 127
short2 bytes-32,768 to 32,767
int4 bytes~2 Billion
long8 bytesMassive (use L suffix)
Decimalsfloat4 bytes6-7 digits (use f suffix)
double8 bytes15 digits (Preferred)
Logicboolean1 bittrue / false
Textchar2 bytessingle Unicode character

Common Mistakes

  1. The Floating 'f': Writing float price = 10.50; will error. You MUST write 10.50f. Java defaults all decimals to double.
  2. The Long 'L': Same for long: long count = 9000000000L;.
  3. 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 double for currency or scientific math to avoid rounding errors common in float.

Practice Exercises

  1. The Memory Counter: Research why a byte only goes up to 127. Hint: It has to do with "Bits" and "Binary."
  2. The Precise Scientist: Calculate the area of a circle using float and then double. Print both results to see the difference in precision.
  3. 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.