Null Literal – Computer Sir Ki Class

Login


Lost your password?

Don't have an account ?
Register (It's FREE) ×
  

Login
[lwa]



Code Learning #JAVA#3814    siteicon   siteicon  

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

TC++ #3814

Source Code

Run Output

java.lang.NullPointerException
at NullLiteral.main(NullLiteral.java:11)

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



Share

sunmitra| Created: 12-Mar-2018 | Updated: 12-Mar-2018|






Back