String comparison

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

Objects.equals() checks for nulls before calling .equals() so you don't have to (available as of JDK7, also available in Guava).

Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals().

You almost always want to useObjects.equals(). In the rare situation where you know you're dealing with interned strings, you can use ==.

// 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 

// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true

// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,496评论 0 23
  • 最近自己越来越不想说话,尽管思绪万千,但我懂多说无益必自毙,或者沉默是最美的语言,所以还是选择沉默吧。 自从步入婚...
    哼哼不哼阅读 1,846评论 0 0
  • 老舅走了,走得很急,就像他的脾气,老舅走的时候有一只眼睛没闭上,大舅捋了好几次,却怎么都闭不上,不知道是不是心里...
    矮油3147阅读 3,764评论 0 0
  • 收拾明天返校的行李,没想到清理完就已经是这个点了。寂静的夜,又令我思索起来……隔壁房里传来阵阵鼾声,想必老爸老...
    侧耳呢喃阅读 1,553评论 0 0

友情链接更多精彩内容