Home > Java > Javagetting Started > Is null an object in java?

Is null an object in java?

王林
Release: 2019-12-06 14:34:27
Original
2884 people have browsed it

Is null an object in java?

null in java 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.

Detailed explanation of null keyword

1. First of all, null is a keyword, 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.

2. Just like every basic type has a default value, for example, the default value of int is 0, the default value of boolean is false, and null is the default value of any reference type. 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 (when you use an uninitialized local variable, the compiler will warn you). To demonstrate this fact, you can observe this reference variable by creating a variable and then printing its value.

Free video tutorial recommendation: java video

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, look at the following code:

String str = null;
Integer i = null;
Double d = null; 

String myStr = (String) null;
Integer myI = (Integer) null;
Double myD = (Double) null;
Copy after login

You can see that during compilation and runtime, null is cast to any Reference types are all feasible and will not throw a null pointer exception at runtime.

4. Null can be assigned to reference variables, but you cannot assign null to basic type variables, such as int, double, float, and boolean. The compiler will report an error.

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.

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:

Integer iAmNull = null;
int i = iAmNull; // Remember - No Compilation Error
Copy after login

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

public class Test3 {
  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 = (int) numberAndCount.get(i);//NullPointerException
      numberAndCount.put(i, count++); 
    } 
  }
}
package test;import java.util.HashMap;
import java.util.Map;
public class Test3 {
  public static void main(String args[]) throws InterruptedException {    
      Map numberAndCount = new HashMap<>();    
      Integer[] numbers = {3, 5, 7,9, 11, 13, 17, 19, 2, 3, 5, 33, 12, 5};    
      for(Integer i : numbers){      
          Integer count = (Integer) numberAndCount.get(i);      
          numberAndCount.put(i, count++); // NullPointerException    
      }    
  }
}
Copy after login

This code looks very simple and error-free. All you do is find how many times a number appears in an array, which is the typical technique for finding duplicates in Java arrays. The developer first gets the previous value, then adds one, and finally puts the value back into the Map.

Programmers may think that when calling the put method, the first way is to convert int to report a null pointer, verify what was said before. In the second way, autoboxing will handle the unboxing problem by itself, but it forgets that when a number has no count value, the get method returns null instead of 0, because the default value of Integer is null instead of 0. Autoboxing will return a NullPointerException when passing a null value to an int variable.

6. If a reference type variable with a null value is used, the instanceof operation will return 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");
}
Copy after login

This is a very important feature of the instanceof operation, making it very easy to check the type cast. it works.

7. You may know that you cannot call non-static methods to use a reference type variable with a null value. It will throw a null pointer exception, but you may not know that you can use static methods to use a reference type variable with a null value. Because static methods use static binding, null pointer exceptions will not be thrown. The following is an example:

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

8. You can pass null to the method. At this time, the method can receive any reference type, for example public void print(Object obj)You can call print like this (null). This is OK from a compilation perspective, but the result depends entirely on the method. Null-safe methods, like the print method in this example, do not throw a NullPointerException and simply exit gracefully.

If the business logic allows it, it is recommended to use the null safe method.

9. You can use == or != operations to compare null values, but you cannot use other algorithms or logical operations, such as less than or greater than. In Java null==null will return true.

Recommended related articles and tutorials: Getting started with java

The above is the detailed content of Is null an object in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template