发布日期:2016-02-29 17:18:52

== 用来测试reference是否相等(whether they are the same object). 是否同一个对象?

.equals() 用来测试 value 值是否相等 (whether they are logically "equal"). 是否值相同?

记住下面的几个情况:

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

// but they are not the same object(拥有相同值得不同对象是不等同的,正如年龄18的我和年龄18的你不是同一个人)
new String("test") == "test" // --> false 

// ... neither are these (new出来的两个同值对象不相等)
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 

// checks for nulls and calls .equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
String nullString1 = null;
String nullString2 = null;

// Evaluates to true
nullString1 == nullString2;

// Throws an Exception
nullString1.equals(nullString2);
String a="Test";
String b="Test";
if(a==b) ===> true
/*This is a because when you create any String literal, JVM first searches for that literal in String pool, if it matches, same reference will be given to that new String, because of this we are getting*/

                  String Pool
     b -----------------> "test" <-----------------a
"MyString" == new String("MyString") // ==>will always return false.
//Java also talks about the function intern() that can be used on a string to make it part of the cache.
"MyString" == new String("MyString").intern() // ==> will return true.

 

 

 

发表评论