How do I compare strings in Java?(Stackoverflow)

本文解释了Java中使用==与.equals()方法比较字符串的区别。==用于检查两个字符串引用是否指向同一个对象,而.equals()则用于检查两个字符串的内容是否相同。文章还详细介绍了字符串常量池的概念及其如何影响字符串的比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question:

I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.

Is == bad? When should it and should it not be used? What's the difference?


Answer:

== tests for reference equality.

.equals() tests for value equality.

Consequently, if you actually want to test whether two strings have the same value you should use.equals().

There are however a few situations where you can guarantee that two strings with the same value will be represented by the same object because of String interning. Those cases are specified by the Java Language Specification.

== is for testing whether two strings are the same object.

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true 

// concatenation of string literals happens at compile time,
// also resulting in the same object
"test" == "te" + "st" // --> true

// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) // --> false

// interned strings can also be recalled by calling .intern()
"test" == "!test".substring(1).intern() // --> true

It is important to note that == is a bit cheaper than equals() (a single reference comparison instead of a method call), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement.However, these situations are rare.

More information here: What's wrong with using == to compare floats in Java?


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值