WAP to Sort Array Of String According To String Length: The program InterviewPrograms52 aims to sort an array of strings based on the lengths of the strings in ascending order.
In this program, we have used the concepts of For Loop and If Statement. For better understanding, you can follow the tutorials which we have already shared by clicking on the below link:
Sort Array Of String According To Strig Length
package com.softwaretestingo.interviewprograms; import java.util.Arrays; public class InterviewPrograms52 { /* * Input { "Hi" , "maven" , "selenium " , "java" } * Output{ "Hi", "java", "maven" , "selenium" } */ public static void main(String[] args) { String ip[]={"Hi","maven","selenium","java"}; for(int i=0;i<ip.length;i++) { for(int j=i+1;j<ip.length;j++) { if(ip[i].length()>ip[j].length()) { String temp=ip[j]; ip[j]=ip[i]; ip[i]=temp; } } } System.out.println(Arrays.toString(ip)); } }
Output
[Hi, java, maven, selenium]
Here’s how the program works:
- The input array ip contains four strings: “Hi”, “maven”, “selenium”, and “java”.
- The program uses nested loops to compare each string’s length with all other strings in the array.
- Starting from the first string (“Hi”), it compares its length with the lengths of the other strings (“maven”, “selenium”, and “java”).
- If the length of the current string (“Hi”) is greater than the length of any other string, it swaps their positions in the array.
- The program continues this process until the array is fully sorted based on the lengths of the strings in ascending order.
- After sorting, the program prints the sorted array to the console using Arrays.toString(ip).
In this specific case, the program will output:
[Hi, java, maven, selenium]
The output represents the array of strings sorted based on their lengths in ascending order. The string “Hi” has the shortest length, followed by “java”, “maven”, and “selenium,” which has the longest length.
Leave a Reply