views:

436

answers:

3

What endianness does Java use in its virtual machine? I remember reading somewhere that it depends on the physical machine it's running on, and then other places I have read that it is always, I believe, big endian. Which is correct?

+7  A: 

Multibyte data in the class files are stored big-endian.

From The Java Virtual Machine Specification, Second Edition, Chapter 4: The class File Format:

A class file consists of a stream of 8-bit bytes. All 16-bit, 32-bit, and 64-bit quantities are constructed by reading in two, four, and eight consecutive 8-bit bytes, respectively. Multibyte data items are always stored in big-endian order, where the high bytes come first.

Furthermore, the operand in an bytecode instruction is also big-endian if it spans multiple bytes.

From The Java Virtual Machine Specification, Second Edition, Secion 3.11: Instruction Set Summary:

If an operand is more than one byte in size, then it is stored in big-endian order-high-order byte first. For example, an unsigned 16-bit index into the local variables is stored as two unsigned bytes, byte1 and byte2, such that its value is

(byte1 << 8) | byte2

So yes, I think it can be said that the Java Virtual Machine uses big-endian.

coobird
+2  A: 

The actual working data stored in the running process will almost certainly match the endianess of the executing process. Generally file formats (including class files) will be in network order (big endian).

It's generally difficult to tell what the machine is doing underneath, as it is abstracted away by the virtual machine. You can't cast a short[] to byte[] as you can in C and C++. java.nio.ByteOrder.nativeOrder() should give you the underlying endianess. Matching endianess is useful when using non-byte NIO buffers.

Tom Hawtin - tackline
+2  A: 

Why ask? It's an implementation detail, thus it can't be answered in general.

mfx
Your answer is part of what I wanted to know... so thanks!
JoeCool
More to the point, it shouldn't matter. The only time you need to know is when you are exchanging binary data with another application. e.g. one written in C.
Peter Lawrey