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. 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 have to coexist with null. Instead of regretting the existence of null, we should learn about null better 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 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.
Copy the code code as follows:
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, 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. Strictly 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 demonstrate this fact, you can observe this reference variable by creating a variable and then printing its value, as shown in the following code:
Copy the code code as follows:
private static Object myObj;
public static void main(String args[]){
System.out.println("What is value of myObjc : " + myObj);
}
What is value of myObjc : null
This is true for both static and non-static objects. 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. See below. Code:
Copy the code code as follows:
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
You can see that casting null to any reference type is possible at compile and run time, and will not throw a null pointer exception 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 throw an error like this:
Copy the code code as follows:
int i = null; // type mismatch : cannot convert from null to int
short s = null; // type mismatch : cannot convert from null to short
byte b = null: // type mismatch: cannot convert from null to byte
double d = null; //type mismatch: cannot convert from null to double
Integer itr = null; // this is ok
int j = itr; // this is also ok, but NullPointerException at runtime
As you can see, when you assign null directly to a primitive type, a compilation error occurs. 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:
Copy the code code as follows:
Integer iAmNull = null;
int i = iAmNull; // Remember - No Compilation Error
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.
Copy the code code as follows:
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
}
}
}
Output:
Copy the code code as follows:
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:25)
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. The programmer may think that when calling the put method, automatic boxing will handle the boxing of int into Interger, but he forgets that when a number does not have a count value, the get() method of HashMap will return null, and Not 0, because the default value of Integer is null not 0. Autoboxing will return a NullPointerException when passing a null value to an int variable. Imagine if this code was inside an if nest and was not running in a QA environment, but once you put it in a production environment, BOOM :-)
6) If a reference type variable with a null value is used, the instanceof operation will return false:
Copy the code code as follows:
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");
}
Output:
Copy the code code as follows:
i
AmNull is NOT an instance of Integer
This is a very important feature of the instanceof operation, making it useful for type cast checks.
7) You may know that you cannot call a non-static method 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 value of null. Because static methods use static binding, null pointer exceptions will not be thrown. Here is an example:
Copy the code code as follows:
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't date to call me by null");
}
Output:
Copy the code code as follows:
I am static method, can be called by null reference
Exception in thread "main" java.lang.NullPointerException
at Testing.main(Testing.java:11)
8) You can pass null to the method, and the method can receive any reference type. For example, public void print(Object obj) can call print(null) like this. This is OK from a compilation perspective, but the result depends entirely on the method. Null-safe methods, such as the print method in this example, do not throw a NullPointerException and simply exit gracefully. If business logic allows it, it is recommended to use null-safe methods.
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. Unlike SQL, null==null will return true in Java, as shown below:
Copy the code code as follows:
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){
}
}
}
Output:
Copy the code code as follows:
null == null is true in Java
This is all about null in Java. With some experience in Java programming and using simple tricks to avoid null pointer exceptions, you can make your code null-safe. Because null is often used as an empty or uninitialized value, it is a source of confusion. For methods, it is also very important to record how the method behaves when null is used as a parameter. All in all, remember that null is the default value of any reference type variable. You cannot use null references to call any instance methods or instance variables in Java.