gpt4 book ai didi

Java 引用资料。 Java 是否对字符串文字进行特殊检查?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:31:37 25 4
gpt4 key购买 nike

public class Test {
int multiple;
public static void main(String[] args){

String string1 = "string";
String string2 = "string";
String string4 = "Changed";

String string3 = new String("string");

System.out.println("string1 == string2: " + (string1 == string2));\\true
System.out.println("string1 == string4: " + (string1 == string4));\\false
System.out.println("string1 == string3: " + (string1 == string3));\\false

}


}

我知道如果引用相同,== 运算符将返回 true。我想知道的是,Java 在创建对象之前是否检查字符串文字的内容?

最佳答案

您看到了 Java string interning 的副作用之一.来自 the JLS §3.10.5 :

...A string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Lots more reading on SO ,特别是:

关于Java 引用资料。 Java 是否对字符串文字进行特殊检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10163444/

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