0

Please, explain to me, why do I get longToInt value == -9 when converting long into int? I understand that my long is higher than max value of int and I expected to get some warning by IDE or some error by compiler, not -9. Thx!

long someLong = 21474836471L;
int longToInt = (int) someLong;
System.out.println(longToInt);
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • You drop the first three bits of the `long` with your cast. `System.out.printf("%s%n%s%n", Long.toBinaryString(21474836471L), Integer.toBinaryString((int) 21474836471L));` – Elliott Frisch Jul 05 '21 at 00:01
  • 2
    re *expected ... some error in compiler* -- you explicitly told the compiler that you understood and expected the result, by writing the cast `(int)`. Writing that turned off the warning that you otherwise would get. – iggy Jul 05 '21 at 00:28

0 Answers0