Difference between null.equals (str) and str.equals (null) in conditional expression

package test1;

public class javatest1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str="123";
        String str1=null;
        //str-test
        if("123"==str)
        {
            System.out.println("the result of judge is true");
        }
        else
        {
            System.out.println("the result of judge is false");
        }
        if(str=="123")
        {
            System.out.println("the result of judge is true");
        }
        else
        {
            System.out.println("the result of judge is false");
        }
        
        //str1-test
        if("123".equals(str1))
        {
            System.out.println("the result1 of judge is true");
        }
        else
        {
            System.out.println("the result1 of judge is false");
        }
        //通过debug模式调试,在此处遇到了空指针错误
        if(str1.equals("123"))
        {
            System.out.println("the result1 of judge is true");
        }
        else
        {        
            System.out.println("the result1 of judge is false");
        }
    }

}


First look at the above example, the results of the operation:

Obviously, when str1 is empty, a null pointer exception occurs in operation str1.equals ("123"). So the reason why in many programming examples is to put the constant in the expression in front and the variable in the back, is to avoid such a null pointer exception, especially in web development, different pages If you don't use this way of writing the value between the two, it may lead to a null pointer exception, which in turn may lead to the result of the page crashing directly. Based on this situation, this constant is first, and the variable is written as a programming standard.

It should be written as: "123" .equals (str1)

 


————————————————
Copyright Statement: This article is an original article of CSDN blogger "hymKing", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement for reprint .
Original link: https://blog.csdn.net/hymking/article/details/8849844

Published 31 original articles · Likes6 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/u012824529/article/details/103782527