The Wayback Machine - https://web.archive.org/web/20240828180237/https://www.geeksforgeeks.org/difference-between-an-integer-and-int-in-java/
Open In App

Difference between an Integer and int in Java with Examples

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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")); 
    } 
} 

Output
133.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); 
    } 
} 

Output
1111011
173
7b

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); 
    } 
} 

Output
Left 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));
    }
}

Output
Sum 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 TypeWrapper Class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble



Similar Reads

TimeZone getOffset(int, int, int, int, int, int) Method in Java with Examples
The getOffset(int era, int yr, int mon, int day, int dayOfWeek, int millisec) method of TimeZone class in Java is used to know the offset value of this TimeZone at a specific date or modified date in case of daylight savings, from the UTC or the Universal Time Coordinated. This offset value can be added to get the local time. Syntax: public abstrac
2 min read
ZoneOffset ofHoursMinutesSeconds(int, int, int) method in Java with Examples
The ofHoursMinutesSeconds(int, int, int) method of ZoneOffset Class in java.time package is used to obtain an instance of ZoneOffset using the offset in hours, minutes and seconds passed as the parameter. This method takes the hours, minutes and seconds as parameter in the form of int and converts it into the ZoneOffset. Syntax: public static ZoneO
2 min read
SimpleTimeZone setStartRule(int, int, int) method in Java with Examples
The setStartRule(int startofMonth, int startofDay, int startofTime) method of SimpleTimeZone class in Java is used to set a particular start rule of the day-light saving time to a fixed date within a given month. Syntax: public void setStartRule(int startofMonth, int startofDay, int startofTime) Parameters: The method takes three parameters: starto
2 min read
SimpleTimeZone setEndRule(int, int, int) method in Java with Examples
The setEndRule(int endofMonth, int endofDay, int endofTime) method of SimpleTimeZone class in Java is used to set a particular rule of the day-light saving time to a fixed date within a given month. Syntax: public void setEndRule(int endofMonth, int endofDay, int endofTime) Parameters: The method takes three parameters: endofMonth: This is of Integ
2 min read
HijrahDate of(int, int, int) method in Java with Example
The of() method of java.time.chrono.HijrahDate class is used to generate the date according to Islamic hijri calendar system by using the passed proleptic year, month and date. Syntax: public static HijrahDate of(int Year, int month, int dayOfMonth) Parameter: This method takes the following argument as a parameter: year: which is the integer value
2 min read
IsoChronology date(int, int, int) method in Java with Example
The date() method of java.time.chrono.IsoChronology class is used get the local date according to ISO calendar system for the given year, month and day. Syntax: public LocalDate date(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following arguments as parameter. prolepticYear: integer proleptic year for the year fie
2 min read
JapaneseChronology date(int, int, int) method in Java with Example
The date() method of java.time.chrono.JapaneseChronology class is used get the local date according to japanese calendar system for the given year, month and day.Syntax: public JapaneseDate date(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following arguments as parameter. prolepticYear: integer proleptic year for
2 min read
JapaneseDate of(int, int, int) method in Java with Example
The of() method of java.time.chrono.JapaneseDate class is used to generate the date according to japanese calendar system by using the passed proleptic year, month and date. Syntax: public static JapaneseDate of(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following argument as a parameter: year: which is the integ
2 min read
JapaneseDate of(JapaneseEra,int, int, int) method in Java with Example
The of() method of java.time.chrono.JapaneseDate class is used to generate the date according to Japanese calendar system by using the passed proleptic year, month, date and JapaneseEra. Syntax: public static JapaneseDate of(JapaneseEra era, int yearOfEra, int month, int dayOfMonth) Parameter: This method takes the following argument as a parameter
2 min read
MinguoChronology date(int, int, int) method in Java with Example
The date() method of java.time.chrono.MinguoChronology class is used get the local date according to Minguo calendar system for the given year, month and day.Syntax: public MinguoDate date(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following arguments as parameter. prolepticYear: integer proleptic year for the ye
2 min read
MinguoDate of(int, int, int) method in Java with Example
The of() method of java.time.chrono.MinguoDate class is used to generate the date according to Minguo calendar system by using the passed proleptic year, month and date. Syntax: public static MinguoDate of(int Year, int month, int dayOfMonth) Parameter: This method takes the following argument as a parameter: year: which is the integer value of yea
2 min read
ThaiBuddhistChronology date(int, int, int) method in Java
The date() method of java.time.chrono.ThaiBuddhistChronology class is used get the local date according to ThaiBuddhist calendar system for the given year, month and day.Syntax: public ThaiBuddhistDate date(int prolepticYear, int month, int dayOfMonth) Parameter: This method takes the following arguments as parameter. prolepticYear: integer prolept
2 min read
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[] var-name; Multidimensional Arrays: int[][] intArray
6 min read
Java Guava | IntMath.checkedSubtract(int a, int b) method with Examples
The checkedSubtract(int a, int b) is a method of Guava's IntMath Class which accepts two parameters a and b, and returns their difference. Syntax: public static int checkedSubtract(int a, int b) Parameters: The method accepts two int values a and b and computes their difference. Return Value: The method returns the difference of int values passed t
2 min read
Java Guava | IntMath.checkedMultiply(int a, int b) method with Examples
The checkedMultiply(int a, int b) is a method of Guava's IntMath Class which accepts two parameters a and b, and returns their product. Syntax: public static int checkedMultiply(int a, int b) Parameters: The method accepts two int values a and b and computes their product. Return Value: The method returns the product of int values passed to it, pro
2 min read
Matcher region(int, int) method in Java with Examples
The region(int, int) method of Matcher Class restricts the region to be matched by the pattern. This region must be lesser than or same as the previous region, but not greater. Else it would lead to IndexOutOfBoundsException. This method returns a Matcher with the new matching region. Syntax: public Matcher region(int startIndex, int endIndex) Para
3 min read
ZoneOffset ofHoursMinutes(int, int) method in Java with Examples
The ofHoursMinutes(int, int) method of ZoneOffset Class in java.time package is used to obtain an instance of ZoneOffset using the offset in hours and minutes passed as the parameter. This method takes the hours and minutes as parameter in the form of int and converts it into the ZoneOffset. Syntax: public static ZoneOffset ofHoursMinutes(int hours
2 min read
Java Guava | binomial(int n, int k) of LongMath Class with Examples
The binomial(int n, int k) method of Guava's LongMath Class accepts two parameters n and k and calculate the value of the binomial coefficient [Tex]{n}\choose{k}[/Tex]. If the calculated value overflows the maximum value of a long, then the method returns Long.MAX_VALUE i.e, the maximum value of a long. Syntax : public static long binomial(int n, i
2 min read
PrintWriter write(String, int, int) method in Java with Examples
The write(String, int, int) method of PrintWriter Class in Java is used to write a specified portion of the specified String on the stream. This String is taken as a parameter. The starting index and length of String to be written are also taken as parameters. Syntax: public void write(String string, int startingIndex, int lengthOfstring) Parameter
2 min read
PrintWriter write(char[], int, int) method in Java with Examples
The write(char[], int, int) method of PrintWriter Class in Java is used to write a specified portion of the specified character array on the stream. This character array is taken as a parameter. The starting index and length of characters to be written are also taken as parameters. Syntax: public void write(char[] charArray, int startingIndex, int
2 min read
PrintWriter append(CharSequence, int, int) method in Java with Examples
The append(CharSequence, int, int) method of PrintWriter Class in Java is used to append a specified portion of the specified charSequence on the stream. This charSequence is taken as a parameter. The starting index and ending index to be written are also taken as parameters. Syntax: public void append(CharSequence charSequence, int startingIndex,
2 min read
PrintStream append(CharSequence, int, int) method in Java with Examples
The append(CharSequence, int, int) method of PrintStream Class in Java is used to append a specified portion of the specified charSequence on the stream. This charSequence is taken as a parameter. The starting index and ending index to be written are also taken as parameters. Syntax: public void append(CharSequence charSequence, int startingIndex,
2 min read
PrintStream write(byte[], int, int) method in Java with Examples
The write(byte[], int, int) method of PrintStream Class in Java is used to write a specified portion of the specified byteacter array on the stream. This byteacter array is taken as a parameter. The starting index and length of byteacters to be written are also taken as parameters. Syntax: public void write(byte[] byteArray, int startingIndex, int
2 min read
Writer append(CharSequence, int, int) method in Java with Examples
The append(CharSequence, int, int) method of Writer Class in Java is used to append a specified portion of the specified charSequence on the writer. This charSequence is taken as a parameter. The starting index and ending index to be written are also taken as parameters. Syntax: public void append(CharSequence charSequence, int startingIndex, int e
2 min read
StringWriter write(char[], int, int) method in Java with Examples
The write(char[], int, int) method of StringWriter Class in Java is used to write a specified portion of the specified character array on the writer. This character array is taken as a parameter. The starting index and length of characters to be written are also taken as parameters. Syntax: public void write(char[] charArray, int startingIndex, int
2 min read
StringWriter write(String, int, int) method in Java with Examples
The write(String, int, int) method of StringWriter Class in Java is used to write a specified portion of the specified String on the stream. This String is taken as a parameter. The starting index and length of String to be written are also taken as parameters. Syntax: public void write(String string, int startingIndex, int lengthOfstring) Paramete
2 min read
StringWriter append(CharSequence, int, int) method in Java with Examples
The append(CharSequence, int, int) method of StringWriter Class in Java is used to append a specified portion of the specified charSequence on the writer. This charSequence is taken as a parameter. The starting index and ending index to be written are also taken as parameters. Syntax: public void append(CharSequence charSequence, int startingIndex,
2 min read
Java Guava | LongMath.checkedMultiply(int a, int b) method with Examples
The checkedMultiply(long a, long b) is a method of Guava's LongMath Class which accepts two parameters a and b, and returns their product. Syntax: public static long checkedMultiply(long a, long b) Parameters: The method accepts two long values a and b and computes their product. Return Value: The method returns the product of long values passed to
2 min read
Java Guava | IntMath.checkedAdd(int a, int b) method with Examples
The checkedAdd(int a, int b) is a method of Guava's IntMath Class which accepts two parameters a and b, and returns their sum. Syntax: public static int checkedAdd(int a, int b) Parameters: The method accepts two int values a and b and computes their sum. Return Value: The method returns the sum of int values passed to it, provided it does not over
2 min read
Java Guava | Ints.indexOf(int[] array, int[] target) method with Examples
Ints.indexOf(int[] array, int[] target) method of Guava's Ints Class accepts two parameters array and target. If the target exists within the array, the method returns the start position of its first occurrence. If the target does not exist within the array, the method returns -1. Syntax: public static int indexOf(int[] array, int[] target) Paramet
3 min read