9 explanations of NULL in Java (Java null detailed) _java

Source: Internet
Author: User
Tags instance method wrapper

For Java programmers, NULL is a headache. is often harassed by null-pointer anomalies (NPE). Even the inventor of Java admits it was a huge mistake. Why should Java keep null? Null has been around for some time, and I think the Java inventor knows that null is causing more trouble than the problem it solves, but Null still accompanies Java.

I am more surprised because the Java design principle is to simplify things, that is why there is no waste of time on pointers, operator overload, multiple inheritance implementation of the reason, null and this is just the opposite. Well, I really don't know the answer to this question, and I know that regardless of how null is criticized by Java developers and the open source community, we have to be in common with null. Rather than regretting the existence of NULL, we might as well learn null to ensure that NULL is used correctly.

Why do I need to learn null in Java? Because if you are not aware of NULL, Java will cause you to suffer from the exception of the null pointer, and you will also receive a painful lesson. The energetic programming is an art, your team, the customer and the user will appreciate you more. In my experience, one of the most important causes of NULL pointer exceptions is the lack of knowledge about NULL in Java. Many of you are already familiar with NULL, but for those who are not very familiar, you can learn something about null old and new knowledge. Let's go back to some important knowledge of NULL in Java.

What is null in Java?

As I said, NULL is a very important concept in Java. Null was designed to indicate something missing, such as missing users, resources, or something else. But a year later, the headaches of null-pointer anomalies are causing a lot of harassment for Java programmers. In this material, we will learn the basic details of the NULL keyword in Java, and explore techniques to minimize null checks as much as possible and how to avoid disgusting null pointer exceptions.

1 First, NULL is the keyword in Java, like public, static, final. It is case sensitive and you cannot write null or NULL, and the compiler will not recognize them and then make an error.

Copy Code code as follows:

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

Programmers with other languages may have this problem, but the use of the IDE now makes the problem trivial. Now, when you knock on the code, the IDE, like Eclipse and NetBeans, can correct this error. But with other tools like Notepad, Vim, Emacs, this problem can be a waste of your valuable time.
2)Just as each original type has a default value, such as the default value of the int default value of 0,boolean is False,null is the default value of any reference type, which is not strictly the default value for all object types. As you create a boolean-type variable, it takes false as its default value, and any reference variable in Java takes null as the default value. This applies to all variables, such as member variables, local variables, instance variables, and static variables (but when you use a local variable that is not initialized, the compiler warns you). To prove this fact, you can look at the reference variable by creating a variable and then printing its value, as shown in the following figure:
Copy 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 object. As you can see here, I defined myobj as a static reference, so I could use it directly in the main method. Note that the main method is a static method and that non-static variables are not available.

3 We want to clarify some misunderstandings, NULL is neither an object nor a type, it is only a special value, you can give it any reference type, you can also convert null to any type, look at the following code:

Copy Code code as follows:

String str = NULL; Null can is assigned to String
Integer ITR = null; Can assign null to Integer Also
Double dbl = null; Null can also be assigned to Double

String mystr = (string) null; Null can is 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 it is feasible to cast null to any reference type at compile and runtime times, and Null pointer exceptions are not thrown during runtime.
4)Null can be assigned to a reference variable, you cannot assign null to a primitive type variable, such as int, double, float, Boolean. If you do that, the compiler will make an error, as follows:
Copy 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 the base type, a compilation error occurs. However, if you assign null to wrapper class object and then assign object to its respective base type, the compiler will not report it, but you will encounter a null pointer exception at run time. This is caused by the automatic unboxing in Java, and we'll see it at the next point.
5)Any wrapper class that contains a null value throws a null pointer exception when it generates the base data type in the Java unboxing. Some programmers make the mistake of thinking that automatic boxing converts NULL to the default values of their base types, such as converting to int to 0 and Boolean to false, but that is incorrect, as shown here:
Copy Code code as follows:

Integer iamnull = null;
int i = Iamnull; Remember-no compilation Error

But when you run the code snippet above, you will see the main thread throw a null pointer exception on the console. Many of these errors occur when using HashMap and integer key values. An error occurs when you run the following code.
Copy 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 Code code as follows:

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

This code looks very simple and has no errors. All you do is find out how many times a number appears in the array, which is a typical technique for finding duplicates in a Java array. The developer first gets the previous value, then adds one, and finally puts the value back in the map. The programmer might think that when the put method is invoked, the automatic boxing handles the boxed int into Interger, but he forgets that when a number does not count, the HashMap get () method returns Null instead of 0, Because the default value for integer is null instead of 0. When a null value is passed to an int variable, automatic boxing returns a null pointer exception. Imagine if this code is in an if nesting and 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 returns false:

Copy 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 a instance of Integer");
}


Output:
Copy Code code as follows:

I
Amnull is isn't an instance of Integer

This is a very important feature of the instanceof operation, making it useful for type cast checking

7 You may know that a non-static method cannot be invoked to use a reference type variable with a value of NULL. It will throw a null pointer exception, but you may not know that you can use a static method to use a reference type variable with a value of NULL. Because static methods use static bindings, NULL pointer exceptions are not thrown. Here is an example:

Copy 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 is called by null Reference");
  }

   private void Iamnonstaticmethod () {
       System.out.println ("I AM") NON static method, don ' t date to called me by null ');
  }


Output:
Copy Code code as follows:

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

8)You can pass null to a method, and the method can receive any reference type, such as public void print (Object obj), to call print (null). This is possible from a compilation point of view, but the result depends entirely on the method. Null-safe methods, such as the Print method in this example, do not throw null pointer exceptions, but gracefully exit. If business logic allows, it is recommended to use a method of NULL security.

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 returns true in Java, as follows:

Copy 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 Code code as follows:

NULL = NULL = TRUE in Java

This is all about NULL in Java. With some experience in Java programming and using simple techniques to avoid null pointer anomalies, you can make your code null and secure. Because NULL is often a null or uninitialized value, it is the source of confusion. For a method, it is also important to record the behavior of the method when it is logged as a parameter. To summarize, remember that NULL is the default value for any reference type variable, and in Java you cannot use NULL citation to invoke any instance method or instance variable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.