Understanding the Distinction Between Integer and int in Java
The Java programming language provides two options for representing integers: primitive type int and object wrapper class Integer. While both store numerical values, they differ significantly in their nature and usage.
int: Primitive Type
int is a primitive type, meaning its variables directly hold integer values. Assigning a value to an int variable stores the binary representation of the integer in memory. For instance, the following code assigns the value 9 to an int variable:
int n = 9;
Primitive types do not have methods or properties, so expressions like int.parseInt("1") are invalid.
Integer: Object Wrapper Class
Integer, on the other hand, is an object wrapper class. Its variables store references to Integer objects that encapsulate an integer value. Similar to other object types, Integer has methods and properties. When assigning a value to an Integer variable, a new Integer object is created and the reference to it is stored:
Integer n = 9;
Method Invocation
Method invocations can be made on the Integer class, but not on the primitive type int. For example, you can use the parseInt method to convert a string to an integer:
Integer.parseInt("1");
Autoboxing and Unboxing
Since Java 5, autoboxing and unboxing allow seamless conversion between primitive types and their wrapper classes. The following assignment is equivalent to the previous example:
int n = Integer.parseInt("1"); // Autoboxing
Similarly, the following code retrieves the integer value from an Integer object:
int n = Integer.valueOf(9).intValue(); // Unboxing
Summary
int and Integer are different representations of integers in Java. int is a primitive type that stores integer values directly, while Integer is an object wrapper class that encapsulates integer values as objects. Integer provides methods and properties, while int does not.
The above is the detailed content of Java int vs. Integer: What\'s the Difference?. For more information, please follow other related articles on the PHP Chinese website!