字串比較辨析
阿新 • • 發佈:2018-12-17
java中的資料型別分為字元型,數值型,布林型和引用型別,其中字元型、數值型、布林型統稱為基本資料型別
1、觀察基本資料型別的比較,利用“==”進行比較
public class MyInterface{
public static void main(String[] args){
int x = 23;
int y = 23;
System.out.println(x == y); //return value:true
}
}
觀察用 “==”進行String物件的比較
public class MyInterface{ public static void main(String[] args){ String str1 = "Hello"; String str2 = new String("Hello"); System.out.println(str1 == str2); } }
上述程式碼返回值是false,這是為什麼呢?
因為String是引用型別,直接使用“== “ 比較的是指向字串的引用,即儲存字串的地址,在java中遇到new關鍵字就要開闢新空間,所以返回值為false
如果要比較字串的內容就需要用String類的equals()方法進行比較如下述程式碼
public class MyInterface{ public static void main(String[] args){ String str1 = "Hello"; String str2 = new String("Hello"); System.out.println(str1.equals(str2)); //input:true } }
2、再觀察下面的程式碼
public class MyInterface{
public static void main(String[] args){
String str1 = "Hello";
String str2 = "Hello";
System.out.println(str1 == str2); //input:true
}
}
上面的程式碼使用”==“比較時返回值卻為 true,這就涉及到java中的物件池的概念。
物件池:JVM底層會自動維護一個字串的物件池,如果現在採用直接賦值的形式進行String的物件例項化,該物件會自動儲存在這個物件池中。如果下次繼續使用直接賦值的模式宣告String物件,此時物件池若有指定內容,則直接使用;如果沒有,則開闢新的堆空間將其儲存在物件池中供下次使用
上述程式碼中str2指向的字串與第一次的字串的內容相同,JVM沒有新開闢空間,所以用 == 比較地址的時候,返回true
3、在用java判斷使用者輸入的字串是否與特定字串相等,請看下面程式碼:
public class MyInterface{
public static void main(String[] args){
String str = null; //假設由使用者輸入
//System.out.println(str.equals("hehe")); //執行時異常
/**Exception in thread "main"
java.lang.NullPointerException
at MyInterface.main(MyInterface.java:229)*/
System.out.println("hehe".equals(str)); //返回false
}
}
所以在比較字串是否相等時,使用 :
String str = " ";
"特定字串".equals(str2); //推薦使用該形式
str2.equals(特定字串); //有可能產生空指標異常