2012-10-26 156 views
4

對不起,如果我的問題是愚蠢或不是沒關係。但我只想知道在這兩種情況下會發生什麼。這兩個條件之間的區別?

public class Test { 
    public static void main(String[] args) 
    { 
     String str="test"; 
     if(str.equals("test")){ 
      System.out.println("After"); 
     } 
     if("test".equals(str)){ 
      System.out.println("Before"); 
     } 
    } 
} 

兩者僅給出相同的結果。但我知道有一些原因,我不知道。這兩個條件有什麼區別?

回答

12

他們之間沒有任何區別。許多程序員只是用第二種方法來確保他們沒有得到NullPointerException。就這樣。

String str = null; 

    if(str.equals("test")) { // NullPointerException 
     System.out.println("After"); 
    } 
    if("test".equals(str)) { // No Exception will be thrown. Will return false 
     System.out.println("Before"); 
    } 
2

第二個不扔NullPointerException。但同樣它被認爲是不好的代碼,因爲它可能會發生strnullyou do not detect that bug at this point instead you detect it somewhere else

  1. 如果可以選擇喜歡1,因爲它可以幫助你早期發現程序中的錯誤。
  2. 否則爲null如果str增加檢查null,那麼你就可以做出來的都是字符串真的不等於或者是第二個字符串不存在

    if(str == null){ 
    //Add a log that it is null otherwise it will create confusion that 
    // program is running correctly and still equals fails 
    } 
    if("test".equals(str)){ 
        System.out.println("Before"); 
    } 
    

對於第一種情況

if(str.equals("test")){//Generate NullPointerException if str is null 
     System.out.println("After"); 
    } 
0

當您嘗試第一次修復靜態字符串時,您可以在許多情況下避免出現nullpointer異常。

2

其實兩者都是一樣的。這兩者之間沒有區別。 http://www.javaworld.com/community/node/1006等式方法比較兩個字符串對象的內容。因此,在第一種情況下,它將str變量與「test」進行比較,然後在第二個比較中將「test」與str變量進行比較。

1

第一if語句來測試,是否str等於"test"。第二個if -statement測試,是否"test"等於str。因此,這兩個if -statements之間的區別在於,您首先使用參數"test"str對象發送消息。然後str對象進行比較,無論它是否等於參數並返回truefalse。第二個if -statement發送消息到"test""test"也是一個字符串對象。所以現在比較"test",是否等於str並返回truefalse

1

他們做的差不多。

唯一的區別是第一個示例使用字符串對象「str」的equal()方法和「test」-string作爲參數,而第二個示例使用字符串「text」的equal()方法,以「str」作爲參數。

第二個變體不能拋出NullPointerException,因爲它顯然不爲null。