-1

Possible Duplicate:
Literal Syntax For byte[] arrays using Hex notation..?

I am trying to create a byte array of size '1' that holds the byte 0x0. In Java, can I just do something like this:

byte[] space = new byte[1];
space[0] = 0x0;

Will the hex value 0x0 be converted to its byte rep of 00000000 and store it in space[0]?

Community
  • 1
  • 1
darksky
  • 20,411
  • 61
  • 165
  • 254
  • 1
    Java (as any programming language) is about **values**, not **representations**. I'm certain that most of your preconceptions are mistaken. – Kerrek SB Dec 04 '11 at 02:28

2 Answers2

7

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:

  1. 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.)
  2. The int literal is narrowed using an implicit primitive narrowing conversion to a byte value.
  3. The byte value is used in the initialization of the array.

The implicit narrowing in step 2 is allowed because:

  1. This is in an assignment context.
  2. The value being assigned is a compile time constant expression of an integer type. (A literal is a compile time constant expression.)
  3. 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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

Yes this will do exactly what you think it should do. Also see this related question.

Community
  • 1
  • 1
Roman Byshko
  • 8,591
  • 7
  • 35
  • 57