Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

Java long number too large error?

Why do I get an int number is too large where the long is assigned to min and 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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All literal numbers in java are by default ints, which has range -2147483648 to 2147483647 inclusive.

Your literals are outside this range, so to make this compile you need to indicate they're long literals (ie suffix with L):

long min = -9223372036854775808L;
long max = 9223372036854775807L;

Note that java supports both uppercase L and lowercase l, but I recommend not using lowercase l because it looks like a 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

Java Language Specification for the same

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...