I know this question has been partly answered here on S.O., but there they explain what happens during an arithmetic overflow. And elsewhere on S.O. they explain how to check for overflow in java code, i.e. to prevent it as a programmer.
Here I am asking why there are no exceptions at run-time, and no compiler warnings?
AFAIK, this has not been answered before.
In Bruce Eckel's book Thinking in Java, 1st ed. (2000), Chapter 3, there is this little 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 output of this is:
big = 2147483647 bigger = -4
and you get no errors or warnings from the compiler, and no exceptions at run-time.
No change when Integer.MAX_VALUE is used instead of "0x7fffffff"
I have tried this on some java compilers from 1.2 to 1.6, and it still shows this behaviour. I now wonder why this is so?
- Is this a bug or feature?
- Is this impossible to detect, or a low-priority issue for compiler designers?
- Is this not fixed because of backward compatibility?
- Maybe in newer releases of the JDK, can this be controlled at compile time by enabling some rarely used compiler switch/-D:property, or some java VM argument (-XX:...)?
Just now I used these VMs, Windows x86 32 bit
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 behaviour
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverflowCheck
{
class Overflow
{
static void Main(string[] args)
{
int big = 0x7fffffff; // same behaviour vor Int32.MaxValue
prt("big = " + big);
int bigger = big * 4;
prt("bigger = " + bigger);
prt("done");
}
static void prt(String s) {
System.Console.WriteLine(s);
}
}
}
Output:
big = 2147483647
bigger = -4