9 things about NULL in Java

Source: Internet
Author: User
Tags type casting

9 things about NULL in Java

For Java programmers, NULL is a headache. It is often harassed by a null pointer exception (NPE).

Even the inventor of Java admits it was a big mistake. Why should Java keep null? Null has been around for some time, and I think the Java inventor knows that null is more troublesome than the problem it solves, but Null still accompanies Java.

I am more and more surprised because Java is designed to simplify things, and that is why there is no time wasted on pointers, operator overloading, and multiple inheritance implementations, and Null is just the opposite. Well, I really don't know the answer to this question, I know that no matter how null is criticized by the Java developer and the open source community, we must exist with NULL. Rather than regretting the existence of NULL, we might as well learn null to make sure 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 a null pointer exception, and you will get a painful lesson. Energetic programming is an art that your team, customers and users will appreciate more about you. In my experience, one of the main causes of NULL pointer exceptions is that knowledge of NULL in Java is not enough. Many of you are already familiar with NULL, but for those who are not very familiar with it, you can learn something about the old and new knowledge of NULL. Let's re-learn some of the important things about NULL in Java.


What is null in Java?

As I said, NULL is a very important concept in Java. Null is designed to represent something that is missing, such as a missing user, resource, or other thing. However, a year later, the headache of a null pointer exception caused a lot of harassment to the Java programmer. In this material, we will learn the basic details of the NULL keyword in Java, and explore some techniques to minimize null checking and how to avoid disgusting null pointer anomalies.

1) First, NULL is a 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.

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

Programmers using other languages may have this problem, but now the use of the IDE has made the problem trivial. Now, when you hit the code, the IDE looks likeEclipse, NetBeans can correct this error. But using other tools like Notepad, Vim, Emacs, this problem will waste your precious time.


2) just as each primitive type has a default value, such as the default value of 0,boolean for int defaults to False,null is the default value for any reference type, not strictly the default value for all object types. Just as you create a Boolean type variable, it will be false as its default value, and any reference variable in Java will be 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, you can observe the reference variable by creating a variable and then printing its value, as shown in the code:

Privatestatic Object myobj;publicstatic void Main (String args[]) {    System.out.println ("What is value of MYOBJC:" + my OBJ);}
What is value of Myobjc:null

This is true for both static and non-static object. As you see here, I define 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 non-static variables cannot be used.

3) to clarify some misunderstandings, NULL is neither an object nor a type, it is only a special value, you can assign it to any reference type, you can convert null to any type , and see the following code:

String str = null;//null can assigned to Stringinteger ITR = null;//You can assign null to Integer alsodouble DBL = n Ull Null can also is assigned to Double String mystr = (String) null;//null can is type cast to Stringinteger Myitr = (Int Eger) null;//It can also is type casted to integerdouble Mydbl = (Double) null;//yes it ' s possible, no error

You can see that it is possible to cast null to any reference type during the compile and run times, without throwing a null pointer exception during runtime.


4)null can be assigned to a reference variable, and 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:

Inti = null;//type mismatch:cannot convert from null to Intshorts = null;//  type Mismatch:cannot convert from nul L to Shortbyteb = null://type mismatch:cannot convert from null to bytedoubled = Null;//type Mismatch:cannot Convert From NULL to double Integer ITR = null;//this is OKINTJ = ITR; This is also OK and 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 the wrapper class object and then assign the object to its own 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 unpacking in Java, and we'll see it in the next point.


5) any wrapper class that contains null values throws a null pointer exception when the Java unboxing generates a basic data type. Some programmers make such mistakes, and they think that Auto boxing will convert NULL to their default value for their base type , for example, to convert int to 0 and Boolean to false, but that's not true, as shown here:

Integer iamnull = Null;inti = Iamnull; Remember-no compilation Error

But when you run the code snippet above, you'll see on the console that the main thread throws a null pointer exception. Many of these errors occur when you use the HashMap and integer key values. An error occurs when you run the following code.
Importjava.util.hashmap;importjava.util.map; /** * An example of autoboxing and nullpointerexcpetion * * @author WINDOWS 8 */publicclass Test {    publicstatic void m Ain (String args[]) throwsinterruptedexception {      Map numberandcount = newhashmap<> ();      int[] numbers = {3,5,7,9,11,13,17,19,2,3,5,33,12,5};       for (inti:numbers) {         intcount = numberandcount.get (i);         Numberandcount.put (i, count++); NullPointerException here      }}}          


Output:

Exceptioninthread "main" java.lang.NullPointerException at Test.main (test.java:25)

This code looks very simple and has no errors. All you have to do is find out how many times a number appears in the array, which is typically the technique of looking for repetition in a Java array. The developer first obtains the previous value, then adds one, and finally puts the value back into the map. Programmers might think that when the put method is called, the auto-boxing handles the boxed int into Interger, but he forgets that when a number is not counted, the HashMap get () method will return null instead of 0. Because the default value of integer is null instead of 0. When a null value is passed to an int variable, the auto-boxing will return a null pointer exception. Imagine if this code is in an if nested, not running in the QA environment, but once you're in the production environment, BOOM:-)


6) If a reference type variable with a null value is used, the instanceof operation will return false:

Integer iamnull = null;if (iamnullinstanceofinteger) {   System.out.println ("Iamnull is instance of Integer");                             } else{   System.out.println ("Iamnull is not a instance of Integer");}

Output:

I

Amnull is isn't an instance of Integer

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


7) You may know that you cannot call a non-static method 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:

Publicclass testing {                publicstatic void Main (String args[]) {      testing myObject = null;      Myobject.iamstaticmethod ();      Myobject.iamnonstaticmethod ();                               }    privatestatic void Iamstaticmethod () {        System.out.println ("I am static method, can be called by null Reference");   }    privatevoid Iamnonstaticmethod () {       System.out.println ("I am NON static method, don ' t date to call me by null"); 
   }

Output:

I am static method, can be called by null Referenceexceptioninthread "main" java.lang.NullPointerException at               testing. Main (TESTING.JAVA:11)

8) You can pass NULL to the method, at which point the method can receive any reference type, such as public void print (Object obj), which can call print (null). This is possible from a compilation point of view, but the result depends entirely on the method. The null-safe method, such as the Print method in this example, does not throw a null pointer exception, but gracefully exits. It is recommended to use a null-safe method if the business logic allows it.

9) You can use the = = or! = action to compare null values, but you cannot use other algorithms or logical operations, such as less than or greater than. Unlike SQL, null==null in Java will return true as follows:

Publicclass Test {     publicstatic void Main (String args[]) throwsinterruptedexception {        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 & Gt NULL) {        }}}    

Output:

NULL = = NULL is Truein Java

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


9 things about NULL in Java

Related Article

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.