Modified code to avoid null pointer exception