0

您能否澄清一下 - 应该使用哪个词来描述从文字创建 String 对象的过程:

字符串 obj = "值";

据我了解,在这里说我们有自动装箱是不正确的,因为它实际上只适用于原始类型,但是这个过程还有其他特殊的关键字吗?

4

3 回答 3

2

它被称为定义。您正在“声明”一个字符串变量,并将其“初始化”为特定值。

查看以下链接以获得更好的说明:
http ://ee.hawaii.edu/~tep/EE160/Book/chap14/subsection2.1.1.4.html

并引用其中的一部分:
So far when we have ``declared'' a variable, we have meant that we have told the compiler about the variable; i.e. its type and its name, as well as allocated a memory cell for the variable (either locally or globally). This latter action of the compiler, allocation of storage, is more properly called the definition of the variable. The stricter definition of declaration is simply to describe information ``about'' the variable.

于 2013-10-15T15:12:59.827 回答
1

You are actually doing two things in that statement. You are declaring the variable obj of type String, and you are initializing it to "value."

Another term for the latter is assignment. Initialization is a specific form of assignment where you're doing it for the first time.

于 2013-10-15T15:22:41.763 回答
-1

您正在寻找的是初始化

此外,我将尝试解释 String 类可以具有的两个初始化的区别。

对于 StringString obj = "value";String obj = new String("value");

String obj = "value";

当我们使用双引号创建字符串时,JVM 会在字符串池中查找是否有任何其他字符串以相同的值存储。如果找到,它只会返回对该 String 对象的引用,否则它会创建一个具有给定值的新 String 对象并将其存储在 String 池中。

String obj = new String("value");

当我们使用 new 运算符时,JVM 会创建 String 对象,但不会将其存储到 String Pool 中。我们可以使用 intern() 方法将 String 对象存储到 String 池中,或者如果池中已经存在具有相等值的 String,则返回引用。

参考:http ://www.journaldev.com/1321/java-string-interview-questions-and-answers

于 2013-10-15T15:13:51.813 回答