且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中的字符串初始化

更新时间:2022-06-22 22:21:07


1.和2.有什么区别?如果我将 str1 视为指针变量,它存储的是JVM或OS从不使用的特定内存地址?

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

If these are local variables (i.e. variables declared in a method) str1 will not be initialized to anything, while str2 will be initialized to null. The difference here is that a local variable can't be used until it has been initialized, so (as you seem to have discovered) you can't print str1, but you can print str2.


4和5之间有区别吗?

Is there a difference between 4. and 5.?

不,不是语义上的。你会得到稍微不同的字节码。

No, not semantically. You'll get slightly different byte code though.


当我直接用System.out.println(str1)和System打印str1和str2时.out.println(str2),对于str1,我甚至无法通过编译。对于str2,编译是正常的,我在控制台窗口中得到null和输出。为什么?

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?

这似乎表明这些是局部变量。局部变量在使用之前需要初始化。

This seems to indicate that these are local variables. Local variables needs to be initialized before they are used.


我想了解更多关于null的信息。由于 str2 (引用变量)就像一个指针变量,因此应该有一些东西(0/1位)(在这个指针变量占用的内存中)。当它被初始化为 null 时,是全0位还是 null 的字节码全为零?

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 as null, is it all-0-bits or the bytecode of null is all-zero?

这已被问及(并已回答):

This has already been asked (and answered):

  • How is null represented in memory in java
  • What exactly is null in Java memory

另一个问题是如果我调用方法 toString() on str2 by str2.toString(),我得到一个NullPointer错误在运行时。因此,JVM检查引用变量是否为 null

Another question is that if I call the method toString() on str2 by str2.toString(), I got a NullPointer Error at runtime. So it is JVM that checks if the reference variable is null?

是。


JVM如何知道它是 null ? JVM检查 str2 中的位?

How can JVM know that it is null? JVM checks the bits in str2?

是。