In this guide, you will learn the differences between int and Integer. Both of these are the data types that represents integer values. However they serve different purposes and usages.
int
- Primitive Data Type:
intis a primitive data type in Java. - Memory Efficiency: It takes less space in memory compared to Integer so it is more memory efficient. It takes 4 bytes compared to 16 bytes taken by Integer.
- Default Value: The default value of an
intis0. - No Methods:
intis a primitive data type, hence it doesn’t have any methods associated with it. - Usage: Commonly used in arithmetic operations.
Integer
- Wrapper Class:
Integeris a wrapper class that belongs tojava.langpackage. - Object: Integer is a class so an object can be created for this class. It can be used where objects are required for example, collections (e.g.,
LinkedList<Integer>). - Memory Overhead:
Integertakes more space in memory compared tointbecause they store metadata along with actual data. - Default Value: The default value of an
Integerisnull. - Methods:
Integerclass provides several useful methods such asintValue(),parseInt(),toString(),valueOf()etc. - Autoboxing and Unboxing: The autoboxing and unboxing feature of Java provides automatic conversion between
intandInteger.
Java int vs Integer Example
Let’s take an example to understand the key differences between these two.
public class IntVsInteger {
public static void main(String[] args) {
// Using int
int primitiveInt = 5;
System.out.println("Primitive int: " + primitiveInt);
// Using Integer
Integer wrapperInt = 10;
System.out.println("Wrapper Integer: " + wrapperInt);
// Autoboxing: int to Integer Conversion
Integer autoBoxedInt = primitiveInt;
System.out.println("int to Integer: " + autoBoxedInt);
// Unboxing: Integer to int Conversion
int unboxedInt = wrapperInt;
System.out.println("Integer to int: " + unboxedInt);
// Demonstrating methods of Integer class
String intString = Integer.toString(primitiveInt);
int parsedInt = Integer.parseInt(intString);
System.out.println("Parsed int from String: " + parsedInt);
}
}
Key Differences
- Memory and Performance:
intis more memory-efficient and faster compared to anInteger. - Nullability:
Integercan benullbecause it is an object, whileintcannot be null, they have default 0 value. - Collections: When working with Collections such as ArrayList, LinkedList, HashMap etc,
Integeris preferred because these collections require objects.
Leave a Reply