Java Null – 7 Unknown Facts about Null in Java
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Before we talk about null in Java, let us go back a few steps and recall what variables in Java are.
Well, simply speaking, they can be thought of as tumblers. And the value of those variables is the water inside the tumbler. Makes sense.
Now, how many types of variables were there?
Well, classifying broadly, there were 2 types.
- Reference types
- Primitive types
Primitive types are the ones that would hold values, and reference types are the ones that can store references.
Null in Java
Since we just read about primitive and reference types in Java, let’s break down a few points.
When primitive values do not have a value explicitly mentioned by the programmer, the default value is stored based on the data type of the variable.
For example, an uninitialized int variable will have 0 as the default value, a boolean variable will have false as the default value and so on…
But what will the reference variables have if they are not explicitly referencing an object in memory? Yes, you guessed it! They would store null!
This is exactly why we need null in Java. It is used for representing references when they are not pointing to any objects in memory. It has a special purpose.
In java, null is literal. It is the same as true or false. It has a special meaning. Many people confuse it with an identifier or a keyword.
Important Facts about Null
There are some facts that are essential to know when you are working with null in Java.
- Null is case-sensitive in nature. This means that you cannot expect NULL to be a “literal” in Java. It’s the same as true and false. These have individual meaning.
- All reference variables have null as their default value.
- The compiler is unable to unbox null objects. It throws a NullPointerException.
- Null is not an instance of any class. Hence a null value will return false if used with the instanceOf operator.
- Static methods are callable with a reference of the null type.
- You cannot call non-static methods with a reference of the null type.
- You can use == and != comparisons with null types in Java.
Java Null Pointer Exception
When the program tries to access a part of the memory which is not initialized by default, then the compiler throws a null pointer exception.
Simply speaking, this is possible when you try to access the 100th element of an array of 50 elements.
Java example to evaluate all the facts of null:
package com.dataflair.javanull; public class Main { private static Object a; public static void staticmethodtest() { System.out.println("This is a static method! "); } public void nonstaticmethodtest() { System.out.println("This is a non-static method!"); } public static void main(String[] args) { Integer i = null;//null is a reserved word //Returns error-> Integer j=NULL;//NULL is invalid. System.out.println("The default value of a is "+a); Integer value1=null ; //Returns error -> int value=value1; Cannot unbox null type. System.out.println(value1 instanceof Integer);//returns false.this is because null isnt an instance of any class. Main ob=null; ob.staticmethodtest(); //Returns error-> ob.nonstaticmethodtest(); This is not possible. NullPointerException. String a=null; String b=null; System.out.println(a==b);//returns true; } }
Output:
This is a static method!
true
- We came to know about the Null Pointer Exception in Java. But now we will learn how to avoid it.
We know that we will encounter a null pointer exception when the compiler tries to access some data which is null.
Any data value which is not present in memory or set to null explicitly will return a Null Pointer Exception if accessed.
A primary example of this would be trying to access an index in the array which is out of bounds. Let us see this with an example.
Program to illustrate Java NullPointerException:
package com.dataflair.javanull; import java.util.*; public class Main { public static String nullreturnfunc() { return null; } public static void main (String[] args) { String test; test=nullreturnfunc(); System.out.println(test.charAt(3)); } }
Output:
at Main.main(Main.java:21)
- Now we can either use a try-catch method or a simple if-else block to prevent these types of errors. The try-catch method is the more sensible way to do it. But both work.
The same program when modified becomes:
package com.dataflair.javanull; import java.util.*; public class Main { public static String nullreturnfunc() { return null; } public static void main (String[] args) { String test; test=nullreturnfunc(); if(test!=null) System.out.println(test.charAt(3)); else System.out.println("The value is null!"); } }
Output:
- Now we try to use try-catch to avoid null pointer exceptions.
We can use any kind of message we want in the catch block.
If you are having difficulty understanding what try-catch is, please refer to our exception handling in Java article.
The program becomes:
package com.dataflair.javanull; import java.util.*; public class Main { public static String nullreturnfunc() { return null; } public static void main (String[] args) { String test; test=nullreturnfunc(); try { System.out.println(test.charAt(3)); } catch(Exception e) { System.out.println("The value is null!"); } } }
Output:
Best Ways to Use Null
The following are recommended practices to bear in mind when utilizing null in Java:
- Beware of null references: Before using a reference variable, always take into account the possibility that it might be null.
- Make strategic use of null checks: Only when required, add null checks to avoid NullPointerExceptions.
- Examine alternatives to null: You may be able to completely avoid null references by redesigning your program in certain situations.
- Null usage of documents: If you choose to use null, be sure to explain its purpose and methodology in order to make the code easier to read.
Summary
We learned a lot about null in Java. It is essential to have a good grasp of null in Java.
Even experienced Java programmers sometimes run into fatal NullPointerExceptions and have no idea how to fix the bug.
Hence a clear understanding of Java Null will come in handy.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google