Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaInteresting facts about null in Java

Interesting facts about null in Java

Almost all the programming languages are bonded with null. There is hardly a programmer, who is not troubled by null. 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 that every Java programmer should know: 

  • In Java, null is a special value that represents the absence of a value or reference. It is used to indicate that a variable or object does not currently have a value assigned to it.
  • The null value is not the same as an empty string or an empty array. An empty string is a string that contains no characters, while an empty array is an array that contains no elements.
  • The Java programming language has a built-in null type, called “null”, which is a subtype of all reference types. However, it cannot be used as a type for a variable, because it doesn’t have any instance and cannot be instantiated.
  • Java provides a special operator called the “null coalescing operator” (??), which can be used to assign a default value to a variable if it is null. This operator is introduced in Java SE 14 and can be used as follow: int x = y ?? 0;
  • It is considered a best practice to check for null values before performing any operations on them, to avoid the risk of a NullPointerException (NPE). NPE is considered one of the most common exceptions in Java and can cause unexpected behavior or crashes in a program.
  • In Java, null is also used to indicate that a method does not return any value. This is known as a “void” return type. A void method does not return any value and is typically used for performing an action, such as printing to the console or updating a database.
  • In addition, null can be used as a default value for optional parameters in a method. This allows a method to be called without specifying a value for that parameter, and the null value will be used instead.
  • It is not recommended to use null as a value for a variable or object that is intended to hold a value of a primitive data type, such as int or double, because it will cause a compile-time error.
  • The use of null in Java can be a source of confusion and subtle bugs, so it is important to be aware of its behavior and how to properly handle it in your code to prevent errors.

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

Java




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


Output:

5: error: cannot find symbol
 can't find symbol 'NULL'
                 ^
   variable NULL
 class Test
1 error 

2. Reference Variable value: Any reference variable in Java has a default value null

Java




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


Output:

Value of object obj is : null 

3. Type of null: 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 type cast null to any type Examples:

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

4. Autoboxing and unboxing : During auto-boxing and unboxing operations, compiler simply throws Nullpointer exception error if a null value is assigned to primitive boxed data type. 

Java




public class Test {
    public static void main(String[] args)
        throws java.lang.Exception
    {
        // An integer can be null, so this is fine
        Integer i = null;
 
        // Unboxing null to integer throws
        // NullpointerException
        int a = i;
    }
}


Output:

 Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:6) 

5. instanceof operator: The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). At run time, 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 type casting checks. 

Java




public class Test {
    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:

false 
true

6. 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 static method with reference variables with null values. Since static methods are bonded using static binding, they won’t throw Null pointer Exception. 

Java




public class Test {
    public static void main(String args[])
    {
        Test 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:

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

7. == and != The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java. 

Java




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


Output:

true
false

8. “null” can be passed as an argument in the method :

We can pass the null as an argument in java and we can print the same. The data type of argument should be Reference Type. But the return type of method could be any type as void, int, double or any other reference type depending upon the logic of program.

Here, the method “print_null” will simply print the argument which is passed from the main method.

Java




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


Output :

Hey, I am : null

9. ‘+’ operator on null :

We can concatenate the null value with String variables in java. It is considered a concatenation in java.

Here, the null will only be concatenated with the String variable. If we use “+” operator with null and any other type(Integer, Double, etc.,) other than String, it will throw an error message. 

Integer a=null+7 will throw an error message as “bad operand types for binary operator ‘+’ “

Java




import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        String str1 = null;
        String str2 = "_value";
        String output = str1 + str2;
        System.out.println("Concatenated value : "
                           + output);
    }
}


Output

Concatenated value : null_value

This article is contributed by Gaurav Miglani. If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks. 

Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

RELATED ARTICLES

Most Popular

Recent Comments