A) FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext=facesContext.getExternalContext();
HttpSession session = (HttpSession) externalContext.getSession(false);
if(session.isNew()) { // java.lang.NullPointerException
B) HttpServletRequest req1 = (HttpServletRequest)FacesContext.getCurrentInstance()
.getExternalContext().getRequest();
HttpSession session1=req1.getSession();
if(session1.isNew()) { // no Exception
why case A is throwing NullPointerException where as case B is not.
First, it’s important to understand when and why a
NullPointerExceptionis been thrown. The way you put the question indicates that you don’t understand it. You asked "Why does it throwNullPointerException?". You didn’t ask "Why does it returnnull?".As its javadoc indicates, the
NullPointerExceptionwill be thrown when you try to access a variable or to invoke a method using the period.operator on an object reference which is actuallynull.E.g.
In your particular case, you were trying to invoke the method
isNew()on anullobject. This is thus not possible. Thenullreference has no methods at all. It simply points to nothing. You should be doing a null-check instead.The
getSession()call withfalseargument may namely returnnullwhen the session hasn’t been created yet. See also the javadoc:See the emphasized part.
The
HttpServletRequest#getSession()call which doesn’t take any argument, uses by defaulttrueascreateargument. See also the javadoc:See the emphasized part.
I hope that you’ll take this as a hint to consult the javadocs better. They contain more than often already the answers to your questions as they describe very precisely what the classes and methods do.