I know this question partially answered here on SO , but there they explain what happens during arithmetic overflow. And in another place according to S.O. they explain how to check for overflow in java code, i.e. prevent him as a programmer.
Here I ask why there are no runtime exceptions and no compiler warnings ?
AFAIK, this has not yet been answered.
In Bruce Eckel's book Thinking in Java , 1st ed. (2000), chapter 3, there is this small java program:
//: Overflow.java // Surprise! Java lets you overflow. public class Overflow { public static void main(String[] args) { int big = 0x7fffffff; // max int value prt("big = " + big); int bigger = big * 4; prt("bigger = " + bigger); } static void prt(String s) { System.out.println(s); } } ///:~
The result of this:
big = 2147483647 bigger = -4
and you get no errors or warnings from the compiler, and no runtime exceptions.
No change if Integer.MAX_VALUE is used instead of "0x7fffffff"
I tried this on some java compilers from 1.2 to 1.6, and it still shows this behavior. Now I wonder why this is so?
- Is this a bug or a function?
- Is it impossible to detect or a low priority problem for compiler developers?
- Is this fixed due to backward compatibility?
- Perhaps in newer versions of the JDK this can be controlled at compile time by allowing the use of the rarely used compiler / -D: or some java VM argument (-XX: ...)?
Only now I used these virtual machines, 32-bit Windows x86
Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
and
Java(TM) SE Runtime Environment (build 1.7.0_03-b05) Java HotSpot(TM) Client VM (build 22.1-b02, mixed mode, sharing)
By the way, C # (Microsoft.CSharp \ v4.0_4.0.0.0) shows the same behavior
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OverflowCheck { class Overflow { static void Main(string[] args) { int big = 0x7fffffff;
Output:
big = 2147483647 bigger = -4