Java - Error on: long n = 8751475143;

折月煮酒 提交于 2019-12-02 11:36:05

Make it

long n = 8751475143L;

L will make it long literal

by default its int

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). The suffix L is preferred, because the letter l (ell) is often hard to distinguish from the digit 1 (one). [..]

The target of the assignment isn't taken into account when parsing the literal - so you need the L suffix:

long n = 8751475143L;

For the most part - and there are a few notable exceptions - the type of an expression is determined without much reference to its context. So as per section 3.10.1 of the JLS, an integer literal is of type int unless it has an l or L suffix, and the range of an integer literal of type int is of course limited to the range of int itslf.

All numbers in java are treated as integers, unless you say otherwise (or you use a decimal separator - then they are treated as a floats).

So, if you write

long i = 1234;

java will tread the number 1234 as integer, and do the type-cast to long for you.

However, if you type:

long n = 8751475143;

Java cannot treat 8751475143 as integer, because it's out of range. You need to specify, that what you meant was long, by adding 'L' at the end:

long n = 8751475143L;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!