What is '0x0102030405060708L' in Bits.java

So I saw this bit of static block in Bits.java in the java.nio package.

 static {
    long a = unsafe.allocateMemory(8);
    try {
        unsafe.putLong(a, 0x0102030405060708L);
        byte b = unsafe.getByte(a);
        switch (b) {
        case 0x01: byteOrder = ByteOrder.BIG_ENDIAN;     break;
        case 0x08: byteOrder = ByteOrder.LITTLE_ENDIAN;  break;
            assert false;
            byteOrder = null;
    } finally {

What is the significance of 0x0102030405060708L?
What is this hardcoded value?

3 answers

  • answered 2018-07-11 05:51 Yunnosch

    The code counts the 8 bytes, writes the index of each byte into it.
    It does so by writing the mentioned hardcoded value into a datastructure of 8 byte size. The hardcoded value contains an increasing byte value across the consecutive bytes in the structure. Then it reads the value of the first byte and by its value determines the endianess of the environment.

    (Endianess: https://en.wikipedia.org/wiki/Endianness )

    Note that the special chosen value can detect the (extremely weird) endianess which uses neither the lowest addressed byte nor the highest-addressed byte as as LSB. The assertion could detect any of the intermediate bytes or even a byte with e.g. value 0 and would raise an alarm in that case. That would also be possible with e.g. "0x4400000000000055", but with the shown value, a debugging session can easily identify any of the intermediate bytes and even almost surely any non-initialised byte, i.e. any byte not covered by the hardcoded value. That would of course be an extremely weird environment, but that is what assertions are for.

  • answered 2018-07-11 05:53 Stephen C

    There is no particular significance to the value. The code is writing a 64bit integer, and seeing which order the bytes appear in memory. (That is what "big endian" and "little endian" is all about; see Endianness.

    Just about any value could be used ... provided that the top 8 bits and bottom 8 bits are distinguishable.

  • answered 2018-07-11 06:01 Robert Rouhani

    You could put any pattern in there so long as the last byte and the first byte are different values. 0x0100000000000002L would work just as well, and you would be checking for 0x01 and 0x02 in the switch statement instead of 0x01 and 0x08. The purpose of the code is to determine the order in which bytes are stored in memory (endianness).

    Because there's no cost associated with using a different value, I think the constant they chose is a very good one because it indicates that there is an intended order to the bytes, as opposed to a set of flags or something where each bit is significant.