4 Numbers

 

This chapter covers

  • Problems due to numeric overflow or rounding
  • Mistakes that can occur when handling special numbers, such as Integer.MIN_VALUE or -0.0
  • How to avoid mistakes when doing bit manipulation and using hexadecimal numbers
  • Caveats in seemingly simple numerical algorithms, such as oddness check and clamping
  • Why it’s better to avoid certain numeric data types

Modern programs usually operate with very high-level abstractions. Still, numbers and primitive math is used by programmers quite often. Unfortunately, computer math differs in many ways from real math, and these differences often produce unpleasant bugs. An experienced Java programmer should be aware about many peculiarities of number processing in this language, including numeric overflow and implicit conversions.

4.1 Mistake 26: Accidental use of octal literal

4.2 Mistake 27: Numeric overflow

4.2.1 Overflow in Java

4.2.2 Assigning the result of int multiplication to a long variable

4.2.3 File size, time, and financial computations

4.3 Mistake 28: Rounding during integer division

4.4 Mistake 29: Absolute value of Integer.MIN_VALUE

4.5 Mistake 30: Oddness check and negative numbers

4.6 Mistake 31: Widening with precision loss

4.7 Mistake 32: Unconditional narrowing

4.8 Mistake 33: Negative hexadecimal values

4.9 Mistake 34: Implicit type conversion in compound assignments

4.10 Mistake 35: Division and compound assignment