How to avoid null pointer exception in java -


this question has answer here:

i curious know proper way avoid nullpointerexceptions.

try {     string name = null;     system.out.println("name=" + name.tostring()); } catch(exception e) {     system.out.println("exception occured" + e.getmessage()); } 

here catching , showing exception message. want know proper way handle or avoiding such situations.

other catching error, if going work might null, might want throw in null checks.

what reduce chances of having make null checks, never return null methods, unless necessary, instance:

public ilist<string> getusernames() {      //no usernames found...      return new arraylist<string>();       //as opposed returning null      return null; } 

by returning empty list, call above code result so: for(string name : this.getusernames()) {...}. if no user names found, loop not execute.

if on other hand, return null, need so:

list<string> usernames = this.getusernames(); if(usernames != null)      for(string username : usernames) {....} 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -