Null Pointer Exception

Null pointer exception is one the Runtime Exception in java.This exception occurs when we try to access null object references values.Lets see the below below example.

package com;

import javax.jws.WebService;

//Service Implementation
@WebService(endpointInterface = "com.IHelloService")
public class HelloServiceImpl implements IHelloService {
 public String welcome(String name) {
  // TODO Auto-generated method stub
    return  "Welcome"+name;
  return null;
 public static void main(String arg[]){
   String name=DBData.getUserName();
   new HelloServiceImpl().welcome(name);

When i execute the above code i will get null pointer exception as below.

Exception in thread "main" java.lang.NullPointerException
 at com.HelloServiceImpl.welcome(HelloServiceImpl.java:12)
 at com.HelloServiceImpl.main(HelloServiceImpl.java:19)

If we look at the exception its clearly mentioned its raised because we are trying to access null reference in line number 12. We are expecting some values from DB but due to some reason we did not get the results from DB,so the null values is passed to method which results null pointer exception.
Possible Reasons for Object Become Null :

1.Object variable declared but never initialized
 2. We are expecting some value from database but its return null due to data issue

  How to handle Null pointer exception
 1. Make sure object is initialized before we use it
 2. We can add null check before access the object.


Post a Comment

Powered by Blogger.