Starter Tutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Java » Programs » Strings » Java program for sorting a given list of names in ascending order
Suryateja Pericherla Categories: Strings. No Comments on Java program for sorting a given list of names in ascending order
Join Our Newsletter - Tips, Contests and Other Updates
Email
Name

In this article we will learn to implement a Java program for sorting a given list of names in ascending order. A Java program is provided for sorting a given list of names or strings in ascending order.

 

Program is as follows:

import java.util.*;
class Sorting
{
	void sortStrings()
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the value of n: ");
		int n = s.nextInt();
		String[] str = new String[n];
		System.out.println("Enter strings: ");
		for(int i = 0; i < n; i++)
		{
			str[i] = new String(s.next());
		}
		for(int i = 0; i < n; i++)
		{
			for(int j = i+1; j < n; j++)
			{
				if(str[i].compareTo(str[j])>0)
				{
					String temp = str[i];
					str[i] = str[j];
					str[j] = temp;
				}
			}
		}
		System.out.println("Sorted list of strings is:");
		for(int i = 0; i < n ; i++)
		{
			System.out.println(str[i]);
		}
	}
}
class Driver
{
	public static void main(String[] args)
	{
		Sorting obj = new Sorting();
		obj.sortStrings();
	}
}

 

Input and output for the above program are as follows:

Enter the value of n:
4
Enter strings:
suresh
mahesh
dinesh
ganesh
Sorted list of strings is:
dinesh
ganesh
mahesh
suresh

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

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

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory