// This code shows some unexpected results of java math operations // Author: mhornick // Date: 1/10/2013 package cs2710; public class MathDemo { /** * @param args - not used */ public static void main(String[] args) { // this code causes a positive integer value to overflow on addition int x = 0x7FFFFFFF; // 0111 1111 1111 1111 1111 1111 1111 1111 System.out.println(x); // largest int in decimal format int y = x + 1; // increment the largest int by 1 System.out.println(y); // ...largest negative int is the result! // this code causes a negative integer value to overflow on subtraction x = 0x80000000; // 1000 0000 0000 0000 0000 0000 0000 0000 (largest negative int) y = x-10; // try to make it even more negative System.out.println(y); // ...we get a positive int as a result! // Moral of the story: java does not generate errors on overflow in addition/subtraction! x = 0x0FFFFFFF; // 268,435,455 y = 0x0FFFFFFF; int z = x*y; // theoretical answer: 72,057,593,501,057,025 (0xFF FFFF E000 0001 - 56 bits!!) System.out.println(z); // we get a bogus negative result since only the first 32 bits were saved! // Moral of the story: don't run with scissors! } }