Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why ClassCastException

 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following code

I would have thought that it compiled with no issue, but apparently it throws a ClassCastException and I'm not sure why. I thought that you could easily cast an Object to a String
 
Liutauras Vilda
Bartender
Pie
Posts: 2792
112
BSD VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jason Attin wrote:I would have thought that it compiled with no issue

That code should compile with no issues, just throw an exception at run time. Why? Simply because not every Object is a String, and indeed in your case it isn't, so exception is thrown at run time.

In case Object is a String, then exception wouldn't be thrown, i.e.

And opposite assignment is always allowed and cast not needed at all, because every String is an Object, always, i.e.
 
timothy adigun
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:
Jason Attin wrote:
In case Object is a String, then exception wouldn't be thrown, i.e.



Or if he explicitly call the function toString like so:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic