java - Java中的字符串初始化

标签 java string

  1. 字符串str1;
  2. String str2 = null;
  3. String str3 = "";
  4. String str4 = new String();
  5. 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 as null, is it all-0-bits or the bytecode of null is all-zero?

这已经被问过(并回答过):

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?

是的。

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

是的。

关于java - Java中的字符串初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30694275/

相关文章:

java - 使用 Mockito 在 REST Controller 中模拟类

java - Google Container Engine 中集群中 pod 的组织

c++ - 将二维字符串数组传递给 C++ 中的函数

string - ExtJS 如何从字符串动态创建小部件和布局

java - 在 Java 中检查并从字符串中提取一个数字

java - 返回字符串的函数的 C++ 执行顺序

java - 使用 Extjs 将表单数据传递到 servlet

java - 将字符串替换为空格

java - 带有 switch case 语句的 Android Studio 1.1 警告

c - 交换 char 数组的元素可以工作,但交换 char 字符串的元素会导致核心转储