Java Reference
In-Depth Information
< Day Day Up >
2. Integer Arithmetic
This section concerns arithmetic on the integral types: byte , char , short , int , and long .
2.1. Nonzero result of % operator has sign of left operand
Prescription: If you need a nonnegative remainder, process the result of the % operator by adding
the modulus if the result is negative.
References: Puzzles 1 and 64 ; [JLS 15.17.3].
2.2. Integer arithmetic overflows silently
Prescription: Use types that are sufficiently large to hold results, including intermediate results.
References: Puzzles 3 , 26 , 33 , and 65 ; [JLS 4.2.2].
2.3. The sign of the difference of int values does not reliably indicate
their order
Prescription: Do not use a subtraction-based comparator unless you are sure that the difference
between values will never be greater than Integer.MAX_VALUE . Note that this is a special case of
Trap 2.2.
References: Puzzle 65 ; [EJ Item 11].
2.4. Compound assignment operators can cause silent narrowing cast
Prescription: Don't use compound assignment operators on variables of type byte , short , or char .
References: Puzzles 9 and 31 ; [JLS 15.26.2].
2.5. Integral types are asymmetric: Integer.MIN_VALUE is its own
negation, as is Long.MIN_VALUE
Prescription: Program defensively. Use long instead of int if necessary.
References: Puzzles 33 and 64 ; [JLS 15.15.4].
2.6. Shift operators use only the low-order bits of their right operand
 
 
Search WWH ::




Custom Search