Write a java program to sort the names in ascending order

Write a java program to sort the names in ascending order. This is a Java program for alphabetically sorting names. Enter the array’s size, then all of the names in the array. We can now quickly arrange names in alphabetical order using the compare to operator. The Java program to sort names in Alphabetical Order source code is available here.

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names");
for(int i = 0; i < n; i++)
{
names[i] = s1.nextLine();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("names in sorted order");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}

 

Output:

number of names you want to enter 4
Enter all the names
34
45
56
54
names in sorted order34,45,54,56

What is for loop and how does it works in java

A for loop is a repetition control structure that allows you to design a loop that must be repeated a certain number of times quickly. When you know how many times a task will be repeated, a for loop comes in handy.

A loop is used to repeatedly execute a set of statements until a certain condition is met. When showing numbers from 1 to 100, for example, you might wish to set the value of a variable to 1 and display it 100 times, raising its value by 1 with each loop iteration.

What is nextline() in java programming

nextLine() The java. util. nextLine() function is used to get the next line in a string. The Scanner class searches for a line separator delimiter starting at the current location. The String from the current place to the end of the line is returned by this method.