Q.Write a java program to accept n employee names from user. Sort them in ascending order and Display them.(Use array of object and Static keyword)[25 M]
import java.util.Scanner;
class Employee {
String name;
// Constructor
Employee(String name) {
this.name = name;
}
// Static method to sort employees
static void sortEmployees(Employee[] emp) {
int n = emp.length;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// Compare names and swap
if (emp[i].name.compareToIgnoreCase(emp[j].name) > 0) {
Employee temp = emp[i];
emp[i] = emp[j];
emp[j] = temp;
}
}
}
}
// Static method to display employees
static void displayEmployees(Employee[] emp) {
System.out.println("\nEmployee Names in Ascending Order:");
for (Employee e : emp) {
System.out.println(e.name);
}
}
}
public class EmployeeSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of employees: ");
int n = sc.nextInt();
sc.nextLine(); // consume newline
// Array of objects
Employee[] emp = new Employee[n];
// Accept names
for (int i = 0; i < n; i++) {
System.out.print("Enter employee name " + (i + 1) + ": ");
String name = sc.nextLine();
emp[i] = new Employee(name);
}
// Sort using static method
Employee.sortEmployees(emp);
// Display using static method
Employee.displayEmployees(emp);
sc.close();
}
}