Java program to sort words of sentence in ascending order

JavaObject Oriented ProgrammingProgramming

To sort words of sentence in ascending order, the Java code is as follows −


 Live Demo

import java.util.*;
public class Demo{
   static void sort_elements(String []my_str, int n){
      for (int i=1 ;i<n; i++){
         String temp = my_str[i];
         int j = i - 1;
         while (j >= 0 && temp.length() < my_str[j].length()){
            my_str[j+1] = my_str[j];
         my_str[j+1] = temp;
   public static void main(String args[]){
      String []my_arr = {"This", "is", "a", "sample"};
      int len = my_arr.length;
      System.out.print("The sorted array is : ");
      for (int i=0; i<len; i++)
      System.out.print(my_arr[i]+" ");


The sorted array is : a is This sample

A class named Demo contains a function named ‘sort_elements’. This function iterates through a String and checks the length of every word in the string and arranges them based on their length. In the main function, aString array is defined and its length is assigned to a variable. The ‘sort_elements’ function is called on this string and the sorted array is displayed on the console.

Published on 07-Jul-2020 12:51:35