Int vs Integer in Java: Key Differences and Usage Guide
int is a primitive data type in Java used to store simple integer values, while Integer is a wrapper class that encapsulates an int in an object. Use int for efficient, simple number storage and Integer when you need objects, such as in collections or when null values are required.Quick Comparison
Here is a quick side-by-side comparison of int and Integer in Java.
| Feature | int | Integer |
|---|---|---|
| Type | Primitive data type | Wrapper class (Object) |
| Memory | Stores 4 bytes directly | Object with additional overhead |
| Nullability | Cannot be null | Can be null |
| Usage in Collections | Not allowed | Allowed (e.g., ArrayList |
| Default Value | 0 | null |
| Methods | No methods | Has methods like parseInt(), toString() |
Key Differences
int is a basic data type that holds a 32-bit signed integer value directly in memory. It is fast and efficient because it does not involve any object overhead. However, it cannot represent the absence of a value (null) and cannot be used where objects are required, such as in Java collections.
Integer is a class that wraps an int value inside an object. This allows it to be used in places where objects are needed, like in ArrayList or other generic classes. It can also represent a null value, which means it can indicate 'no value'. However, using Integer involves more memory and slightly slower performance due to object creation and garbage collection.
Java automatically converts between int and Integer when needed, a feature called autoboxing and unboxing, but understanding the difference helps avoid unexpected null pointer errors and performance issues.
Code Comparison
Here is how you declare and use int in Java to store and print a number.
public class IntExample { public static void main(String[] args) { int number = 10; System.out.println("int value: " + number); } }
Integer Equivalent
Here is the equivalent code using Integer to store and print a number.
public class IntegerExample { public static void main(String[] args) { Integer number = 10; // autoboxing from int to Integer System.out.println("Integer value: " + number); } }
When to Use Which
Choose int when you need simple, fast storage of integer values without the need for objects or nulls. It is best for arithmetic operations and performance-critical code.
Choose Integer when you need to store integers in collections like ArrayList, or when you need to represent a missing value with null. Also use Integer when you want to use utility methods provided by the class.
Key Takeaways
int is a primitive type storing raw integer values efficiently.Integer is an object wrapper that can be null and used in collections.int and Integer automatically.int for performance and Integer for object needs or nullability.Integer nulls to avoid NullPointerExceptions.