public
class
Demo {
public
static
void
main(String args[])
{
String str=
new
String(
"hello"
);
if
(str==
"hello"
)
{
System.out.println(
"true"
);
}
else
{
System.out.println(
"false"
);
}
}
}
-
答案:false
鏈接:https://www.nowcoder.com/questionTerminal/aab7300da6d1455caffcbda21c10fca5
來源:牛客網
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public
class
Demo {
public
static
void
main(String args[]) {
String str1 =
new
String(
"hello"
);
String str2 =
new
String(
"hello"
);
String str3 =
"hello"
;
String str4 =
"hello"
;
String str5 =
"he"
+
"llo"
;
String str6 =
"he"
;
String str7 =
"llo"
;
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str3==str4);
System.out.println(str3==
"hello"
);
System.out.println(str4==(str6+str7));
}
}
|
上面代碼的輸出結果是:
false
false
true
true
false
1
|
String str1 =
new
String(
"hello"
);
|
1
|
String str3 =
"hello"
;
|
==用來判斷兩個變量是否相等時,如果兩個變量是基本類型變量,且都是數值類型(不要求數據類型嚴格相同),則只要兩個變量的值相等,就返回true;對於兩個引用類型變量,必須指向同一個對象,==才會返回true。
java中使用new String("hello")時,jvm會先使用常量池來管理"hello"常量,再調用String類的構造器創建一個新的String對象,新創建的對象被保存在堆內存中;而直接使用"hello"的字符串直接量,jvm會用常量池來管理這些字符串。故上述程序中str=="hello"返回結果為false
‘==’操作符專門用來比較兩個變量的值是否相等,也就是用來比較兩個變量對應的內存所存儲的數值是否相同,要比較兩個基本類型的數據或兩個引用變量是否相等,只能用==操作。
如果一個變量指向的數據是對象類型的,那么這時候涉及了兩塊內存,對象本身占用一塊(堆內存),變量也占用一塊。對於指向類型的變量,如果要比較兩個變量是否指向同一對象,即要看兩個變量所對應的內存的數值是否相等,這時就需要用==操作符進行比較。
equals方法用於比較兩個獨立對象的內容是否相同。
在實際開發中,我們經常要比較傳遞過來的字符串是否相等,一般都是使用equals方法。
例如:
String a = new String(“foo”);
String b = new String(“foo”);
兩條語句創建了兩個對象,他們的首地址是不同的,即a和b中存儲的數值是不相同的。所以,表達式a==b將返回false,而這兩個對象的內容是相同的,所以表達式a.equals(b)將返回true。