Facts About Null Value in Java

Price: INR 8,999.00
Price: INR 15,999.00
Was: INR 16,999.00

Let’s see the role of Null value in Java, I hope all you have troubled by Null once in your career. We will see the Application of null in this tutorial post.

 

In Java, null is associated java.lang.NullPointerException. As it is a class in java.lang package, it is called when we try to perform some operations with or without null and sometimes we don’t even know where it has happened.

Below are some important points about null in java which every Java programmer should know:

 

Applications of Null Value in Java

Null is Case Sensitive –

Null is case sensitive in Java. null is literal in Java and because keywords are case-sensitive in java, we can’t write NULL or 0 as in C language.

Output

 

instanceof operator

The java instanceof operator in java is used to test whether the object is an instance of the specified type (class or subclass or interface). At runtime, the result of the instanceof operator is true if the value of the Expression is not null.
This is an important property of instanceof operation which makes it useful for typecasting checks.

Output :

false
true

 

Type of null

In Java, Unlike the common misconception, null is not Object or neither a type. It’s just a special value, which can be assigned to any reference type and you can typecast null to any type. Let’s have some examples :

 

Reference Variable value

Any reference variable in Java has default value null. Let’s try with a small example :

Output :

Value of object obj is : null

 

Comparision  == and !=

The comparison and not equal to operators are allowed with null value in Java. This can make useful in checking for null with objects in java.

Output :

true
false

 

Static vs Non static Methods

We cannot call a non-static method on a reference variable with null value, it will throw NullPointerException, but we can call the static method with reference variables with null values. Since static methods are bonded using static binding, they won’t throw Null pointer Exception.

Output :

static method, can be called by null referenceException in thread “main”
java.lang.NullPointerException
at Test.main(Test.java:5)

 

This is all about Null in Java, I hope this tutorial will help to get the better knowledge of Java and crack the Java Interviews.

0 Comment

Leave a Reply