aspose file tools*
The moose likes Beginning Java and the fly likes Simple program but not getting class cast exception,why so? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Simple program but not getting class cast exception,why so?" Watch "Simple program but not getting class cast exception,why so?" New topic
Author

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

Vishal Hegde
Ranch Hand

Joined: Aug 01, 2009
Posts: 1055







http://www.lifesbizzare.blogspot.com || OCJP:81%
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3071
    
  33

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.


Mohamed Sanaulla | My Blog
Aditya Jha
Ranch Hand

Joined: Aug 25, 2003
Posts: 227


Think about it... what kind of object are you actually passing in IntegerBox.add method?
Vishal Hegde
Ranch Hand

Joined: Aug 01, 2009
Posts: 1055

Aditya Jha wrote:
Think about it... what kind of object are you actually passing in IntegerBox.add method?


it returns 10
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4392
    
    8

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Simple program but not getting class cast exception,why so?