Sorting Strings with Varargs in Java


Create a Java program to demonstrate a method with varargs that sorts a sequence of strings

  • The StringSorter class contains a static method named sortStrings that takes a variable number of strings (String... strings) as arguments.
  • Inside the method, it prints the given strings using Arrays.toString() to display the array contents.
  • It then sorts the strings array using Arrays.sort() method, which sorts the array in lexicographic (dictionary) order.
  • After sorting, it prints the sorted strings array.
  • In the main method, the sortStrings method is called with several strings as arguments.
  • The sorted strings are then printed to the console.

Source Code

import java.util.Arrays;
 
public class StringSorter
{
	static void sortStrings(String... strings)
	{
		System.out.println("Given Strings : " + Arrays.toString(strings));
		Arrays.sort(strings);
		System.out.println("Sorted Strings : " + Arrays.toString(strings));
	}
 
	public static void main(String[] args)
	{
		sortStrings("Pink", "Blue", "White", "Red", "Black", "Green", "Yellow", "Orange");
	}
}

Output

Given Strings : [Pink, Blue, White, Red, Black, Green, Yellow, Orange]
Sorted Strings : [Black, Blue, Green, Orange, Pink, Red, White, Yellow]

Example Programs