Null Literal
Use of a special case of using null as a literal for nullifying a reference.
Learning Objectives
- Nullifying a reference so that it relieves memory.
Source Code
|
Run Output
Code Understanding
Note: This code will give runtime error in it has been purposefully written so to show how null literal works.
void show() { System.out.println(“This will print only if object is not null referenced”); }
This method has been created to demonstrate the effect of nullifying an object reference
NullLiteral ob=new NullLiteral();
An object reference variable ob has been created here;
ob=null;
null literal has been assigned to object reference variable. This means that the reference place memory has been cleared.
ob.show();
This line will give null pointer exception, as the ob reference has been nullified.
int a[]={1,2};
Here an array reference has been created as variable a.
a=null;
Array reference a has been assigned the null literal.
a[0]=4;
This line will also give null pointer exception if the previous exception line is commented.
Notes
- Sometimes people take null as a keyword. It is just a reserved word like true and false. All these reserved words are used as literals only.
Common Errors
- The null literal assignment can not be done on primitive datatypes.
Suggested Filename(s): NullLiteral.java
sunmitra| Created: 12-Mar-2018 | Updated: 12-Mar-2018|