本文介绍了这两个条件的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果我的问题很愚蠢,那就不重要了。但我只是想知道在这两种情况下会发生什么。

Sorry if my question is silly or not it doesnot matter. But i just want to know what will happen in these two conditions.

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

两者仅提供相同的结果。但我知道有一些原因。我不知道。这两个条件有什么区别?

Both are giving same results only. But i know there is some reasons.I dont know about that. What is difference between these two conditions?

推荐答案

它们之间没有任何区别。许多程序员使用第二种方法只是为了确保他们没有得到 NullPointerException 。这就是全部。

There are no difference between them at all. Many programmers use the 2nd way just to make sure that they don't get a NullPointerException. That's all.

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

这篇关于这两个条件的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 07:28