How to easily sort characters in a String?

Often companies like Google or Microsoft ask you simple questions like sorting an array during your interview. This is the easiest way I have found to sort the string:

  1. Convert the String to characters array using someString.toCharArray();
  2. Then use Arrays.sort() to sort the character array
  3. Finally create a new String with the sorted characters array

Here is the code and it’s output:

package com.icodejava.blog.datastructure;

import java.util.Arrays;

/**
 * @author Kushal Paudyal 
 * www.icodejava.com 
 * Created On - Feb 14, 2014 
 * Last Modified On - Feb 14, 2014
 */
public class StringSort {
	public static void main(String args[]) {
		System.out.println(sort("Please Sort Me"));
	}

	/**
	 * @param string - String to be sorted
	 * @return sorted string
	 */
	private static String sort(String string) {
		if (string == null) {
			return null;
		}

		char[] characters = string.toCharArray();
		Arrays.sort(characters);
		return new String(characters);

	}

}

Output:

MPSaeeelorst