Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between .toString() and (String) cast in Java

I want to read a value from the session object which returns Object type. I know that the object has either true/false value. I would like to convert that value into boolean type. So I have the following code.

session.getAttribute("MyKeyValue"); // It returns Object type

Below throws an Exception.

boolean myBoolVal = Boolean.parseBoolean((String) session.getAttribute("MyKeyValue"));

Below works properly.

boolean myBoolVal = Boolean.parseBoolean(session.getAttribute("MyKeyValue").toString());

Actually, I don't understand why option 1 is not working ?

like image 288
Chintan Avatar asked Feb 06 '23 21:02

Chintan


1 Answers

When the runtime type of the instance returned by session.getAttribute("MyKeyValue") is not a String, casting it to String throws a ClassCastException.

On the other hand, session.getAttribute("MyKeyValue").toString() always works (assuming session.getAttribute("MyKeyValue") is not null), since all Objects have an implementation of the toString() method.

BTW, since session.getAttribute("MyKeyValue") doesn't return a String, it is likely that it returns a Boolean (since you expect Boolean.parseBoolean() to work), so if that is the case, instead of converting it to String and then to Boolean, you can just cast it to Boolean :

Boolean myBoolVal = (Boolean) session.getAttribute("MyKeyValue");
like image 70
Eran Avatar answered Feb 10 '23 00:02

Eran