gpt4 book ai didi

java - String + String 与从方法返回的 String + String

转载 作者:行者123 更新时间:2023-11-30 07:17:12 26 4
gpt4 key购买 nike

今天在使用 String 时,我遇到了一种我以前不知道的行为。我无法理解内部发生的事情。

    public String returnVal(){
return "5";
}
String s1 = "abcd5";
String s2 = "abcd"+"5";

String s3 = "abcd5";
String s4 = "abcd"+returnVal();

System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s3 == s4);
System.out.println(s3.equals(s4));

我的期望是从所有 s.o.p 中打印“true”,但 s3 == s4 是 false,为什么?

最佳答案

My expectation is printing "true" from all s.o.p's but s3 == s4 is false, why?

编译器可以内联常量表达式。这意味着

String s1 = "abcd5";
String s2 = "abcd"+"5";
final String five = "5"; // final reference
String sa = "abcd" + five;

都是相同的(除了五个),编译器可以将所有这些表达式简化为“abcd5”

但是,如果编译器无法优化表达式,则会在运行时执行该操作并创建一个新的字符串。这个新字符串不是放置在字符串文字池中的常量(因为它不是字节代码中的文字)

 String s4 = "abcd" + returnVal(); //  not inlined by the compiler.
String f5 = "5"; // not a final reference.
String sb = "abcd" + f5; // evaluated at runtime

它们每次运行时都会创建新的字符串(以及新的 StringBuilderchar[])

关于java - String + String 与从方法返回的 String + String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38181878/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com