Home > Java > javaTutorial > Java int vs. Integer: What\'s the Difference?

Java int vs. Integer: What\'s the Difference?

Susan Sarandon
Release: 2024-12-07 05:00:17
Original
825 people have browsed it

Java int vs. Integer: What's the Difference?

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;
Copy after login

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;
Copy after login

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");
Copy after login

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
Copy after login

Similarly, the following code retrieves the integer value from an Integer object:

int n = Integer.valueOf(9).intValue(); // Unboxing
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template