 <p>Check below code and comment:</p> <pre><code>import java.util.Arrays; public class SortString { public static void main(String[] args) { String str = "11,22,13,31,21,12"; StringBuffer strB = new StringBuffer(); String[] arr = str.split(","); // Split string save in array Arrays.sort(arr); // sort array for (int i = 0; i &lt; arr.length; i++) { //add array in stringbuffer if (i != arr.length - 1) { strB.append(arr[i] + ","); } else { strB.append(arr[i]); } } String str2 = strB.toString(); System.out.println(str2); } } </code></pre>