0

Consider the following example in java (or c#):

 //doesn't work
 Object a = 5.2f;
 int b = (int)a; //java.lang.ClassCastException: java.base/java.lang.Float cannot be cast to java.base/java.lang.Integer

 //must first cast object to float, then can cast to integer
 Object a = 5.2f;
 int b = (int)(float)a;

I had always just assumed casting is transitive (A=B & B=C THEN A=C), however that obviously isn't the case.

Can someone explain exactly why this doesn't work?

NSjonas
  • 10,693
  • 9
  • 66
  • 92

0 Answers0