Null in Java

Source: Internet
Author: User
Tags type casting

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, like Eclipse and NetBeans, can correct the 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:

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 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 = null;  Null can also is assigned to doublestring mystr = (String) null; Null can is type cast to Stringinteger Myitr = (Integer) 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:

int i = NULL; Type Mismatch:cannot convert from null to intshort s = null;  type Mismatch:cannot convert from null to Shortbyte B = null://Type Mismatch:cannot convert from null to byte double d = null;//type Mismatch:cannot convert from null to doubleinteger ITR = null;//This is okint j = 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;int i = 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.

Import Java.util.hashmap;import java.util.map;/** * An example of autoboxing and Nullpointerexcpetion *  * @author Wind OWS 8 */public class Test {public    static void Main (String args[]) throws interruptedexception {      Map Numberandcoun t = new hashmap<> ();      int[] Numbers = {3, 5, 7,9, one, 2, 3, 5, 5;      for (int i:numbers) {         int count = Numberandcount.get (i);         Numberandcount.put (i, count++); NullPointerException here      }}}           

Output:

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 (iamnull instanceof Integer) {   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:

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"); c10/>}

Output:

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:

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 & Gt NULL) {       }}}    

Output:

NULL = = NULL is true in 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.

Null in Java

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.