Changing the byte order in a ByteBuffer

The default byte order in a ByteBuffer is ByteOrder.BIG_ENDIAN. The most significant byte is written out first (little endian is the opposite). Change the order as follows.

Main.java:

import java.nio.*;
 
public class Main
{
   public static void main(String []args) {
      ByteBuffer bb = ByteBuffer.allocate(25);
 
      for (int i=1; i<=5; i++) {
         bb.putShort((short) i);
      }
      
      // the initial order of a byte buffer is always BIG_ENDIAN
      System.out.println("Before changing byteorder: ");
      printByteArray(bb.array());
 
      // from now on, everything is stored as LITTLE_ENDIAN
      bb.order(ByteOrder.LITTLE_ENDIAN);
 
      for (int i=1; i<=5; i++) {
         bb.putShort((short) i);
      }
 
      System.out.println("After changing byteorder: ");
      printByteArray(bb.array());
   }
 
   public static void printByteArray(byte[] array) {
      for (int i=0; i<array.length; i++) {
         System.out.print(array[i] + " ");
      }
      System.out.println();
   }
}

outputs:

Before changing byteorder:
0 1 0 2 0 3 0 4 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
After changing byteorder:
0 1 0 2 0 3 0 4 0 5 1 0 2 0 3 0 4 0 5 0 0 0 0 0 0