String比較

public class Demo {java

   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
來源:牛客網

jvm

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


‘==’操做符專門用來比較兩個變量的值是否相等,也就是用來比較兩個變量對應的內存所存儲的數值是否相同,要比較兩個基本類型的數據或兩個引用變量是否相等,只能用==操做。 spa

若是一個變量指向的數據是對象類型的,那麼這時候涉及了兩塊內存,對象自己佔用一塊(堆內存),變量也佔用一塊。對於指向類型的變量,若是要比較兩個變量是否指向同一對象,即要看兩個變量所對應的內存的數值是否相等,這時就須要用==操做符進行比較。 code

equals方法用於比較兩個獨立對象的內容是否相同。 對象

在實際開發中,咱們常常要比較傳遞過來的字符串是否相等,通常都是使用equals方法。 內存

例如:     ci

    String a = new String(「foo」); 開發

    String b = new String(「foo」); 字符串

兩條語句建立了兩個對象,他們的首地址是不一樣的,即a和b中存儲的數值是不相同的。因此,表達式a==b將返回false,而這兩個對象的內容是相同的,因此表達式a.equals(b)將返回true。get

相關文章
相關標籤/搜索