例如,为什么你可以做:

int n = 9;

而不是:

Integer n = 9;

你可以这样做:

Integer.parseInt("1");

而不是:

int.parseInt("1");

当前回答

Int是基本类型,不是对象。这意味着没有与之关联的方法。Integer是一个具有方法的对象(例如parseInt)。

在更新的java中,有自动装箱(和解装箱)的功能。这意味着编译器将在需要的地方插入Integer.valueOf(int)或integer.intValue()。这意味着它实际上是可以写的

Integer n = 9;

它被解释为

Integer n = Integer.valueOf(9);

其他回答

为了优化Java代码运行时,添加了int基元类型,包括float, bool等,但它们与包装器类一起出现,以便在需要时可以转换并使用它们作为标准Java对象以及作为其成员函数的许多实用程序(如Integer.parseInt("1"))。

Int是表示整数的基本类型。而Integer是一个包装int的对象。Integer对象提供了更多的功能,例如转换为十六进制、字符串等。

你也可以在Integer中使用OOP概念。例如,您可以使用Integer作为泛型(即Collection<Integer>)。

Integer是Java中的包装器类型,而int是基本类型。在Java中,除了基本数据类型之外的所有内容都是作为对象实现的,这意味着Java是一种高质量的纯面向对象编程语言。如果需要,所有的原语类型在Java中也可以作为包装器类型。使用基本类型可以获得一些性能上的好处,因此包装器类型应该只在必要时使用。

在下面的例子中。

Integer n = 9;

常量9被自动装箱(自动装箱和解装箱从java 5开始自动发生)为Integer,因此你可以使用这样的语句和Integer n = new Integer(9)。这实际上是通过语句Integer.valueOf(9).intValue();

int变量保存一个32位有符号整数值。Integer(大写I)保存对(类)类型Integer或null对象的引用。

Java自动在两者之间进行类型转换;当Integer对象作为int操作符的参数出现,或者被赋值给int变量,或者一个int值被赋值给Integer变量时,从Integer到int。这种类型转换称为装箱/解装箱。

如果一个引用null的Integer变量被显式或隐式地解盒,则抛出NullPointerException异常。

(在上述文本中,“变量”指局部变量、字段或参数)

本文摘自《Java:完整参考,第九版》

Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported by the language. Primitive types, rather than objects, are used for these quantities for the sake of performance. Using objects for these values would add an unacceptable overhead to even the simplest of calculations. Thus, the primitive types are not part of the object hierarchy, and they do not inherit Object. Despite the performance benefit offered by the primitive types, there are times when you will need an object representation. For example, you can’t pass a primitive type by reference to a method. Also, many of the standard data structures implemented by Java operate on objects, which means that you can’t use these (object specific) data structures to store primitive types. To handle these (and other) situations, Java provides type wrappers, which are classes that encapsulate a primitive type within an object. Wrapper classes relate directly to Java’s autoboxing feature. The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy.