为什么Java整数文字的默认类型是int而不是long? [英] Why is the default type of Java integer literals int instead of long?

查看:328
本文介绍了为什么Java整数文字的默认类型是int而不是long?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑为什么Java整数文字默认为 int 而不是 long 。这似乎会导致不必要的混淆。

I'm confused why Java integer literals default to int instead of long. This seems to cause unnecessary confusion.

首先,它要求程序员在为<$ c赋值时采用特殊语法(将L附加到文字) $ c> long 超过最大 int 大小(2147483647)。

First, it requires the programmer to adopt a special syntax (append "L" to literals) when assigning a value to a long that exceeds the maximum int size (2147483647).

long x = 2147483647; // Compiles
long y = 2147483648; // Does not compile
long z = 2147483648L; // Compiles

其次,使用 Long 包装器类,程序员必须始终使用<$ href =https://stackoverflow.com/questions/14425606/java-wrapper-中所述的 long 文字表示法。 classes-why-integer-literals-for-long-but-work-for-smaller>这个问题。

Second, when using the Long wrapper class, the programmer must always use the long literal notation as explained in this SO question.

Long x = 250; // Does not compile
Long y = 250L; // Compiles

第三,考虑从 int隐式转换较窄数据类型的文字(字节)在所有情况下都能正常工作(我知道,似乎简单地使所有整数文字类型 long 都是明显的解决方案......对吗?在特殊情况下,这不会完全消除对整数文字附加L的奇怪系统的需要吗?

Third, considering that implicit conversion from int literals to the "narrower" data types (short and byte) works just fine in all situations (that I know of), it seems that simply making all integer literals type long would have been the obvious solution... right? Wouldn't this completely remove the need for this odd system of appending "L" to integer literals in special cases?

推荐答案

这个行为是设计 1 ,并编入 JLS:Java语言规范

This behavior is by design1 and is codified in the JLS: Java Language Specification.

首先,请注意, 拓宽这就是(有效)整数的原因 - 文字被提升为长期价值。相反,这与 int literal

First, note that this is not related to widening which is why the (valid) integer-literal is promoted to a long value. Instead, this is related to the very specification of the int literal:


如果是十六进制,八进制或二进制int literal,则是编译时错误不适合32位。

It is a compile-time error if a hexadecimal, octal, or binary int literal does not fit in 32 bits.

最小和最大的有符号32位整数值分别为-2147483648和2147483647。

The smallest and largest signed 32-bit integer values are -2147483648 and 2147483647, respectively.

1 我不在推测为什么它以这种方式工作,和C#这样的语言有不同的规则。

1I care not speculate on why it works this way, and languages like C# have different rules.

这篇关于为什么Java整数文字的默认类型是int而不是long?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆