[JAVA] getAttribute () and unboxing

I'm doing Servlet and

HttpSession session = request.getSession();
boolean hasError = (Boolean)session.getAttribute("hasError");

I wrote the code. As a result, this has thrown a NullPointerException.

Since the return value of getAttribute () is Object type, it is necessary to cast it with the wrapper class (Boolean in this case). However, when getAttribute () is called for the first time, the return value becomes null, so as a result of trying to unbox the null of Boolean type and assign it to boolean type, it becomes NullPointerException. It was.

I should have been careful about null when unboxing happened, but this was a bit unexpected for me personally, so I'll make a note of it.

Recommended Posts

getAttribute () and unboxing
== and equals
Difference between getText () and getAttribute () in Selenium