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
- NullPointerExceptions is unchecked exception
- Please read post Exception handling and java keywords before reading this article
- Usually if program tries to fetch the value from reference and finds nothing as value, then program throws NullPointerException
- 'Zero' is not null
- And empty String is not considered to be null
- 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