JAVA SE6 & Swing Capitulo 02 pag.25 Ej.2

2. Los tipos de datos numéricos no tienen alcance infinito. Construir un programa que multiplique dos números de tipo int con valores próximos al alcance indicado en la tabla. Comprobar que el resultado es incorrecto. Este problema se denomina desbordamiento, y se produce cuando el resultado obtenido no se puede representar empleando el tipo de datos indicado.

Nombre

Tamaño

Alcance

short

16 bits

desde –32768 hasta 32767

int

32 bits

desde –2147483648 hasta

long

64 bits

desde –9233372036854775808 hasta 9233372036854775807

De esta manera si lo que buscamos es conseguir un desbordamiento de memoria solo tenemos que ponerle a cada tipo su máximo y sumarle uno.

image

Pero tal y como se puede contemplar en la imagen el desbordamiento u overflow no se produce, el tipo de dato es cíclico y nos retorno el siguiente valor. Os dejo lo que dice SUN sobre el por que de este funcionamiento.

Why does Java ignore overflow? Most computer hardware has no ability to automatically generate an interrupt on overflow. And some hardware has no ability to detect it. Java would have to explicitly test for it on every add, subtract and multiply, greatly slowing down production. Further ex-C programmers are very used to this cavalier ignoring of overflow, and commonly write code presuming that high order bits will be quietly dropped. The Pentium has hardware overflow detect but no hardware interrupt. So if Java were to support overflow detect, inside the JVM implementation would need to add a JO *jump on overflow" instruction after every add and subtract, and special code to look at the high order bits of the 32x32->64 bit multiply. 64/32->32 bit division might need special handling.