JAVA-2

Q.2 Write a java program to create EMPLOYEE class with name, age and salary data members. Take input (data) from user and create minimum 5 objects of employee class. Display all employees data in ascending order of salary.
Solution :-
import java.util.*; class Employee implements Comparable{ String name; int age; double salary; // Constructor public Employee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } // Compare employees based on salary @Override public int compareTo(Employee other) { return Double.compare(this.salary, other.salary); } // Display employee details public void display() { System.out.println("Name: " + name + ", Age: " + age + ", Salary: " + salary); } } public class EmployeeSort { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Employee[] employees = new Employee[5]; // Taking input for 5 employees for (int i = 0; i < 5; i++) { System.out.println("Enter details for Employee " + (i + 1) + " (Name, Age, Salary):"); String name = scanner.next(); int age = scanner.nextInt(); double salary = scanner.nextDouble(); employees[i] = new Employee(name, age, salary); } scanner.close(); // Sorting employees by salary in ascending order Arrays.sort(employees); // Displaying sorted employees System.out.println("\nEmployees sorted by Salary in Ascending Order:"); for (Employee emp : employees) { emp.display(); } } }
OUTPUT :-
