Posts

Showing posts from February, 2015

Inconsistent operation widen rules in Java

Overview When you perform a unary or binary operation in Java the standard behaviour is to use the widest operand (or a wider one for byte, short and char).  This is simple to understand but can be confusing if you consider what the optimal type is likely to be. Multiplication When you perform multiplication, you often get a much large number than either of the individual numbers in magnitude. i.e. |a*b| >> |a| and |a*b| >> |b| is often the case.  And for small types this works as expected Consider this program public static void main(String[] args) throws IOException {     System.out.println(is(Byte.MAX_VALUE * Byte.MAX_VALUE));     System.out.println(is(Short.MAX_VALUE * Short.MAX_VALUE));     System.out.println(is(Character.MAX_VALUE * Character.MAX_VALUE));     System.out.println(is(Integer.MAX_VALUE * Integer.MAX_VALUE));     System.out.println(is(Long.MAX_VALUE * Long.MAX_VALUE)); } static String is(byte b) {     return "byte: " + b; } s