Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting syntax error in Java code: Cannot cast from Object to int

Tags:

java

I keep getting the syntactic error in Java code:

 Cannot cast from Object to int.

The problem code is like this:

int a = (int)obj;//obj is of Object type

But I have always been using this trick around, and only get the error recently.

My question:

  1. Is this a real syntactic error?
  2. Is there any configuration that can hide such syntactic error?.
like image 353
FaceBro Avatar asked Dec 02 '25 08:12

FaceBro


1 Answers

Object to int is two steps - first you need to convert the Object to an Integer, then you need to convert the Integer to an int.

Fortunately auto-boxing will handle the second conversion for you, but you still need to explicitly make the first conversion:

 int a = (Integer)obj;
like image 89
Tim B Avatar answered Dec 04 '25 23:12

Tim B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!