Java Program to Sort List of Strings

Here is the Java program to sort list of strings. This program uses compareTo() method to compare the strings and finally uses bubble sort technique to sort them. compareTo() method compares two strings and return an integer value. The returned integer value is interpreted as show below.

Less than zero: first string is less than second

Greater than zero: first string is greater than second

Zero: two strings are equal

 

Java Program to Sort List of Strings

class StringsSortingExample
{
	public static void main(String...s)
	{
		int n,i,j;
		String str[]={"you","are","so","cute","person"};
		
		System.out.println("Before Sorting:");
		for(i=0;i<str.length;++i)
			System.out.println(str[i]);
	
		for(i=0;i<str.length;++i)
		{
			for(j=0;j<(str.length-i-1);++j)
			{
				if(str[j].compareTo(str[j+1])>0)
				{
					String temp;
					temp=str[j+1];
					str[j+1]=str[j];
					str[j]=temp;
				}
			}
		}

		System.out.println("\nAfter Sorting:");
		for(i=0;i<str.length;++i)
			System.out.println(str[i]);
	}		
}

 

Output

Java Program to Sort List of Strings

Leave a Comment

Your email address will not be published. Required fields are marked *