2

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?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

0

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)
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110