了解 Java 数据类型 [英] Understanding Java data types

查看:30
本文介绍了了解 Java 数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1) 为什么不允许以下赋值:

1) Why is the following assignment not allowed:

byte b = 0b11111111; // 8 bits or 1 byte

但允许此分配:

int i = 0b11111111111111111111111111111111; //32 bits or 4 bytes

两种类型都是有符号的,我希望 bi 是 -1.

Both types are signed, and I would expect b and i were -1.

2) 为什么整数 MIN_VALUE 没有符号?

2) Why doesn't the Integer MIN_VALUE have a sign?

public static final int   MIN_VALUE = 0x80000000;

但是字节 MIN_VALUE 确实有符号?

but the Byte MIN_VALUE does have a sign?

public static final byte   MIN_VALUE = -128;

推荐答案

所有整数字面量都具有 int 类型(除非后缀为 Ll).因此,在第一种情况下,您将 int 存储到 byte 中.没有强制转换,这样的缩小转换是不允许的,除非右边是一个常量,如果值在范围内是允许的,即 -128127.0b11111111 是 255,但不在范围内.

All integer literals have type int (unless suffixed by an L or l). Thus, in the first case, you're storing an int into a byte. A narrowing conversion like this is not allowed without a cast, except that if the right side is a constant, it's allowed if the value is in range, which is -128 to 127. 0b11111111 is 255, though, which is not in range.

至于为什么 int i = 0b1111111111111111111111111111111 是允许的:这几乎是因为 JLS 是这么说的".事实上,该特定示例出现在 JLS 3.10.1.有一个规则是 decimal int 类型的文字不能超过 214743647(特定情况除外 -2147483648),但没有关于二进制文字的规则除了它们必须适合 32 位.

As for why int i = 0b11111111111111111111111111111111 is allowed: it's pretty much "because the JLS says so". In fact, that specific example appears in JLS 3.10.1. There's a rule that decimal literals of type int cannot exceed 214743647 (except in the specific case -2147483648), but there's no rule about binary literals except that they have to fit into 32 bits.

正如我在评论中提到的,第二个问题实际上是关于编写代码的程序员的风格偏好的问题,无法回答.

As I mentioned in a comment, the second question is really a question about the style preference of the programmers who wrote the code, and it's impossible to answer.

这篇关于了解 Java 数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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