Home  >  Article  >  Java  >  null in JAVA

null in JAVA

高洛峰
高洛峰Original
2016-11-23 10:10:011385browse

For Java programmers, null is a headache. You are often harassed by Null Pointer Exceptions (NPE). Even the inventor of Java admitted that this was a huge mistake on his part. Why does Java keep null? The null has been around for a while, and I think the Java inventors knew that the null caused more trouble than the problems it solved, but the null is still with Java.

I am more and more surprised, because the design principle of Java is to simplify things, that is why no time is wasted on pointers, operator overloading, and multiple inheritance implementation, but null is just the opposite. Well, I don't really know the answer to this question, what I do know is that no matter how criticized null is by Java developers and the open source community, we must coexist with null. Rather than regretting the existence of null, we should learn better about null and ensure that null is used correctly.

Why do you need to learn null in Java? Because if you don't pay attention to null, Java will make you suffer from NullPointerException, and you will learn a painful lesson. Energetic programming is an art that your team, customers, and users will appreciate more. In my experience, one of the main reasons for null pointer exceptions is insufficient knowledge of null in Java. Many of you are already familiar with null, but for those who are not, you can learn something old and new about null. Let’s re-learn some important knowledge about null in Java.

What is Null in Java?

As I said, null is a very important concept in Java. The original intention of null design is to represent something missing, such as a missing user, resource or other things. However, a year later, the troublesome null pointer exception caused a lot of harassment to Java programmers. In this material, we will learn the basic details of the null keyword in Java, and explore some techniques to minimize null checks and how to avoid nasty null pointer exceptions.

1) First of all, null is a keyword in Java, like public, static, and final. It is case-sensitive, you cannot write null as Null or NULL, the compiler will not recognize them and report an error.

Object obj = NULL; // Not Ok
Object obj1 = null  //Ok

Programmers using other languages ​​may have this problem, but now the use of IDE has made this problem trivial. Now, when you type code, IDEs like Eclipse and Netbeans can correct this error. But using other tools like notepad, Vim, and Emacs, this problem will waste your precious time.

2) Just like every primitive type has a default value, such as the default value of int is 0, the default value of boolean is false, null is the default value of any reference type, loosely speaking, it is the default value of all object types . Just like you create a boolean variable that has false as its default value, any reference variable in Java has null as its default value. This is true for all variables, such as member variables, local variables, instance variables, static variables (but when you use an uninitialized local variable, the compiler will warn you). To prove this fact, you can observe this reference variable by creating a variable and then printing its value, as shown in the following code: is correct. As you can see here, I defined myObj as a static reference so I can use it directly in the main method. Note that the main method is a static method and cannot use non-static variables.

3) We want to clarify some misunderstandings. Null is neither an object nor a type. It is just a special value. You can assign it to any reference type. You can also convert null to any type. Let’s see The following code:

private static Object myObj;
public static void main(String args[]){
    System.out.println("What is value of myObjc : " + myObj);
}


You can see that casting null to any reference type is feasible at compile and run time, and no null pointer exception will be thrown at run time.

4) Null can be assigned to reference variables, but you cannot assign null to basic type variables, such as int, double, float, and boolean. If you do that, the compiler will report an error like this:

What is value of myObjc : null


As you can see, when you assign null directly to a basic type, a compilation error will occur. But if you assign null to the wrapper class object, and then assign object to the respective basic types, the compiler will not report it, but you will encounter a null pointer exception at runtime. This is caused by automatic unboxing in Java, which we will see in the next bullet point.

5) Any wrapper class containing a null value will throw a null pointer exception when Java unboxes and generates basic data types. Some programmers make the mistake of thinking that autoboxing will convert null to the default value of the respective basic type, such as 0 for int and false for boolean type, but that is not correct, as shown below:

String str = null; // null can be assigned to String
Integer itr = null; // you can assign null to Integer also
Double dbl = null;  // null can also be assigned to Double
 
String myStr = (String) null; // null can be type cast to String
Integer myItr = (Integer) null; // it can also be type casted to Integer
Double myDbl = (Double) null; // yes it's possible, no error


But when you run the above code snippet, you will see the main thread throwing a null pointer exception on the console. Many such errors occur when using HashMap and Integer key values. An error will appear when you run the following code.

import java.util.HashMap;
import java.util.Map;
 
/**
 * An example of Autoboxing and NullPointerExcpetion
 *
 * @author WINDOWS 8
 */
public class Test {
    public static void main(String args[]) throws InterruptedException {
      Map numberAndCount = new HashMap<>();
      int[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5};
 
      for(int i : numbers){
         int count = numberAndCount.get(i);
         numberAndCount.put(i, count++); // NullPointerException here
      }      
    }
}

   


输出:

Exception in thread "main" java.lang.NullPointerException
 at Test.main(Test.java:25)

   


这段代码看起来非常简单并且没有错误。你所做的一切是找到一个数字在数组中出现了多少次,这是Java数组中典型的寻找重复的技术。开发者首先得到以前的数值,然后再加一,最后把值放回Map里。程序员可能会以为,调用put方法时,自动装箱会自己处理好将int装箱成Interger,但是他忘记了当一个数字没有计数值的时候,HashMap的get()方法将会返回null,而不是0,因为Integer的默认值是null而不是0。当把null值传递给一个int型变量的时候自动装箱将会返回空指针异常。设想一下,如果这段代码在一个if嵌套里,没有在QA环境下运行,但是你一旦放在生产环境里,BOOM:-)

6)如果使用了带有null值的引用类型变量,instanceof操作将会返回false:

Integer iAmNull = null;
if(iAmNull instanceof Integer){
   System.out.println("iAmNull is instance of Integer");                            
 
}else{
   System.out.println("iAmNull is NOT an instance of Integer");
}

   


输出:

i
   
AmNull is NOT an instance of Integer

   


这是instanceof操作一个很重要的特性,使得对类型强制转换检查很有用

7)你可能知道不能调用非静态方法来使用一个值为null的引用类型变量。它将会抛出空指针异常,但是你可能不知道,你可以使用静态方法来使用一个值为null的引用类型变量。因为静态方法使用静态绑定,不会抛出空指针异常。下面是一个例子:

public class Testing {            
   public static void main(String args[]){
      Testing myObject = null;
      myObject.iAmStaticMethod();
      myObject.iAmNonStaticMethod();                            
   }
 
   private static void iAmStaticMethod(){
        System.out.println("I am static method, can be called by null reference");
   }
 
   private void iAmNonStaticMethod(){
       System.out.println("I am NON static method, don&#39;t date to call me by null");
   }

   


输出:

I am static method, can be called by null reference
Exception in thread "main" java.lang.NullPointerException
               at Testing.main(Testing.java:11)

   


8)你可以将null传递给方法使用,这时方法可以接收任何引用类型,例如public void print(Object obj)可以这样调用print(null)。从编译角度来看这是可以的,但结果完全取决于方法。Null安全的方法,如在这个例子中的print方法,不会抛出空指针异常,只是优雅的退出。如果业务逻辑允许的话,推荐使用null安全的方法。

9)你可以使用==或者!=操作来比较null值,但是不能使用其他算法或者逻辑操作,例如小于或者大于。跟SQL不一样,在Java中null==null将返回true,如下所示:

public class Test {
 
    public static void main(String args[]) throws InterruptedException {
 
       String abc = null;
       String cde = null;
 
       if(abc == cde){
           System.out.println("null == null is true in Java");
       }
 
       if(null != null){
           System.out.println("null != null is false in Java");
       }
 
       // classical null check
       if(abc == null){
           // do something
       }
 
       // not ok, compile time error
       if(abc > null){
 
       }
    }
}

   


输出:

null == null is true in Java

   


这是关于Java中null的全部。通过Java编程的一些经验和使用简单的技巧来避免空指针异常,你可以使你的代码变得null安全。因为null经常作为空或者未初始化的值,它是困惑的源头。对于方法而言,记录下null作为参数时方法有什么样的行为也是非常重要的。总而言之,记住,null是任何一个引用类型变量的默认值,在java中你不能使用null引用来调用任何的instance方法或者instance变量。


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn