Will the hex value 0x0 be converted to its byte rep of 00000000 and store it in space[0]?
In your executing program, there is only one representation of the Java byte
value zero - the 8 bit 2's complement representation of the integer zero - 8 zero bits.
It doesn't make any difference whether you express the number literal in your source code as 0
(decimal) or 00
(octal) or 0x0
. They all mean exactly the same thing.
So - Yes, your code does what you expect.
A simpler one line version would be:
byte[] space = new byte[] {0};
or
byte[] space = {0};
or even
byte[] space = new byte[1];
(The last one relies on the fact that Java byte arrays are default initialized to all zeros.)
Will the hex value 0x0
be converted to its byte rep of 00000000
and store it in space[0]
?
Sort of yes. Technically (i.e. according to the JLS) what happens is this:
0x0
becomes an int
literal. (The specific syntax used for the integer literal is actually immaterial at this point ... so long as it is valid.)
- The int literal is narrowed using an implicit primitive narrowing conversion to a
byte
value.
- The
byte
value is used in the initialization of the array.
The implicit narrowing in step 2 is allowed because:
- This is in an assignment context.
- The value being assigned is a compile time constant expression of an integer type. (A literal is a compile time constant expression.)
- The actual value being assigned is in the range of the type it is to be assigned to. (In this case, -128 to +127.)
In layman's terms, the compiler "knows" that there will never be any loss of information in the narrowing conversion.