This write-up aims to present a thorough overview of the below-listed concepts associated with the null keyword:
- What does null mean in Java?
- Default value of Java reference variable
- How to assign/pass null to an object reference variable?
- How to assign/pass null to primitive data type in Java?
- Is null case sensitive in java?
What does null mean in Java?
It is a reserved keyword that can be used to point to the absence of something. The null keyword is case-sensitive, which means the Java compiler will consider “null” and “Null” two different things. If we assign “Null” to an object, consequently, we will encounter an error. However, the program will work fine if we assign “null” to an object. Moreover, accessing a null reference can throw a NullPointerException. In Java, it is not possible to pass null as a value to call a method containing a primitive data type.
Default value of Java reference variable
Let’s consider the below snippet to understand what’s the default value of a reference variable in Java:
private static ExampleClass object;
public static void main(String args[])
{
System.out.println("Default Value of reference variable: " + object);
}
}
Let’s execute the above-given program to see what will be the default value for the reference variable:
The output verified that the reference variable has, by default, “null” value.
How to assign/pass null to an object reference variable?
Java allows us to pass a null value to an object reference variable:
System.out.println("Default Value of reference variable: " + object);
In the above program, we created an object of the class and assigned it a “null” value:
This is how we can assign a null value to an object.
How to assign null to primitive data type in Java?
We can assign a “null” value to any primitive type like int, string, etc. The below-given program will guide you on how to assign a null value to the primitive data types:
System.out.println("Result: " + message);
Integer intVal= null;
System.out.println("Result: " + intVal);
In the above snippet we created one string type and one integer type variable and assigned a “null” value to both of them:
The output verified that we can assign a null value to any primitive data type.
Is null case sensitive in java?
Let’s consider the below-given piece of code to check whether the “null” keyword is case sensitive or not:
The above-specified code will generate a compile-time error as shown in the following screenshot:
The above screenshot verified that “null” is a case-sensitive keyword.
Conclusion
In Java, null is a reserved keyword that can be used to point to the absence of something. The null keyword is case-sensitive, which means the Java compiler will consider “null” and “Null” two different things. This write-up explained the working of the null keyword with the help of some appropriate examples.