简体   繁体   English

long a = 1 和 long a = 1L 的区别

[英]Difference between long a = 1 and long a = 1L

My question is long a = 1;我的问题是long a = 1; an integer in reality?现实中的整数? And is it the same as long a = 1L;long a = 1L; in data type?在数据类型中?

In Java the default type for integer number literals is int , that means all numeric integer constants are treated as int .在 Java 中,整数字面量的默认类型是int ,这意味着所有数字整数常量都被视为int If you assign an int literal to a long typed variable, the type of the variable will not change.如果将int字面量分配给long类型变量,则变量的类型不会改变。

If you assign long a = 1L , you're telling the compiler that the literal 1 should be treated as a long .如果您分配long a = 1L ,则您是在告诉编译器文字1应该被视为long

long a = 3000000000;   // <-- won't work; 3,000,000,000 > Integer.MAX_VALUE

long a = 3000000000L;  // <-- will work; fits into a long

a is still a long , 1 is implicitly converted (only works in this direction, not when shrinking where an implicit cast is required). a仍然是long1被隐式转换(仅在这个方向上有效,而不是在需要隐式转换的收缩时)。

You can confirm that it can hold values larger than an integer could:您可以确认它可以保存大于整数的值:

    public static void main(String[] args) {
        long a = 1;
        a += Integer.MAX_VALUE;
        System.out.println(a); // outputs 2147483648 rather than -2147483648
    }

You can see from the following experiments that the literals (not prefixed with L ) are int s, but that there are automatic casts such that a long variable finaly always holds a long value:您可以从以下实验中看到,字面量(不以L为前缀)是int s,但是存在自动转换,使得long变量 finaly 始终保持long值:

long a = 2147483647 + 1;

long b = 2147483647;
b++;

long c = 2147483647L + 1;
  • For a , the literals are int s.对于a ,文字是int s。 The calclulation is done with int s, which overflows.计算是用int s 完成的,它会溢出。 Therefore long a gets assigned -2147483648L .因此long a被分配-2147483648L
  • For b , the int literal is casted to long during assignment, which can be incremented to the final value b = 2147483648L without overflow.对于bint字面量在赋值期间被强制转换为long ,可以递增到最终值b = 2147483648L而不会溢出。
  • For c , the calculation is already done with long s (the int literal 1 is automatically casted to 1L ), giving c = 2147483648L in first place.对于c ,计算已经使用long s 完成( int文字1自动转换为1L ),首先给出c = 2147483648L

You can find the specification for numeric promotion in JLS 5.6 "Numeric Contexts"您可以在JLS 5.6 "Numeric Contexts"中找到数字提升的规范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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