Java Program to Sort Strings in an Alphabetical Order

Java program to sort names in an alphabetical order. Sorting names in alphabetical order with a Java program. Enter the array’s size, then all of the names in the array. We can now quickly arrange names in alphabetical order using the compareTo 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 name you want to enter");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the name");
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]);
}
}

Enter number of name you want to enter 3
Enter all the name
apple
microsoft
inlarn
Names in sorted Orderapple,inlarn,microsoft

For Loop in Java Program

The “for” loop in Java is an entry-controlled loop that allows a user to iteratively run a block of statement(s) for a fixed number of times. The number of iterations is determined by the test condition specified within the “for” loop. The Java “for” loop is one of the simplest Java loops to grasp.

If Else Statement in Java

In Java, the if statement is used to execute a block of code if a given condition is true. If a condition evaluates to false, the if…else statement is used alongside an if statement to run code. Furthermore, the if…else…if statement is used to test numerous conditions.

The if statement in Java is the most basic decision-making statement. It is used to determine whether or not a specific statement or block of statements will be executed, that is if a given condition is true, then a block of statements is executed, otherwise not.

Temporary Variable in Java

A temporary array is one that exists only for the period of the data step in which it is defined. A temporary array can be used to store constant values that are utilised in calculations. There are no matching variables in a temporary array to identify the array elements. 

The method java can be used to create a temporary file. This method requires two parameters: the prefix, which defines the file name, and the suffix, which defines the file extension. It also returns the abstract path name of the created temporary file. Temporary variables are very important to execute this java program to sort names in an alphabetical order.