Java – numeric assignment should throw an error
I'm doing some tests with number conversion and cast in Java, and I find this strange behavior (for me)
class Test { public static void main(String[] args) { //int y = 100000000000000; //does not compile int x = 100000 * 1000000000; //compile (why?) System.out.println(x); //x is 276447232 } }
Basically, X and y should be the same number: why compile?
Solution
No integer overflow was detected in Java, which is why multiplication works normally However, the text you said is too large, so it is a compilation error
I think that although most Java compilers calculate this value in advance at compile time, it is not required by JLS So it won't be an error because different compilers may compile a piece of code or produce errors - which is not good
The Sun Java compiler actually performs the calculation because the disassembly shows:
Compiled from "x.java" class x extends java.lang.Object{ x(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: ldc #2; //int 276447232 2: istore_1 3: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream; 6: iload_1 7: invokevirtual #4; //Method java/io/PrintStream.println:(I)V 10: return
The important thing to note here is that for all intents and purposes, the result must be the same as the result calculated at run time Therefore, no compiler errors will occur here