这两个条件的区别?

时间:2012-10-26 09:14:44

标签: java string if-statement

对不起,如果我的问题很愚蠢或无关紧要。但我只是想知道在这两种情况下会发生什么。

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 个答案:

答案 0 :(得分: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");
    }

答案 1 :(得分:2)

第二个不会抛出NullPointerException。但又被认为是错误的代码,因为str可能null you do not detect that bug at this point instead you detect it somewhere else1

  1. 选择首选null,因为它可以帮助您在早期阶段找到程序中的错误。
  2. 如果strnull,则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");
        }
    
  3. 对于第一种情况

    {{1}}

答案 2 :(得分:2)

实际上两者都是一样的。这两者没有区别。 http://www.javaworld.com/community/node/1006 Equal方法比较两个字符串对象的内容。因此,在第一种情况下,它将str变量与“test”进行比较,然后将“test”与str变量进行比较。

答案 3 :(得分:1)

第一次if - 语句测试,str是否等于"test"。第二个if - 语句测试,"test"等于str。因此,这两个if - 语句之间的区别在于,首先使用参数str"test"对象发送消息。然后str对象进行比较,是否等于参数并返回truefalse。第二个if - 语句向"test"发送消息。 "test"也是一个字符串对象。现在"test"进行比较,是否等于str并返回truefalse

答案 4 :(得分:1)

他们几乎一样。

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

第二个变体不能抛出NullPointerException,因为它显然不是null。

答案 5 :(得分:0)

当您尝试首先修复静态字符串时,可以避免在许多情况下出现nullpointer异常。

相关问题