find endianness of system in java

On JVMs that have the sun.misc.Unsafe class and store an Unsafe singleton in a static instance variable named "theUnsafe", then the following approach can be used. I tested this successfully on the Oracle JVM and openjdk. The code works by writing a short (2 bytes) value of 1 to memory, and then reading the first byte.

import java.lang.reflect.Field;
import sun.misc.Unsafe;

public class Endianness {
    private static Unsafe getUnsafe() {
        Unsafe unsafe = null;
        try {
            Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            unsafe = (Unsafe) f.get(null);
        } catch (Exception e) {}
        return unsafe;
    }

    public static void main(String[] args) {
        Unsafe unsafe = getUnsafe();
        long address = unsafe.allocateMemory(2);
        short number = 1;
        unsafe.putShort(address, number);
        if (unsafe.getByte(address) == 0)
            System.out.println("Big Endian");
        else
            System.out.println("Little Endian");
        unsafe.freeMemory(address);
    }
}

System.out.println(ByteOrder.nativeOrder());

How can i find such thing in *java?*I dont want to use inbuilt libs as this is a interview question.I want to find it out in java.

You can't do this in pure Java without calling a library. This is because;

  • Java says you shouldn't care about such things if you can avoid it.
  • Java is relatively feature poor as a language and relies on its libraries to do a lot of things which might be a language feature in another language.
  • Most people don't distinguish between what the language does and what is a built in library because the distinction is rarely useful.
  • Byte code/virtual machine is not big endian or little endian as such, only real implementations are. ;)

Older libraries only support big endian (which most processors use, Intel being a notable exception) Newer libraries can be set one way or the other.

It is pretty rare that you need to know how to re-write built in functionality again, and if you did, you would read the code on how it is done already (even if you did know how it could be done)

I have seen many people redevelop built in functionality which is buggy, more difficult to use because it behave in unexpected ways and less performant than the built in libraries. It is quite possible to write something faster or more bespoke than what is in the JDK, but its very rarely useful to know how off the top of your head.

I do get these questions from time to time, and before answering the question I point out all the reasons you wouldn't do this. ;)


I take no credit for this, however you can try:

import java.nio.ByteOrder;

if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN)) {
  System.out.println("Big-endian");
} else {
  System.out.println("Little-endian");
}