Q:

Why the compiler cast long to int?

1 public class Foo {
2   public static void main(String[]a){
3       foo(1000000000); // output: 1000000000
4       foo(1000000000 * 10); // output: 1410065408
5       foo((long)1000000000 * 10); // output: 10000000000
6       
7       long l = 1000000000 * 10;
8       foo(l); // output: 1410065408
9       //long m = 10000000000; // compile error
10  }

    static void foo(long l){
        System.out.println(l);
    }
}

Why line 4 output: 1410065408 instead of 10000000000?
Why line 9 is a compile error? can't the compiler create a Long as the expected type is a Long?

A:

By default, integer literals are ints -- which means they abide by int arithmetic, and they can't represent numbers larger than an int can hold. Note that in your line 4, the two ints are first multiplied (using int arithmetic) and only then is the result casted to a long -- but by then it's too late, and the overflow has already happened.
To put a long literal, just append L to it:
long m = 10000000000L;

(A lowercase 'l' would also compile, but that looks like a digit '1' so you should avoid it; use the capital 'L' so that it stands out).

