java - String = 运算符引用或在这种情况下创建新的 String 对象

标签 java string object

一开始听起来可能很奇怪,可能看起来很简单,但我却卡在了预料之中。我认为在下面的代码中,textst 引用,作为输出,我会得到 hello world hello world,但不是。我得到 hello world

class Test2 {
    private volatile static String text = "";

    public static void main(String[] args) {
        String s = text;
        text = "hello world";
        String t = text;
        System.out.println(s + "   " + t);
    }
}

到目前为止我错过了什么?我真的很困惑。大概在那里隐式创建了一个新对象。但是为什么?


下面一个不是Java相关的,是C-knowers。我尝试用 C 解释上面的代码。我在那里得到了预期的结果,hello world hello world

#include <stdio.h>

int main()
{
    char const volatile * volatile x = "";
    char const volatile * volatile const * xPtr = &x;
    x = "hello world";
    char const volatile * volatile const * xPtr2 = &x;

    printf("%s  %s\n", *xPtr, *xPtr2);

    return 0;
}

最佳答案

I get hello world.

你应该在开头有两个空格。

What point did I miss until now?

使用调试器向您展示了原因,但简而言之,您只有 Java 中的引用和原语。没有引用文献。

char const volatile * volatile const * xPtr = &x;

Java 中没有这样的东西。

Presumably a new object is created there implicitly.

一个新的 StringBuilder 和一个新的 char[] 是隐式创建的,但我认为这不是你的意思。

单步执行代码

    String s = text;  // text = "", s = ""
    text = "hello world"; // text = "hello world", s = ""
    String t = text; // text & t = "hello world", s = ""
    System.out.println(s + "   " + t);

关于java - String = 运算符引用或在这种情况下创建新的 String 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51176173/

相关文章:

java - 如何漂亮地打印一个复杂的 Java 对象(例如,带有对象集合的字段)?

python - python中字符串的打印长度

Java纸牌游戏。如何在main中调用

java - Servlet 初始化内部的 Init 过滤器

java - 如何使用 double 格式的数字为范围之间的随机间隔编写代码?

python - sys.intern() 无法在切片时实习字符串

c++ - 来自 std::unordered_set<char> 的有效构造 std::string

javascript - 我必须返回过滤后的对象

java - servlet 发生异常时如何重定向到错误页面?

Java:为 GZIPOutputStream 的 Deflater 使用 setDictionary 时出现 CRC 错误