Null or null value judgment processing – Java

1,错误用法一: 

if (name == "") {
     //do something
}

2,错误用法二: 
if (name.equals("")) {
     //do something
}


3,错误用法三: 
if (!name.equals("")) {
     //do something
}

Let's explain: the above error usage 1 is the most easily made and least easily found by beginners, because their syntax itself is OK, and the java compiler does not report errors when compiling. However, this condition may cause a bug in the program at runtime and will never be true, that is, the statements in the if block will never be executed. The above usage 2 and usage 3 are mistakes that many Java experts are easy to make. Why are they wrong? Maybe you'll wonder. Yes, their writing itself is correct, but without a null judgment condition, imagine what will happen if name = null? As a result, your program will throw a NullPointerException exception, and the system will be suspended and no longer provide normal services. Of course, the exception is if the name has been judged null before. The correct writing should first add name= Null condition, for example:

if (name != null && !name.equals("")) {
     //do something
}

或者

if (!"".equals(name)) {//将""写在前头,这样,不管name是否为null,都不会出错。
     //do something
}

Here is a simple example:

TestNullOrEmpty.java
public class TestNullOrEmpty {

    public static void main(String[] args) {
         String value = null;
         testNullOrEmpty(value);
        
         value = "";
         testNullOrEmpty(value);
        
         value = " ";
         testNullOrEmpty(value);
        
         value = "hello me! ";
         testNullOrEmpty(value);
     }
    
    static void testNullOrEmpty(String value) {
        if (value == null ) { //正确的写法
             System.out.println("value is null. ");
         } else if ("".equals(value)) { //正确的写法
             System.out.println("value is blank but not null. ");
         } else {
             System.out.println("value is /" " + value + "/" ");
         }
        
        if (value == "") {  //NG 错误的写法
        //别用这种写法
         }
     }
}

Compilation execution:

c:/>javac TestNullOrEmpty.java

c:/>java TestNullOrEmpty
value is null.
value is blank but not null.
value is " "
value is "hello me!"
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>