简体   繁体   中英

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 ?

By default, integer literals are int s -- 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).

Literals default to int unless otherwise specified. Instead of casting with (long) you can add L to the end of your literal to note that it should be of type long , in the same way that 1.1 is a double and 1.1f is a float .

foo(1000000000L * 10); // output: 10000000000

and

long m = 10000000000L;

When you perform any operation in java, the compiler tries to make an implicit cast to the operands transforming both of them to the bigger datatype. (int / int = result is allways int).

Add an explicit cast to your literals (defaulted to int ) as indicated in other answers:

long l = 1000000000L * 10;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM