这两种条件之间有什么区别?

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");
        }
    }
}

这两个条件得到的结果是相同的,但我知道它们之间有一些区别。我不清楚具体原因是什么。请问这两个条件之间有何不同?

6个回答

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 异常。但是这仍被视为糟糕的代码,因为可能会发生 strnull 的情况,而且你没有在此时检测到该错误,而是在其他地方检测到。

  1. Given a choice prefer 1 since it helps you to find bugs in the program at early stage.
  2. Else add check for null if str is null then you will be able to make out are strings really not equal or is second string does not present

    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");
    }

2

实际上两者是相同的。这两个之间没有区别。http://www.javaworld.com/community/node/1006 Equal方法比较两个字符串对象的内容。因此,在第一个例子中,它将str变量与“test”进行比较,在第二个例子中,它将“test”与str变量进行比较。


1
第一个if语句测试是否str等于"test"。第二个if语句测试"test"是否等于str。所以这两个if语句的区别在于,第一个if语句向str对象发送一个带有参数"test"的消息。然后str对象比较它是否等于该参数并返回true或false。第二个if语句向"test"发送一个消息。"test"也是一个字符串对象。现在"test"比较它是否等于str并返回true或false。

1

它们基本上是一样的。

唯一的区别在于,第一个示例使用字符串对象“str”的equal()方法,并将“test”字符串作为参数,而第二个示例使用字符串“text”的equal()方法,并将“str”作为参数。

第二种变体不会抛出NullPointerException,因为它显然不为空。


0

当您首先尝试修复静态字符串时,可以避免许多情况下的空指针异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接