Understanding Java Data Types

1) Why the following assignment is 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 be -1.

2) Why is Integer MIN_VALUE unmarked?

 public static final int MIN_VALUE = 0x80000000; 

but does MIN_VALUE byte have a character?

 public static final byte MIN_VALUE = -128; 
+6
source share
2 answers

All integer literals are of type int (if not the suffix L or L ). Thus, in the first case, you save the int in byte . Narrowing such a transformation is not allowed without casting, except that if the right side is a constant, it allows, if the value is in the range, from -128 to 127 . 0b11111111 is 255 but is not in the range.

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

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

+4
source

Question 1)

This is because 0b11111111 is an int literal whose value is 255 . This value does not fit in bytes. See http://docs.oracle.com/javase/7/docs/technotes/guides/language/binary-literals.html for more details.

Question 2)

When we write binary or hexadecimal literals, we never put a sign. The literal 0x80000000 is actually a negative value, even if we do not write it as such.

There is no really good reason why the JDK creators decided to use the decimal literal for -128 , but the hexadecimal literal for 0x80000000 ; except that in each case it is probably much clearer than it is intended.

+6
source

All Articles