gpt4 book ai didi

java - Java 中 == 运算符的工作原理

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

我正在阅读有关 == operator in java 的内容并发现它用于比较内存引用,下面的示例来自给定的链接。

String obj1 = new String("xyz");

// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;

if(obj1 == obj2)
System.out.printlln("obj1==obj2 is TRUE");
else
System.out.println("obj1==obj2 is FALSE");

Note in the code above that obj2 and obj1 both reference the same place in memory because of this line: “String obj2 = obj1;”. And because the “==” compares the memory reference for each object, it will return true. And, the output of the code above will be:

之后我随机编写代码来检查 == 运算符,但为什么在这个示例中它返回 true?

String obj1 = "ABC";
String obj2 = "ABC";
if(obj1 == obj2)
System.out.println("obj1==obj2 is TRUE");
else
System.out.println("obj1==obj2 is FALSE");

“ABC”字符串保存在一个内存位置,然后 obj1 和 obj2 共享该内存引用吗?

甚至 int 也返回 true。

int obj1=3;
int obj2=3;

最佳答案

字符串有点特殊,因为它们使用 String interning 。所以是的,在屏幕后面,这两个字符串具有相同的内存引用(但不要指望它进行字符串比较。请参阅 this question )。

将字符串替换为

Object obj1 = new Object();
Object obj2 = new Object();

您将得到预期的输出。

关于java - Java 中 == 运算符的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32806991/

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