The null keyword in java is a literal. It is neither a data type nor an object. The null (all letters in small case) is a literal that represents the absence of a value. For example, if you assign a null to an object of string class, it does not refer to any value in the memory.
Important points regarding null literal
- You cannot assign null to primitive data types such as int, float, double etc.
- You can assign null to string or wrapper classes of primitive types as shown below.
Valid cases:
String str = null; Integer i = null; Double d = null;
Invalid cases: The null cannot be assigned to primitive data types.
int i = null; //not allowed, error float f = null; //not allowed, error //all letters of null should be in small cases Double d = NULL; //Error, Cannot find symbol 'NULL'
Example of null literal
public class JavaExample { public static void main(String[] args) { String str = null; if(str == null){ System.out.println("String str is a null String"); }else{ System.out.println("String str is a not a null String"); } } }
Output:
String str is a null String