How to sort elements in Character Array in Java?
Declaration :
1 |
public static void sort(char[] a) |
Explanation :
Purpose | The java.util.Arrays.sort(char[]) method sorts the specified array of chars into ascending numerical order. |
Parameters | a ===> This is the array to be sorted. |
Return Value | This method does not return any value. |
Exception | NA |
Java Program : Example
Below example will explain java.util.Arrays.sort() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.c4learn; import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // Initialize unsorted char array char chArr[] = { 'c', 'a', 'b', 'd' }; // Print the Unsorted Array List System.out.println("The unsorted char array is:"); for (char val : chArr) { System.out.println("Value = " + val); } // Sort the array Arrays.sort(chArr); // Print the Sorted Array List System.out.println("The sorted char array is:"); for (char val : chArr) { System.out.println("Value = " + val); } } } |
Output of Program :
1 2 3 4 5 6 7 8 9 10 |
The unsorted char array is: Value = c Value = a Value = b Value = d The sorted char array is: Value = a Value = b Value = c Value = d |