Java Study Chapter ยท Official ReferenceAfzaal Suleman Knowledge Base
In Java, int is a primitive data type that stores raw integer values directly in memory, while Integer is a wrapper class that wraps an int value into an object. This fundamental difference affects memory usage, nullability, and performance in your applications.
Key Differences
- Memory: int uses 4 bytes of memory; Integer uses additional memory for object overhead
- Nullability: int cannot be null; Integer can be null
- Performance: int is faster for arithmetic operations
๐ป
Code Demonstration & Syntax
java
// Primitive type
int primitiveNum = 100;
// Wrapper Class object
Integer wrapperNum = Integer.valueOf(100);
System.out.println("Primitive: " + primitiveNum);
System.out.println("Wrapper: " + wrapperNum);Output
Primitive: 100 Wrapper: 100
๐
Chapter Rules & Key Notes
๐ก
Remember This
- Primitive data types use lowercase (int), wrapper classes use capital letters (Integer)
- int is stored on stack, Integer is stored on heap
- Integer provides utility methods like parseInt(), toString()
๐
Important Rules
- String starts with a capital S because it is a class, not a primitive
- Always use Integer when you need nullability (e.g., database fields)
- Use int for high-performance arithmetic operations
โ ๏ธ
Common Mistakes
- Comparing Integer objects with == instead of .equals() for values outside -128 to 127
- Forgetting to handle NullPointerException when unboxing null Integer
- Using Integer in tight loops where performance is critical
โฆโฆโฆ