Sort Byte Array in Java

Java 8Object Oriented ProgrammingProgramming

A byte array can be sorted using the java.util.Arrays.sort() method with a single argument required i.e. the array to be sorted. A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      byte[] arr = new byte[] { 4, 1, 9, 7, 5};
      System.out.print("The original byte array is: ");
      for (byte i: arr) {
         System.out.print(i + " ");
      }
      Arrays.sort(arr);
      System.out.print("\nThe sorted byte array is: ");
      for (byte i: arr) {
         System.out.print(i + " ");
      }
   }
}

Output

The original byte array is: 4 1 9 7 5
The sorted byte array is: 1 4 5 7 9

Now let us understand the above program. 

First the byte array arr[] is defined and then displayed using a for loop. A code snippet which demonstrates this is as follows −

byte[] arr = new byte[] { 4, 1, 9, 7, 5};
System.out.print("The original byte array is: ");
for (byte i: arr) {
   System.out.print(i + " ");
}

The Arrays.sort() method is used to sort the byte array. Then the resultant sorted array is displayed using for loop. A code snippet which demonstrates this is as follows −

Arrays.sort(arr);
System.out.print("\nThe sorted byte array is: ");
for (byte i: arr) {
   System.out.print(i + " ");
}
raja
Published on 09-Jan-2019 11:08:26
Advertisements