Numerical assignment should cause an error

I did some tests with numerical conversions and translations in Java and I found this weird 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 does it compile?

+3
source share
2 answers

Integer overflow remains invisible in Java, so multiplication works fine. However, the literal that you specified is too large and therefore is a compiler error.

, Java , JLS. , , - - .

Sun Java , :

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

, , . .

+7

Java , .

, :

int x = Integer.MAX_VALUE + 1;
System.out.println(x);

Java . :

-2147483648

Integer.MIN_VALUE. , . Java BigInteger , .

0

Source: https://habr.com/ru/post/1785997/


All Articles