×

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class in java.lang package, it is invoked whenever we attempt to carry out specific operations with or without null, and occasionally we aren't even aware of when it has occurred. Every Java programmer needs to be aware of the following significant null-related features in Java:

1. The null is Case Sensitive.

It is not possible to write NULL or 0, as in C, because Java's keywords are case-sensitive. The null is literal in Java.

Filename: Example1.java

public class Example1
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // compile-time error : can't find symbol 'NULL'
        Object ob = NULL; 
         
        //runs successfully
        Object ob1 = null; 
    }
}

Output

Facts about null in Java

2. Reference Variable value

In Java, the default value of every reference variable is null.

Filename: Example2.java

public class Example2
{
    private static Object b; 
    public static void main(String args[])
    {
        // it will print null;
        System.out.println("Value of object b is : " + b);
    } 
}

Output

Facts about null in Java

3. Type of null

Contrary to popular belief, the null is not an object or a type. In Simple terms, it's a unique value that can be applied to any reference type, and you can type cast null in any kind.

// null can be assigned to a String
    String str = null; 
    
    // you can assign null to Integer, also
    Integer itr = null; 
    
    // Double can also be given a null value.
    Double dbl = null; 
        
    // null can be type cast to String
    String myStr = (String) null; 
    
    // it can also be type cast to Integer
    Integer myItr = (Integer) null; 
    
    // yes, it's possible; no error
    Double myDbl = (Double) null;

4. Autoboxing and Unboxing

If a null value is assigned to a primitive boxed data type during auto-boxing and unboxing operations, the compiler throws a Nullpointer exception error.

Filename: Example3.java

  public class Example3 {
    public static void main(String[] args)
        throws java.lang.Exception
    {
        // This is acceptable because an integer can be null. 
       Integer i = null;
 
        // Unboxing null to integer throws
        // NullpointerException
        int a = i;
    }
}

Output

Facts about null in Java

5. The instanceof operator

If an object is an instance of the specified type, the Java instanceof operator is used to check this (class, subclass, or interface). If the Expression value is not null, the instanceof operator's result is true at runtime. This is an essential property of instanceof operation, making it useful for type-casting checks.

Filename: Example4.java

public class Example4 {
    public static void main(String[] args)
        throws java.lang.Exception
    {
        Integer i = null;
        Integer j = 10;
 
        // prints false
        System.out.println(i instanceof Integer);
 
        // Compiles successfully
        System.out.println(j instanceof Integer);
    }
}

Output

Facts about null in Java

6. Static vs Non-static Methods

NullPointerException will be thrown if a non-static method is called on a reference variable with a null value. Still, we can call static methods on reference variables with null values. Static methods won't throw a Null Pointer Exception because they are bound using static binding.

Filename: Example5.java

public class Example5 {
public static void main(String args[])
{
Example5 obj = null;
obj.staticMethod();
obj.nonStaticMethod();
}


private static void staticMethod()
{
// Can be called by null reference
System.out.println(" static method,can be called by null reference & quot");
}


private void nonStaticMethod()
{
// Can not be called by null reference
System.out.print("Non - static method - ");
System.out.println("cannot be called by null reference & quot");
}
}

Output

Facts about null in Java

7. == and !=

In Java, the comparison and not equal operators are permitted with null. This can be used to check for null with Java objects. 

Filename: Example6.java

public class Example6 {

public class Example6 {
    public static void main(String args[])
    {
 
        // return true;
        System.out.println(null == null);
 
        // return false;
        System.out.println(null != null);
    }
}

Output

Facts about null in Java

8. The method accepts the argument "null" as a parameter.

In Java, we can print null and pass it as an argument. The argument's data type should be Reference Type. However, depending on the logic of the program, the return type of a method could be any type, such as void, int, double, or any other reference type.

The argument passed from the main method will just be printed in this case by the method "print null."

Program

Filename: Example7.java

import java.io.*;
 
class Example7 {
    public static void print_null(String str)
    {
        System.out.println("Hey, I am : " + str);
    }
    public static void main(String[] args)
    {
        Example7.print_null(null);
    }
}

Output

Facts about null in Java

9. ‘+’ operator on null

In Java, the null value can be concatenated with String variables. In Java, it is regarded as a concatenation.

Only the String variable will be concatenated with the null in this case. If the "+" operator is used with null and any other type (such as Double, Integer, etc.) besides String, an error will be raised.

The error message for the integer a=null+7 is “bad operand types for binary operator '+'”.

Program

Filename: Example8.java

import java.io.*;
 
class Example8 {
    public static void print_null(String str)
    {
       String str1 = null;
       String str2 = "_value";
       String output= str1+ str2;
       System.out.println("Concatenated value : "
                           + output);


    }
}

Output

Facts about null in Java

Related Topics

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.