2012-01-19 48 views
16

爲什麼我得到一個int數太大,long分配給min和max?Java長號錯誤太大?

/* 
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); 
    } 
} 
+1

你可以用'Long.MIN_VALUE'和'Long.MAX_VALUE'或'1L << -1'和'-1L >>> 1' –

回答

54

Java中的所有文字數字是默認ints,其範圍-21474836482147483647包容性。

你的文字是在這個範圍之外,所以做出這個編譯你需要指出他們long文字(有L即後綴):

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

注意,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 

Java Language Specification相同

如果整數字面後綴爲ASCII字母L或l(ell);否則它是int類型的(§4.2.1)。

+0

要學究:你也可以使用一個小'升'。 – helpermethod

+8

@OliverWeiler我會說,迂腐,你可以**,但不應該**使用一個小__l__因爲它看起來像__1__。 – TC1

+0

如果使用錯誤的字體,它只會看起來像1,但確定,爲什麼會有混淆的風險。 – Bladt

17

您必須使用L來向編譯器說這是一個長文字。

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