Core Module
12 min forge

Java Data Types

Understanding primitives vs wrapper classes and memory allocation.

Java Data Types

πŸ“˜ What is it

Java is a statically typed language, meaning all variables must be declared before they can be used. It has two categories of data types: Primitives and Reference Types.

🧠 Primitive Types

These are predefined by the language and named by a keyword.

  • int (4 bytes), long (8 bytes)
  • float (4 bytes), double (8 bytes)
  • char (2 bytes, Unicode)
  • boolean (true/false)
  • byte (1 byte), short (2 bytes)

πŸ—οΈ Reference Types (Wrapper Classes)

Reference types are objects that wrap primitive types.

  • Integer, Long, Double, Character, Boolean
  • Autoboxing: Automatic conversion from primitive to wrapper (e.g., int to Integer).
  • Unboxing: Automatic conversion from wrapper to primitive.

πŸ’» Code example

java Standard
int primitiveInt = 10; Integer wrapperInt = primitiveInt; // Autoboxing double price = 19.99; Double wrappedPrice = price; System.out.println("Max Integer: " + Integer.MAX_VALUE);

❌ Common mistakes

  • Precision Loss: Using float for monetary values (use BigDecimal instead).
  • NullPointerException: Forgetting that wrapper classes can be null, while primitives cannot.
  • Reference Equality: Using == instead of .equals() when comparing wrapper objects like Integer.