简体   繁体   中英

Understanding Java data types

1) Why is the following assignment not allowed:

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

but this assignment is allowed:

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

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

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

public static final int   MIN_VALUE = 0x80000000;

but the Byte MIN_VALUE does have a sign?

public static final byte   MIN_VALUE = -128;

Question 1)

This is because 0b11111111 is an int literal, whose value is 255 . This value doesn't fit into a byte. See http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html for more details on this.

Question 2)

When we write binary or hexadecimal literals, we never put a sign. The literal 0x80000000 is actually a negative value, even though we don't write it as such.

There's no really good reason why the makers of the JDK chose to use a decimal literal for -128 but a hexadecimal literal for 0x80000000 ; except that in each case, it's probably a whole lot clearer that way what is intended.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM