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.,
inttoInteger). - Unboxing: Automatic conversion from wrapper to primitive.
π» Code example
java Standardint 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
floatfor monetary values (useBigDecimalinstead). - NullPointerException: Forgetting that wrapper classes can be
null, while primitives cannot. - Reference Equality: Using
==instead of.equals()when comparing wrapper objects likeInteger.