×

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

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Java String toLowerCase() methods

Java String toLowerCase() method is used to convert all the characters of the String into lower case. Syntax: public String toLowerCase()              public String toLowerCase(Locale locale) Returns: It returns Lower...

1 minute read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.