• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple program but not getting class cast exception,why so?

 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator





 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For passing "10" along with Integer constructor- As 10 string is parse able to integer its successful. You can try passing "ten" or some other string to get an ParseException.

The second query- Class cast exception- As the reference is actually an Integer, so casting it to Integer doesnt cause an exception. If it were some object of other class- say String you would get a classcast exception when you tried to cast.

Also before every cast- an instance of check is required so that you dont end up with ClassCastExceptions.
 
Aditya Jha
Ranch Hand
Posts: 227
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Think about it... what kind of object are you actually passing in IntegerBox.add method?
 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aditya Jha wrote:
Think about it... what kind of object are you actually passing in IntegerBox.add method?


it returns 10
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vishal Hegde wrote:
Aditya Jha wrote:Think about it... what kind of object are you actually passing in IntegerBox.add method?

it returns 10

That's not quite what he's getting at. This is happening:
- You pass a String into an Integer constructor (check the API and you'll see this constructor exists)
- This results in an Integer object
- The Integer object is passed into the IntegerBox.add method
- Which means the object contained by IntegerBox is an Integer
- Which means the cast back to an Integer works fine
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic