session.getAttribute("username").toString(); ERROR OCCURS IN JSP PAGE?

Viewed 143

The value in session is null. When I write this code in a JSP page, an error occurs.

String user = session.getAttribute("username").toString();

But when I write it like this no error occurs.

String user = (String)session.getAttribute("username");

Why?

1 Answers

It is because session.getAttribute("username") is returning null which can be cast into String without any issue but if you try to perform any operation on null refefernce, you will get NullPointerException. Given below is a demo:

class Main {
    public static void main(String[] args) {
        String user = (String) null;// No problem
        System.out.println(user);
        user.toString();// This will throw NullPointerException
    }
}

Output:

null
Exception in thread "main" java.lang.NullPointerException
    at Main.main(Main.java:5)
Related