James Gosling: idealism, the Internet and Java, Pt I

Sunday 9 May 2021

Demonstration of Java NullPointerException

NullPointerException causes and reasons

Since Java is object oriented programming language, every thing is considered to be an object. and there is always a scope of an object to be null or "No value". 

Since Java supports primitive data types, Java is not considered to be pure Java object oriented programming language. 


Few Notable points about NullPointerException

  1. NullPointerExceptions is unchecked exception
  2. Please read post Exception handling and java keywords before reading this article
  3. Usually if program tries to fetch the value from reference and finds nothing as value, then program throws NullPointerException
  4. 'Zero' is not null
  5. And empty String is not considered to be null
  6. It is not the subclass of RuntimeException class

Demo code that throws NullPointerException 



package com.allabtjava.blog;

public class DemoNullPointerException {

class BeanDemo {
String name;
Integer ID;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
ID = iD;
}
}
public DemoNullPointerException() {
}
public void createNullPointerException() {
BeanDemo bean = new BeanDemo();
bean.setName("All about Java!");
System.out.println(bean.getName());
if(bean.getID() == null) {
throw new NullPointerException();
}else {
System.out.println(bean.getID());
}
}
public static void main(String args[]) {
new DemoNullPointerException().createNullPointerException();
}
}

Output


All about Java!
Exception in thread "main" java.lang.NullPointerException
at com.allabtjava.blog.DemoNullPointerException.createNullPointerException(DemoNullPointerException.java:36)
at com.allabtjava.blog.DemoNullPointerException.main(DemoNullPointerException.java:44)

No comments:

Post a Comment

Popular posts

Demonstration of Java NullPointerException

NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and t...