Arithmetic limitations

Expect the unexpected:

Figure 142. Strange things I Slide presentation Create comment in forum
byte count = 91;   // o.K.

int i = 91;

byte count2 = i;   //  Compile error: Incompatible types
                   // Required: byte Found: int

byte points = 130; // Compile error: Incompatible types
                   // Required: byte Found: int

Figure 143. Strange things II Slide presentation
final int i = 91;

byte count = i;   //  o.K.

Figure 144. Arithmetic overflow pitfalls Slide presentation Create comment in forum
int count  = 2147483647;
int points = 2147483647;

int sum = count + points;
System.out.println("Sum = "   +  sum);

Result:

Sum = -2
  01111111_11111111_11111111_11111111
+ 01111111_11111111_11111111_11111111
_____________________________________
  11111111_11111111_11111111_11111110

This exceeds the four byte limit of int variables. Thus the leading 1 will be discarded leaving us with a result of 11111111_11111111_11111111_11111110 equalling -2 with respect to four byte integer two complement representation.

Why not using float / double in favour of bounded byte, short, int, long for arithmetics?

Figure 145. Limited precision Slide presentation Create comment in forum
float float2Power31 = Integer.MAX_VALUE + 1f;

float floatDoubleMAX_VALUE = 2 * float2Power31* float2Power31 - 1f; // 2^63 - 1

System.out.format( "   Float value: %f\n", floatDoubleMAX_VALUE);
System.out.println("Expected value: "   +  Long.MAX_VALUE);

Result:

   Float value: 9223372036854776000.000000
Expected value: 9223372036854775807

Figure 146. FloatConverter Slide presentation Create comment in forum
FloatConverter