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:
int
is 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
int
is0
. - No Methods:
int
is a primitive data type, hence it doesn’t have any methods associated with it. - Usage: Commonly used in arithmetic operations.
Integer
- Wrapper Class:
Integer
is a wrapper class that belongs tojava.lang
package. - 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:
Integer
takes more space in memory compared toint
because they store metadata along with actual data. - Default Value: The default value of an
Integer
isnull
. - Methods:
Integer
class provides several useful methods such asintValue()
,parseInt()
,toString()
,valueOf()
etc. - Autoboxing and Unboxing: The autoboxing and unboxing feature of Java provides automatic conversion between
int
andInteger
.
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:
int
is more memory-efficient and faster compared to anInteger
. - Nullability:
Integer
can benull
because it is an object, whileint
cannot be null, they have default 0 value. - Collections: When working with Collections such as ArrayList, LinkedList, HashMap etc,
Integer
is preferred because these collections require objects.
Leave a Reply