Java Program to Sort Names in an alphabetical order in An Array?

here we take an array input data and pass the data two for loop,after that we use compareTo() method to compare two input data.then we swap each data and store in temporary variable.

				
					public class SortNameArray {
	public static void main(String[] args) {
		String[] s = { "santosh", "pankaj", "aman" };
		String temp = null;
		for (int i = 0; i < s.length; i++) {
			for (int j = i + 1; j < s.length; j++) {
				if (s[i].compareTo(s[j]) > 0) {
					temp = s[i];
					s[i] = s[j];
					s[j] = temp;
				}
			}
		}
		System.out.println("Alphabetical order is:- ");
		for (String name : s) {
			System.out.println(name);
		}
	}
}
				
			

Output :-
Alphabetical order is:-
aman
pankaj
santosh

Leave a Comment

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