Java长号太大错误?

Aar*_*ron 22 java

为什么我得到一个int数太大而long分配给min和max?

/*
long: The long data type is a 64-bit signed two's complement integer.
It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of         9,223,372,036,854,775,807 (inclusive).
Use this data type when you need a range of values wider than those provided by int.
*/
package Literals;

public class Literal_Long {
     public static void main(String[] args) {
        long a = 1;
        long b = 2;
        long min = -9223372036854775808;
        long max = 9223372036854775807;//Inclusive

        System.out.println(a);
        System.out.println(b);
        System.out.println(a + b);
        System.out.println(min);
        System.out.println(max);
    }
}
Run Code Online (Sandbox Code Playgroud)

Boh*_*ian 70

Java中的所有文字数字是在默认情况下ints,其范围-21474836482147483647包容.

你的文字超出了这个范围,所以要进行这个编译,你需要表明它们是long文字(即后缀L):

long min = -9223372036854775808L;
long max = 9223372036854775807L;
Run Code Online (Sandbox Code Playgroud)

请注意,java支持大写L和小写l,但我建议不要使用小写,l因为它看起来像1:

long min = -9223372036854775808l; // confusing: looks like the last digit is a 1
long max = 9223372036854775807l; // confusing: looks like the last digit is a 1
Run Code Online (Sandbox Code Playgroud)

Java语言规范相同

如果整数文字后缀为ASCII字母L或l(ell),则整数文字的长度为long; 否则它的类型为int(§4.2.1).

  • @OliverWeiler我会说,为了迂腐,你可以**但不应该**使用一个小的__l__因为它看起来像__1__. (8认同)

Pet*_*hev 24

您必须使用L对编译器说它是一个长文字.

long min = -9223372036854775808L;
long max = 9223372036854775807L;//Inclusive
Run Code Online (Sandbox Code Playgroud)