Digging deep into Null in Java
There is absolutely no Java programmer who has escaped the NullPointerException. Even though the creation of null was indispensable, other complexities that it causes have led the programmers to avoid using it. But you must know how to overcome such bugs without ignoring them.
This article will lay a foundation for understanding null in Java.
Variables in Java:
You would have already learned about variables in Java. However, there is a bridge between this concept and what we will study in this article, which is null. So, let’s have a glimpse at variables before we start.
Types of variables in java:
There are 2 types of variables in java:
1. Reference variables
2. Primitive variables
Let us first look at a brief description about them; primitive variables store that value that is declared for it. At the same time, the reference variables store references.
Role of null in Java:
As mentioned earlier, the primitive variables should be declared by the user. In some exceptional cases, when the user does not explicitly mention a value, the default value is taken into account. 0 is the default value for integer data types, and false is the default value for Boolean datatypes.
Now, what could be assigned to a reference variable when no value is mentioned? This is where null comes into action. It is a reserved word or a ‘literal’ that holds the value of true or false.
Properties of Java null:
Null as a reserved word:
There is a fine line between a keyword and a reserved word. ‘null’ comes under the category of a reserved word. It denotes the value of either true or false as a literal.
Sample program for null as a reserved word in Java:
public class FirstCode{ static FirstCode obj; public static void main(String[] args) { System.out.println(obj); } }
Output:
Null as a default value:
When a value is not assigned to a variable, some default value will be assigned automatically. For instance, the default value for the int data type is 0, and false for the boolean datatype.
In the same way, any reference type variable that is not initialized during the time of declaration holds the value ‘null’ in it.
Everything you need to know about null in Java:
1. The rule of case sensitivity applies to null:
As null is literal, it is highly case-sensitive. Writing null as NULL or Null will not give the desired result in Java as in C language.
Example program to denote that null is case sensitive:
public class FirstCode{ public static void main (String args[]) throws java.lang.exception { Object n = NULL; // this will create compile-time error Object n1 = null; // this will be accepted by the compiler } }
Output:
Can’t find symbol ‘NULL’
variable NULL
class FirstCode1 error
2. Null as a reference variable:
In java, the default value for any undefined reference variable is null. To check it, let’s do a small program.
Example program to indicate null as a reference variable:
public class FirstCode { private static Object n; public static void main(String args[]) { System.out.println("Value assigned to the Object n is: " + n); } }
Output:
3. Null suits all datatypes:
As it is a special value, null is not confined to any specific data type. It can be assigned to any reference type.
Examples of null being assigned to various reference types:
String s = null; // null being assigned to a string datatype Integer i = null; // null being assigned to an integer Double d = null; // null being assigned to double
Examples of null being type casted to other reference types:
String s1 = (String) null; // null being type casted to string Integer i1 = (Integer) null; // null being type casted to integer Double d1 = (Double) null; // null being type casted to double
4. instanceof operator in Java:
The instanceof operator returns true if the object used is an instance of the mentioned type. For this, the value of the expressions should not be null.
Sample program for null with instanceof operator:
public class FirstCode { public static void main (String args[]) throws java.lang.Exception { Integer a = null; Integer b = 1; System.out.println(a instanceof Integer); // prints false System.out.println(b instanceof Integer); // prints true as b!=0 } }
Output:
true
5. Autoboxing and Unboxing in Java:
While performing autoboxing and unboxing operations, an error is thrown if a null value is assigned to a primitive boxed data type. This is a Nullpointer exception error.
Sample program to depict the role of null in boxed data type:
public class FirstCode { public static void main (String args[]) throws java.lang.Exception { Integer it = null; int i = it; // as the null is unboxed, it throws a NullpointerException } }
Output:
at FirstCode(FirstCode.java:6)
6. Static vs Non-static methods in Java:
The static methods can be called using reference variables as they are bonded using static binding. Whereas, on the other side, the non-static method on a reference variable will throw NullPointerException.
Sample program to denote null in static and non-static methods:
public class FirstCode { public static void main(String args[]) FirstCode o = null; o.staticMethod(); o.nonstaticmethod(); } private static void staticMethod() { System.out.println(" The static method can be called using null reference"); } private void nonStaticMethod() { System.out.println("Non-static method cannot be called using null reference"); } }
Output:
Exception in thread “main”
java.lang.NullPointerException
at FirstCode.main(FirstCode.java:5)
7. Comparison (==) and Not equal to (!=) operators in java:
Java allows == and != operators with null. It checks the presence of null objects.
Sample program with == and != to find null:
public class FirstCode { System.out.println(null!=null); // prints false System.out.println(null==null); // prints true } }
Output:
true
NullPointerException (NPE) in java:
The NullPointerException in Java is invoked when a program tries to access uninitialized memory.
In other words, the access to a null reference throws a NullPointerException.
Sample program to call a method that returns null:
public class FirstCode { public void npe_example() { String ans = npe_example2(); if(ans.equals("FirstCode") System.out.println("FirstCode"); } private npe_example2() { return null; } public static void main(String args[]) { NullpointerExample n = NullpointerExample(); n.npe_example(); } }
Output:
FirstCode.npe_example(FirstCode.java:6)
at FirstCode.npe_example.main(FirstCode.java:16)
Accessing an array in java:
Previously, we have seen how a NullPointerException error is thrown for a single value. Following is a sample program for accessing a null array to get a NullPointerException:
Sample program to access Java null array:
public class FirstCode { private static void sumofarray(int[] arr) { int sum = arr[0]; } public static void main(String args[]) { sumofarray(null)}; } }
Output:
FirstCode.sumofarray(FirstCode.java:4)
FirstCode.main.(FirstCode.java:8)
Therefore, the NullpointerException occurs whenever we try to access methods, variables, or arrays of a null object.
Handling NullPointerException:
Now, we are clear regarding why NullPointerException occurs. Whenever there is an exception, better methods to handle it should be practiced. Here is how we can handle NullPointerException in Java.
The presence of a try-catch block checks the reference status of a variable before dereferencing. The if-else condition also gives the desired result.
Sample program that throws NullPointerException:
public class FirstCode { public static String npe_example() { return null; } public static void main(String args[]) { String ans; ans = npe_example(); System.out.println(ans.charAt(5)); } }
Output:
at FirstCode.main(FirstCode.java:10)
Now let’s try the same program to avoid the NullPointerException by if-else condition:
Sample program to avoid NullPointerException using if-else condition:
public class FirstCode { public static String npe_example() { return null; } public static void main(String args[]) { String ans; ans = npe_example(); if(ans!=null) System.out.println(ans.charAt(5)); else System.out.println("Cannot process - Null value"); } }
Output:
Sample program to avoid NullPointerException using try-catch block:
public class FirstCode { public static String npe_example() { return null; } public static void main(String args[]) { String ans; ans = npe_example(); try { System.out.println(ans.charAt(5)); } catch(Exception e) { System.out.println("Cannot process - Null value"); } } }
Output:
Conclusion
Now, you will be having a clear idea about null and its uses in Java. In a nutshell, the null values act as reference variables and are case-sensitive. Any access to the null reference throws a NullPointerException.
And we have already seen the sample programs in the article. Now it is your time to give NullPointerExceptions a shot by dealing with it.