Java Program to Sort Characters of a String


Sorting a String's characters is one of the most asked Interview Questions in Java. Today let's see how this can be solved in a really easy manner. 

We will be utilizing an inbuilt java function in Java.Utils library -> Arrays.sort()

We need to import Java.utils in order to use it. 

import java.util.*;

A string is nothing but an array of characters. The function that we are going to use also needs an char array as an input. So, we'll be converting the String into a character array. 

//Load the string into a character array.
char[] temp = a.toCharArray();

Now we'll use the Arrays.sort function to do the heavy work of sorting for us. 

//Sort the Array

 Let's combine all this information together for a working code. 

You can copy paste this code into a new .java file and see it working for yourself!

package coding;

import java.util.*;

public class Practice {

	public static void main(String[] args) {
		//Create an object of the class
		Practice practice = new Practice();
		//call the sort function

	 * Function to sort the characters of a String
	 * @author
	 * @param a
	public void sortString(String a) {
		System.out.println("Received String:"+a);
		//Load the string into a character array.
		char[] temp = a.toCharArray();
		//Sort the Array
		System.out.println("Sorted String:"+String.valueOf(temp));


And here is the output of this code : 

Received String: ilikecomputengine

Sorted String: ceeegiiiklmnnoptu

Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on FacebookTwitterTumblr.


Popular posts from this blog

Calculate Your CTC Hike Percentage

Java Program to Find a List of Prime Numbers (Step by Step)

Java Program to check Palindrome

What is my IP Address - How to find your IP address on Local Network using Command Prompt, and External Network using JavaScript Code

Reduce Server Load from Dynamic Page Search - Create a Dynamic JavaScript based Table filter