Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (9.5k points)

Below is the code I’ve to catch and show the exception message: 



    String name = null;

    System.out.println("name=" + name.toString());


catch(Exception e)


    System.out.println("Exception Occured" + e.getMessage());


Can anyone tell me a proper way to avoid NullPointerExceptions? 

1 Answer

0 votes
by (19.7k points)

To reduce NullPointerExceptions, never return null from your methods like below: 

public IList<String> getUserNames()


     //No usernames found...

     return new ArrayList<String>();

     //As opposed to returning null

     return null;


This will return the empty list and result into for(String name :

this.getUserNames()) {...}. 

But if you want to return null, you have to do something like below: 

List<String> userNames = this.getUsernames();

if(userNames != null)

     for(String userName : userNames) {....}

Interested in Java? Check out this Java Certification by Intellipaat.    

Browse Categories