Interesting facts about null in Java

JavaObject Oriented ProgrammingProgramming

There are many facts associated with null in Java. We will discuss a few of them here with examples −

  • The default value of any reference variable in Java is always null.

Example

 Live Demo

public class Demo{
   private static Object my_obj;
   public static void main(String args[]){
      System.out.println("The default value of object my_obj is : " + my_obj);
   }
}

Output

The default value of object my_obj is : null

A class named Demo defines a static object and the main function that shows the default value of this pre-defined object.

  • The not equal to (!=) and comparison (==) operators can be used with the null keyword.

Example

 Live Demo

public class Demo{
   public static void main(String args[]){
      System.out.println("The value of null == null is : ");
      System.out.println(null==null);
      System.out.println("The value of null != null is : ");
      System.out.println(null!=null);
   }
}

Output

The value of null == null is :
true
The value of null != null is :
false

A class named Demo contains the main function that checks to see the output when the null values are compared using ‘==’ operator and when they are checked using the ‘!=’ operator.

  • The keyword null is case-sensitive

Example

 Live Demo

public class Demo{
   public static void main (String[] args) throws java.lang.Exception{
      Object my_obj_1 = NULL;
      Object my_obj_2 = null;
   }
}

Output

/Demo.java:5: error: cannot find symbol
Object my_obj_1 = NULL;
^
symbol: variable NULL
location: class Demo
1 error
raja
Published on 04-Jul-2020 08:32:34
Advertisements