Difference between an Integer and int in Java with Examples
Last Updated :
29 Jul, 2024
In Java, int is a primitive data type while Integer is a Wrapper class.
- int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it.
- Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.
- Integer is a class and thus it can call various in-built methods defined in the class. Variables of type Integer store references to Integer objects, just as with any other reference (object) type.
Examples:
// Valid
int n = 20;
//valid
Integer n = 45;
// Valid
Integer.parseInt("10");
// Not Valid
int.parseInt("10");
Important Points of Difference:
1. Casting to String Variable
We can't assign a String value (containing an integer only) directly or even by casting to an int variable. However, we can assign a String to an object of Integer type using the Integer(String) constructor. We can even use parseInt(String) to convert a String literal to an int value.
Java
// Java program to illustrate
// difference between
// int and Integer
public class Main {
public static void main(String args[])
{
Integer a = Integer.valueOf("123");
// Casting not possible
// int a = (int)"123";
// Casting not possible
// int c="123";
// Casting possible using methods
// from Integer Wrapper class
int b = Integer.parseInt("123");
System.out.print(a + new Float("10.1"));
}
}
2. Direct Conversion of value to other base
We can directly convert an integer value stored in Integer class to Binary, Octal or Hexadecimal format using toBinaryString(), toOctalString() or toHexString() respectively. This is not possible in a variable of int type.
Java
// Java program to illustrate
// difference between
// int and Integer
public class Main {
public static void main(String args[])
{
String bin = Integer.toBinaryString(123);
String oct = Integer.toOctalString(123);
String hex = Integer.toHexString(123);
System.out.print(bin + "\n" + oct + "\n" + hex);
}
}
3. Performing operations on data
Integer class also allows us to reverse our number or rotate it left or right using reverse(), rotateLeft() and rotateRight() respectively. We need to define our own logic to perform these operations on an int variable as its not an inbuilt class.
Java
// Java program to illustrate
// difference between
// int and Integer
public class Main {
public static void main(String args[])
{
// mainethods convert integer to its binary form,
// apply the desired operation
// and then returns the decimal form
// of the newly formed binary number
// (12)10->(1100)2 ->
// rotate left by 2 units -> (110000)2->(48)10
int rL = Integer.rotateLeft(12, 2);
// (12)10->(1100)2 ->
// rotate right by 2 units -> (0011)2->(3)10
int rR = Integer.rotateRight(12, 2);
//(12)10 -> (00000000000000000000000000001100)2
// -> reverse ->(00110000000000000000000000000000)2
// -> (805306368)10
// int is of 32 bits
int rev = Integer.reverse(12);
System.out.print("Left Rotate : " + rL
+ "\nRight rotate : " + rR + "\nReverse : " + rev);
}
}
OutputLeft Rotate : 48
Right rotate : 3
Reverse : 805306368
4. Flexibility
Integer wrapper class provides us more flexibility to the existing int datatype. We are able to perform many operations on an int value besides the predefined operators. Integer class is used where we need to treat an int variable like an object. Since Wrapper classes inherit Object class, they can be used in collections with Object reference or generics. Thus we are adding the property of nullability to the existing int data type. Since Java 5, we have the concept of auto-boxing wherein a primitive data type is converted into a wrapper class and vice versa automatically. Hence, we can perform any arithmetic or logical operation between any primitive data type and any Wrapper class.
Note: The new Integer(String) constructor is deprecated in Java 9 and removed in Java 16. However, it is still supported in earlier versions (though it is not recommended to use it due to its deprecation)
- Java 9: The new Integer(String) constructor is deprecated.
- Java 16: The new Integer(String) constructor is removed.
Java
// Java program to illustrate
// auto-boxing
import java.util.function.Function;
public class Main {
public static void main(String args[])
{
Integer a = new Integer("12");
Integer d = new Integer("13");
int b = 2;
double c = 3.1;
Double f = new Double("12.1");
int d2 = a + d;
System.out.println("Sum of 2 Integer objects :"
+ (a + d));
System.out.println("Sum of an Integer object
and int value :" + (a + b));
System.out.println("Sum of an Integer object
and double value :" + (a + c));
System.out.println("Sum of an Integer object
and Double object :" + (a + f));
}
}
Running this Code
- Java 8: The code will compile and run, but using
new Integer(String)
will generate a warning. - Java 9 to Java 15: The code will compile and run, but using
new Integer(String)
will generate a deprecation warning. - Java 16 and Later: Using
new Integer(String)
will cause a compilation error. You must use Integer.valueOf(String)
.
It's best to avoid using deprecated constructors and follow the current best practices to ensure compatibility with future Java versions.
In Java 16 and later versions, using new Integer("12")
will result in a compilation error. The recommended approach is to use Integer.valueOf("12")
Java
/*package whatever //do not write package name here */
// Java program to illustrate
// auto-boxing
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
// Use valueOf instead of new Integer to avoid deprecated constructor usage
Integer a = Integer.valueOf("12");
Integer d = Integer.valueOf("13");
int b = 2;
double c = 3.1;
// Use valueOf instead of new Double to avoid deprecated constructor usage
Double f = Double.valueOf("12.1");
// Correct variable name
int d2 = a + d;
// Corrected print statements
System.out.println("Sum of 2 Integer objects: " + (a + d));
System.out.println("Sum of an Integer object and int value: " + (a + b));
System.out.println("Sum of an Integer object and double value: " + (a + c));
System.out.println("Sum of an Integer object and Double object: " + (a + f));
}
}
OutputSum of 2 Integer objects: 25
Sum of an Integer object and int value: 14
Sum of an Integer object and double value: 15.1
Sum of an Integer object and Double object: 24.1
Besides Integer, we have more wrapper classes in Java corresponding to the data types. These are given as follows :
Equivalent Wrapper Classes of Primitive Types in Java
Primitive Data Type | Wrapper Class |
---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
Similar Reads
Is there any difference between int[] a and int a[] in Java?
An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. In Java, Array can be declared in the following ways: One-Dimensional Arrays: The general form of a one-dimensional array declaration is type var-name[];ORtype[] v
6 min read
Difference Between Object and Instance in Java
The object is an instance of a class. A class is like a blueprint or template that defines the properties and behavior of objects. When we create an object we are creating an instance of that class. Object in JavaThe object is an instance of a class. A class is a blueprint or template that describes
3 min read
Difference Between == Operator and equals() Method in Java
In Java, the equals() method and the == operator are used to compare objects. The main difference is that string equals() method compares the content equality of two strings while the == operator compares the reference or memory location of objects in a heap, whether they point to the same location
4 min read
Difference between x++ and x=x+1 in Java
In x++, it increase the value of x by 1 and in x=x+1 it also increase the value of x by 1. But the question is that both are same or there is any difference between them. We should aware with the fact that whenever we are trying to apply any arithmetic operator between two variables a and b, the res
3 min read
Difference between Array and String in Java
An array is a collection of similar type of elements that are stored in a contiguous memory location. Arrays can contain primitives(int, char, etc) as well as object(non-primitives) references of a class depending upon the definition of the array. In the case of primitive data type, the actual value
5 min read
ByteBuffer getInt() method in Java with Examples
getInt() The getInt() method of java.nio.ByteBuffer class is used to read the next four bytes at this buffer's current position, composing them into an int value according to the current byte order, and then increments the position by four. Syntax: public abstract int getInt() Return Value: This met
5 min read
Difference Between Void and Non Void Methods in Java
The method in Java or Methods of Java is a collection of statements that perform some specific task and return the result to the caller. Every method has a return type that can be differentiated between void and non-void. In this article, we will learn about void and non-void methods. Void Methods i
2 min read
Integer.MAX_VALUE and Integer.MIN_VALUE in Java with Examples
Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold, but remembering such a large and precise number comes out to be a difficult job. Therefore, Java has constants to represent these numbers, so that these can be
3 min read
IntStream count() in Java with examples
IntStream count() returns the count of elements in the stream. IntStream count() is present in java.util.stream.IntStream Syntax : long count() Example 1 : Count the elements in IntStream. Java // Java code for IntStream count() // to count the number of elements in // given stream import java.util.
2 min read
Java 8 | DoubleToIntFunction Interface in Java with Example
The DoubleToIntFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and gives an int-valued result. The lambda expression assigned to an obj
1 min read