例如,为什么你可以做:

int n = 9;

而不是:

Integer n = 9;

你可以这样做:

Integer.parseInt("1");

而不是:

int.parseInt("1");

当前回答

本文摘自《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.

其他回答

Integer基本上只是原始类型int的包装器。它允许您使用Integer类的所有函数,使您的工作更加轻松。

如果您是Java新手,那么您应该学会欣赏Java文档。例如,您想了解的关于Integer类的任何内容都有详细的文档。

这是直接从Integer类的文档中出来的:

Integer类将原始类型int的值包装在对象中。Integer类型的对象包含一个int类型的字段。

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

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

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

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

int是基本数据类型,而Integer是Java中的引用或包装器类型(类)。

在java 1.5之后,引入了自动装箱和拆箱的概念,你可以像这样初始化int或Integer。

int a= 9
Integer a = 9 // both valid After Java 1.5.

为什么Integer.parseInt (" 1 ");但不是int.parseInt("1");??

Integer是jdk库中定义的类,parseInt()是属于Integer Class的静态方法

所以,Integer.parseInt (" 1 ");在java中是可能的。但是int在java中是基本类型(假设是关键字)。所以,你不能用int调用parseInt()。

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

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

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

Integer n = 9;

它被解释为

Integer n = Integer.valueOf(9);