字符串str1;
String str2 = null;
String str3 = "";
String str4 = new String();
String str5 = new String("");
我知道对于上面的第三次初始化,字符串对象是在字符串池中初始化的,第四次与字符串池无关。
1. 和有什么区别?和 2.?如果我将 str1
视为指针变量,它存储的是 JVM 或 OS 从未使用过的特定内存地址?
4.有区别吗?和 5.?
当我通过 System.out.println(str1)
和 System.out.println( str2)
,对于str1
,我什至无法通过编译。对于str2
,编译正常,我得到“null”和控制台窗口。为什么?
在@aioobe 的回答后编辑:更多问题:
我想了解更多关于“null”的信息。由于str2
(reference variable)就像一个指针变量,所以里面应该有一些东西(0/1位)(在这个指针变量占用的内存中)。由于它被初始化为null,它是全0位还是null的字节码是全零?另一个问题是,如果我通过 str2.toString()
在 str2
上调用方法 toString(),我会在运行时遇到 NullPointer 错误。那么是JVM检查引用变量是否为null? JVM怎么知道它是空的呢? JVM 检查 str2
?
还有一个关于Java中null的问题: concatenation of null and a string literal
最佳答案
What is the difference between 1. and 2.? If I consider
str1
as a pointer variable, what it stores is a particular memory address that is never used by the JVM or OS?
如果这些是类中的字段,则没有区别,因为引用类型(例如 String)的字段的默认值已经是 null
。
如果这些是局部变量(即在方法中声明的变量),str1
将不会被初始化为任何东西,而 str2
将被初始化为 null
。这里的区别是局部变量在初始化之前不能使用,所以(你似乎已经发现)你不能打印 str1
,但你可以打印 str2
。
Is there a difference between 4. and 5.?
不,不是语义上的。不过,您会得到略有不同的字节码。
When I print str1 and str2 directly by System.out.println(str1) and System.out.println(str2), for str1, I can't even pass the compilation. For str2, compilation is OK and I get "null" and the output in the console window. Why?
这似乎表明这些是局部变量。局部变量在使用前需要初始化。
I would like to know more about "null". Since
str2
(reference variable) is like a pointer variable, there should be something (0/1 bits) in it (in the memory occupied by this pointer variable). As it is initialized asnull
, is it all-0-bits or the bytecode ofnull
is all-zero?
这已经被问过(并回答过):
Another question is that if I call the method
toString()
onstr2
bystr2.toString()
, I got a NullPointer Error at runtime. So it is JVM that checks if the reference variable isnull
?
是的。
How can JVM know that it is
null
? JVM checks the bits instr2
?
是的。
关于java - Java中的字符串初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30694275/