Integer (Wrapper class) and int (primitive data type)
- The major difference between an Integer and an int is that Integer is a wrapper class whereas int is a primitive data type.
- An int is a data type that stores 32-bit signed two’s complement integer whereas an Integer is a class that wraps a primitive type int in an object.
- An Integer can be used as an argument to a method that requires an object, whereas int can be used as an argument to a method that requires an integer value, that can be used for arithmetic expression.
- An int datatype helps to store integer values in memory whereas Integer helps to convert int into an object and to convert an object into an int.
- The variable of int type is mutable unless it is marked as final and the Integer class contains one int value and is immutable.
Example1
public class PrimitiveDataTypeTest {
public static void main(String []args) {
// Declaration of int
int a = 20;
int b = 40;
int result = a+b;
System.out.println("Result is: " + result);
}
}
Output
Result is: 60
Example2
public class WrapperClassTest {
public static void main(String []args) {
int a = 20;
Integer b = Integer.valueOf(a);
System.out.println("Converted Value of b is: " + b);
Integer c = new Integer(30);
int d = c.intValue();
System.out.println("Converted Value of d is: " + d);
}
}
Output
Converted Value of b is: 20
Converted Value of d is: 30