In Java, int and Integer are two different types that are used to represent integer values. Here’s the difference between them:
int is a primitive data type that represents a 32-bit signed integer. It can hold values between -2,147,483,648 and 2,147,483,647.
Integer is a class that wraps an int value in an object. It provides methods to manipulate the value, such as converting it to a string or comparing it to another value.
Here’s an example Java program that demonstrates the use of int and Integer:
public class IntVsInteger {
public static void main(String[] args) {
int myInt = 10;
Integer myInteger = 20;
System.out.println("My int: " + myInt);
System.out.println("My integer: " + myInteger);
myInt = myInt + 5;
myInteger = myInteger + 5;
System.out.println("My int after increment: " + myInt);
System.out.println("My integer after increment: " + myInteger);
}
}
This program declares an int variable called myInt and an Integer variable called myInteger. It then prints the values of these variables to the console.
The program then increments both variables by 5. Note that the int value is incremented using the + operator, while the Integer value is incremented using the Integer.valueOf method, which returns a new Integer object with the incremented value. This is because Integer is an object, and objects cannot be directly modified like primitive types can.
In summary, int is a primitive data type used to store integer values, while Integer is a class that wraps an int value in an object and provides methods to manipulate the value. In general, it is recommended to use int for most cases unless you need to use the methods provided by the Integer class.