java – Why does the following operation produce -1?

Question:

double m = (byte) 110_987_654_6299.123_34;

Answer:

To be fair, the result (the value of m ) will be -1.0 , not -1 .

3 actions take place:

  1. double number 110_987_654_6299.123_34 is cast to int . The result will be 2147483647
  2. int number 2147483647 is cast to byte . The result will be -1
  3. byte number -1 is cast to double . The result will be -1.0

Why the cast works this way – you can read in the documentation . In short, then:

  • when casting double to byte (the right side of the expression), double is first cast to int , and only then – int to byte
  • casting double to int in case of exceeding the allowed int value returns the maximum value of int
  • casting int to byte just takes the last 8 bits from int
Scroll to Top