0% found this document useful (0 votes)
0 views

JAVA Assignment

The document outlines three Java assignments focusing on Object-Oriented Programming (OOP) concepts, string operations, and file operations. Each assignment includes specific tasks to be implemented in Java, demonstrating various programming principles such as encapsulation, inheritance, polymorphism, and file handling. The provided code snippets illustrate how to achieve the required functionalities for each assignment, ensuring a comprehensive understanding of Java programming.

Uploaded by

52Viraj Gavas
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

JAVA Assignment

The document outlines three Java assignments focusing on Object-Oriented Programming (OOP) concepts, string operations, and file operations. Each assignment includes specific tasks to be implemented in Java, demonstrating various programming principles such as encapsulation, inheritance, polymorphism, and file handling. The provided code snippets illustrate how to achieve the required functionalities for each assignment, ensuring a comprehensive understanding of Java programming.

Uploaded by

52Viraj Gavas
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

JAVA ASSIGNMENTS

1) Write a program to cover all Java OOPS concepts. Topics need to cover:

a) Class and Object


b) Class constructor
c) Polymorphism
d) Method overloading
e) Method overriding
f) Inheritance
g) Interface
h) Abstract class
i) Abstraction and Encapsulation
j) Composition and Aggregation
k) Generalization and Specialization

Code:

// a) Class and Object


class Vehicle {
String model;
int year;

// b) Class constructor
public Vehicle(String model, int year) {
this.model = model;
this.year = year;
}

// Method to demonstrate Encapsulation (i)


public void setModel(String model) {
this.model = model;
}

public String getModel() {


return model;
}

public void setYear(int year) {


this.year = year;
}

public int getYear() {


return year;
}

// Method to be overridden (e)


public void start() {
System.out.println("Vehicle is starting");
}
}

// f) Inheritance
class Car extends Vehicle {
String brand;

// b) Class constructor
public Car(String model, int year, String brand) {
super(model, year);
this.brand = brand;
}

// e) Method overriding
@Override
public void start() {
System.out.println("Car is starting");
}

// d) Method overloading
public void start(String sound) {
System.out.println(sound);
}
}

// g) Interface
interface Electric {
void charge();
}

// h) Abstract class
abstract class HeavyVehicle {
abstract void loadCargo();
}
// c) Polymorphism
class Truck extends Vehicle implements Electric {
public Truck(String model, int year) {
super(model, year);
}

// e) Method overriding
@Override
public void start() {
System.out.println("Truck is starting");
}

// g) Interface implementation
@Override
public void charge() {
System.out.println("Truck is charging");
}
}

// h) Abstract class implementation


class Crane extends HeavyVehicle {
@Override
void loadCargo() {
System.out.println("Crane is loading cargo");
}
}

// j) Composition and Aggregation


class Garage {
private Vehicle[] vehicles; // Aggregation
private Crane crane; // Composition

public Garage(Vehicle[] vehicles, Crane crane) {


this.vehicles = vehicles;
this.crane = crane;
}

public void showVehicles() {


for (Vehicle vehicle : vehicles) {
System.out.println(vehicle.getModel() + " from year " +
vehicle.getYear());
vehicle.start();
}
crane.loadCargo();
}
}

// k) Generalization and Specialization


// Generalization: Moving common properties to a superclass
class Appliance {
String type;
String brand;

public Appliance(String type, String brand) {


this.type = type;
this.brand = brand;
}

public void turnOn() {


System.out.println("Appliance is turning on");
}
}

// Specialization: Creating more specific subclasses


class WashingMachine extends Appliance {
public WashingMachine(String brand) {
super("Washing Machine", brand);
}

@Override
public void turnOn() {
System.out.println("Washing Machine is turning on");
}
}

public class Main {


public static void main(String[] args) {
// a) Class and Object
Car car = new Car("Model S", 2022, "Tesla");
Truck truck = new Truck("F-150", 2021);
Crane crane = new Crane();

// c) Polymorphism
Vehicle myVehicle = truck;
myVehicle.start();

// f) Inheritance
car.start();
car.start("Vroom");
// g) Interface
Electric myTruck = truck;
myTruck.charge();

// j) Composition and Aggregation


Vehicle[] vehicles = { car, truck };
Garage garage = new Garage(vehicles, crane);
garage.showVehicles();

// k) Generalization and Specialization


WashingMachine washingMachine = new WashingMachine("LG");
washingMachine.turnOn();
}
}

Output:
2) Design a Java program that performs various string operations and uses control
statements for user input validation. The program should allow the user to perform
the following operations:

a) Concatenate Strings: The user can enter two strings and the program
should concatenate them.
b) Find Length of a String: The user can enter a string, and the program
should display its length.
c) Convert to Uppercase and Lowercase: The user can enter a string, and the
program should display it in both uppercase and lowercase.
d) Extract Substring: The user can enter a string and specify the starting and
ending index, and the program should extract and display the substring.
e) Split a Sentence: The user can enter a sentence, and the program should
split it into words and display them.
f) Reverse a String: The user can enter a string, and the program should
reverse and display it.
g) Requirements:
i) Use control statements (if-else, switch, loops) for input validation
and handling possible errors.
ii) Implement a user-friendly console interface for the user to interact
with the program.
iii) Cover all string concepts, such as concatenation, length, uppercase
and lowercase conversion, substring extraction, splitting, and
reversal.

Code:

import java.util.Scanner;

public class StringOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("Select an operation:");
System.out.println("a) Concatenate Strings");
System.out.println("b) Find Length of a String");
System.out.println("c) Convert to Uppercase and Lowercase");
System.out.println("d) Extract Substring");
System.out.println("e) Split a Sentence");
System.out.println("f) Reverse a String");
System.out.println("g) Exit");

System.out.print("Enter your choice (a-g): ");


String choice = scanner.nextLine().trim().toLowerCase();

switch (choice) {
case "a":
concatenateStrings(scanner);
break;
case "b":
findStringLength(scanner);
break;
case "c":
convertCase(scanner);
break;
case "d":
extractSubstring(scanner);
break;
case "e":
splitSentence(scanner);
break;
case "f":
reverseString(scanner);
break;
case "g":
System.out.println("Exiting program...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please enter a
valid option (a-g).");
}

System.out.println(); // Add a blank line for readability


}
}

// Operation: Concatenate Strings


private static void concatenateStrings(Scanner scanner) {
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

String concatenatedString = str1 + str2;


System.out.println("Concatenated string: " + concatenatedString);
}
// Operation: Find Length of a String
private static void findStringLength(Scanner scanner) {
System.out.print("Enter a string: ");
String str = scanner.nextLine();

int length = str.length();


System.out.println("Length of the string: " + length);
}

// Operation: Convert to Uppercase and Lowercase


private static void convertCase(Scanner scanner) {
System.out.print("Enter a string: ");
String str = scanner.nextLine();

String uppercase = str.toUpperCase();


String lowercase = str.toLowerCase();

System.out.println("Uppercase: " + uppercase);


System.out.println("Lowercase: " + lowercase);
}

// Operation: Extract Substring


private static void extractSubstring(Scanner scanner) {
System.out.print("Enter a string: ");
String str = scanner.nextLine();

System.out.print("Enter the starting index (0-based): ");


int start = getValidIndex(scanner, str.length());

System.out.print("Enter the ending index (0-based): ");


int end = getValidIndex(scanner, str.length());

String substring = str.substring(start, end + 1);


System.out.println("Extracted substring: " + substring);
}

// Helper method to validate index input


private static int getValidIndex(Scanner scanner, int maxLength) {
while (true) {
try {
int index = Integer.parseInt(scanner.nextLine());
if (index < 0 || index >= maxLength) {
throw new IndexOutOfBoundsException();
}
return index;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid
integer.");
} catch (IndexOutOfBoundsException e) {
System.out.println("Index out of bounds. Please enter a
valid index.");
}
}
}

// Operation: Split a Sentence


private static void splitSentence(Scanner scanner) {
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();

String[] words = sentence.split("\\s+");


System.out.println("Words in the sentence:");
for (String word : words) {
System.out.println(word);
}
}

// Operation: Reverse a String


private static void reverseString(Scanner scanner) {
System.out.print("Enter a string: ");
String str = scanner.nextLine();

StringBuilder reversed = new StringBuilder(str).reverse();


System.out.println("Reversed string: " + reversed);
}
}
Output:
3) Design a Java program to cover all File related topics, demonstrating various File
operations in Java. The program should allow users to perform the following tasks:

a) Create a new directory.


b) Create a new text file and write content to it.
c) Read the content from an existing text file.
d) Append new content to an existing text file.
e) Copy the content from one text file to another.
f) Delete a text file.
g) List all files and directories in a given directory.
h) Search for a specific file in a directory and its subdirectories.
i) Rename a file.
j) Get information about a file (e.g., file size, last modified time).
k) Requirements:
i) Use File Input and Output streams for reading and writing text files.
ii) Implement exception handling to handle possible errors during file
operations.
iii) Provide a user-friendly console interface for the user to interact with
the program.

Code:

import java.io.*;
import java.nio.file.*;
import java.util.Scanner;

public class FileOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("Select a file operation:");
System.out.println("a) Create a new directory");
System.out.println("b) Create a new text file and write con-
tent to it");
System.out.println("c) Read the content from an existing text
file");
System.out.println("d) Append new content to an existing text
file");
System.out.println("e) Copy the content from one text file to
another");
System.out.println("f) Delete a text file");
System.out.println("g) List all files and directories in a
given directory");
System.out.println("h) Search for a specific file in a dir-
ectory and its subdirectories");
System.out.println("i) Rename a file");
System.out.println("j) Get information about a file");
System.out.println("k) Exit");

System.out.print("Enter your choice (a-k): ");


String choice = scanner.nextLine().trim().toLowerCase();

switch (choice) {
case "a":
createDirectory(scanner);
break;
case "b":
createFileAndWrite(scanner);
break;
case "c":
readFile(scanner);
break;
case "d":
appendToFile(scanner);
break;
case "e":
copyFile(scanner);
break;
case "f":
deleteFile(scanner);
break;
case "g":
listFilesAndDirectories(scanner);
break;
case "h":
searchFile(scanner);
break;
case "i":
renameFile(scanner);
break;
case "j":
getFileInformation(scanner);
break;
case "k":
System.out.println("Exiting program...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please enter a
valid option (a-k).");
}

System.out.println(); // Add a blank line for readability


}
}

// a) Create a new directory


private static void createDirectory(Scanner scanner) {
System.out.print("Enter the directory path to create: ");
String dirPath = scanner.nextLine();

File dir = new File(dirPath);


if (dir.mkdir()) {
System.out.println("Directory created successfully.");
} else {
System.out.println("Failed to create directory.");
}
}

// b) Create a new text file and write content to it


private static void createFileAndWrite(Scanner scanner) {
System.out.print("Enter the file path to create: ");
String filePath = scanner.nextLine();

System.out.print("Enter the content to write: ");


String content = scanner.nextLine();

try (BufferedWriter writer = new BufferedWriter(new File-


Writer(filePath))) {
writer.write(content);
System.out.println("File created and content written success-
fully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the
file: " + e.getMessage());
}
}

// c) Read the content from an existing text file


private static void readFile(Scanner scanner) {
System.out.print("Enter the file path to read: ");
String filePath = scanner.nextLine();
try (BufferedReader reader = new BufferedReader(new
FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file:
" + e.getMessage());
}
}

// d) Append new content to an existing text file


private static void appendToFile(Scanner scanner) {
System.out.print("Enter the file path to append to: ");
String filePath = scanner.nextLine();

System.out.print("Enter the content to append: ");


String content = scanner.nextLine();

try (BufferedWriter writer = new BufferedWriter(new File-


Writer(filePath, true))) {
writer.write(content);
System.out.println("Content appended successfully.");
} catch (IOException e) {
System.out.println("An error occurred while appending to the
file: " + e.getMessage());
}
}

// e) Copy the content from one text file to another


private static void copyFile(Scanner scanner) {
System.out.print("Enter the source file path: ");
String sourcePath = scanner.nextLine();

System.out.print("Enter the destination file path: ");


String destPath = scanner.nextLine();

try {
Files.copy(Paths.get(sourcePath), Paths.get(destPath), Stand-
ardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("An error occurred while copying the file:
" + e.getMessage());
}
}

// f) Delete a text file


private static void deleteFile(Scanner scanner) {
System.out.print("Enter the file path to delete: ");
String filePath = scanner.nextLine();

File file = new File(filePath);


if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete file.");
}
}

// g) List all files and directories in a given directory


private static void listFilesAndDirectories(Scanner scanner) {
System.out.print("Enter the directory path to list: ");
String dirPath = scanner.nextLine();

File dir = new File(dirPath);


if (dir.isDirectory()) {
String[] files = dir.list();
if (files != null) {
for (String file : files) {
System.out.println(file);
}
} else {
System.out.println("The directory is empty or an error
occurred.");
}
} else {
System.out.println("The specified path is not a directory.");
}
}

// h) Search for a specific file in a directory and its subdirector-


ies
private static void searchFile(Scanner scanner) {
System.out.print("Enter the directory path to search in: ");
String dirPath = scanner.nextLine();

System.out.print("Enter the file name to search for: ");


String fileName = scanner.nextLine();
searchFileInDirectory(new File(dirPath), fileName);
}

private static void searchFileInDirectory(File dir, String fileName)


{
if (dir.isDirectory()) {
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
searchFileInDirectory(file, fileName);
} else if (file.getName().equalsIgnoreCase(fileName))
{
System.out.println("File found: " + file.getAbso-
lutePath());
}
}
}
}
}

// i) Rename a file
private static void renameFile(Scanner scanner) {
System.out.print("Enter the current file path: ");
String currentPath = scanner.nextLine();

System.out.print("Enter the new file path: ");


String newPath = scanner.nextLine();

File oldFile = new File(currentPath);


File newFile = new File(newPath);

if (oldFile.renameTo(newFile)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename file.");
}
}

// j) Get information about a file


private static void getFileInformation(Scanner scanner) {
System.out.print("Enter the file path to get information about:
");
String filePath = scanner.nextLine();
File file = new File(filePath);
if (file.exists()) {
System.out.println("File name: " + file.getName());
System.out.println("File path: " + file.getAbsolutePath());
System.out.println("File size: " + file.length() + " bytes");
System.out.println("Last modified: " + new java.util.D-
ate(file.lastModified()));
} else {
System.out.println("The file does not exist.");
}
}
}

Output:
4) Design a Java program that covers all thread-related topics, demonstrating various
multithreading concepts in Java. The program should allow users to perform the
following tasks:

a) Create and start multiple threads.


b) Synchronize threads to avoid race conditions and ensure data consistency.
c) Use wait() and notify() to implement thread communication.
d) Use sleep() to pause threads for a specified duration.
e) Demonstrate thread interruption and thread termination.
f) Use thread pools to manage a group of threads efficiently.
g) Implement thread synchronization using locks and conditions.
h) Demonstrate deadlock and ways to avoid it.
i) Use thread-local variables to handle thread-specific data.
j) Implement producer-consumer problem using thread synchronization.
k) Use Executors and Callable to perform parallel computation and get
results.
l) Requirements:
i) Implement exception handling to handle possible errors during
multithreaded operations.
ii) Provide a user-friendly console interface for the user to interact with
the program.
5) Design a Java program to implement a Collection Management System that manages
different types of collections such as lists, sets, and maps. The program should allow
users to perform the following operations for each type of collection:

a) Lists:
i) Add an element: The user can add an element to the list.
ii) Remove an element: The user can remove an element from the list.
iii) Display all elements: The user can view all elements in the list.
b) Sets:
i) Add an element: The user can add an element to the set.
ii) Remove an element: The user can remove an element from the set.
iii) Display all elements: The user can view all elements in the set.
c) Maps:
i) Add a key-value pair: The user can add a key-value pair to the map.
ii) Remove a key-value pair: The user can remove a key-value pair from
the map.
iii) Display all key-value pairs: The user can view all key-value pairs in
the map.
d) Requirements:
i) Implement separate classes for each type of collection
(ListManager, SetManager, MapManager).
ii) Use appropriate collection classes (e.g., ArrayList, LinkedList,
HashSet, TreeMap) to store the elements and key-value pairs.
iii) Use inheritance and polymorphism to manage different types of
collections.
iv) Implement exception handling to handle possible errors (e.g.,
element not found in the list/set, duplicate keys in the map).
v) Provide a user-friendly console interface for the user to interact with
the Collection Management System.
e)Cover all Java collections topics, including Lists, Sets, and Maps

CollectionManagementSystem.java:

import java.util.*;

public class CollectionManagementSystem {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ListManager listManager = new ListManager();
SetManager setManager = new SetManager();
MapManager mapManager = new MapManager();
while (true) {
System.out.println("\nCollection Management Sys-
tem");
System.out.println("1) Manage Lists");
System.out.println("2) Manage Sets");
System.out.println("3) Manage Maps");
System.out.println("4) Exit");

System.out.print("Enter your choice (1-4): ");


int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline character

switch (choice) {
case 1:
manageList(scanner, listManager);
break;
case 2:
manageSet(scanner, setManager);
break;
case 3:
manageMap(scanner, mapManager);
break;
case 4:
System.out.println("Exiting program...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please
enter a valid option (1-4).");
}
}
}

private static void manageList(Scanner scanner, ListManager


listManager) {
while (true) {
System.out.println("\nList Management");
System.out.println("1) Add an element");
System.out.println("2) Remove an element");
System.out.println("3) Display all elements");
System.out.println("4) Go back");

System.out.print("Enter your choice (1-4): ");


int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline character

switch (choice) {
case 1:
System.out.print("Enter element to add: ");
String elementToAdd = scanner.nextLine();
listManager.addElement(elementToAdd);
break;
case 2:
System.out.print("Enter element to remove:
");
String elementToRemove = scanner.nextLine();
listManager.removeElement(elementToRemove);
break;
case 3:
listManager.displayElements();
break;
case 4:
return;
default:
System.out.println("Invalid choice. Please
enter a valid option (1-4).");
}
}
}

private static void manageSet(Scanner scanner, SetManager


setManager) {
while (true) {
System.out.println("\nSet Management");
System.out.println("1) Add an element");
System.out.println("2) Remove an element");
System.out.println("3) Display all elements");
System.out.println("4) Go back");

System.out.print("Enter your choice (1-4): ");


int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline character

switch (choice) {
case 1:
System.out.print("Enter element to add: ");
String elementToAdd = scanner.nextLine();
setManager.addElement(elementToAdd);
break;
case 2:
System.out.print("Enter element to remove:
");
String elementToRemove = scanner.nextLine();
setManager.removeElement(elementToRemove);
break;
case 3:
setManager.displayElements();
break;
case 4:
return;
default:
System.out.println("Invalid choice. Please
enter a valid option (1-4).");
}
}
}

private static void manageMap(Scanner scanner, MapManager


mapManager) {
while (true) {
System.out.println("\nMap Management");
System.out.println("1) Add a key-value pair");
System.out.println("2) Remove a key-value pair");
System.out.println("3) Display all key-value
pairs");
System.out.println("4) Go back");

System.out.print("Enter your choice (1-4): ");


int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline character

switch (choice) {
case 1:
System.out.print("Enter key: ");
String key = scanner.nextLine();
System.out.print("Enter value: ");
String value = scanner.nextLine();
mapManager.addEntry(key, value);
break;
case 2:
System.out.print("Enter key to remove: ");
String keyToRemove = scanner.nextLine();
mapManager.removeEntry(keyToRemove);
break;
case 3:
mapManager.displayEntries();
break;
case 4:
return;
default:
System.out.println("Invalid choice. Please
enter a valid option (1-4).");
}
}
}
}

ListManager.java

package Task5;

import java.util.ArrayList;
import java.util.List;

public class ListManager {


private List<String> list;

public ListManager() {
list = new ArrayList<>();
}
public void addElement(String element) {
list.add(element);
System.out.println("Element added to the list.");
}

public void removeElement(String element) {


if (list.remove(element)) {
System.out.println("Element removed from the
list.");
} else {
System.out.println("Element not found in the
list.");
}
}

public void displayElements() {


if (list.isEmpty()) {
System.out.println("The list is empty.");
} else {
System.out.println("Elements in the list: " + list);
}
}
}

SetManager.java

package Task5;

import java.util.HashSet;
import java.util.Set;

public class SetManager {


private Set<String> set;

public SetManager() {
set = new HashSet<>();
}

public void addElement(String element) {


if (set.add(element)) {
System.out.println("Element added to the set.");
} else {
System.out.println("Element already exists in the
set.");
}
}

public void removeElement(String element) {


if (set.remove(element)) {
System.out.println("Element removed from the set.");
} else {
System.out.println("Element not found in the set.");
}
}

public void displayElements() {


if (set.isEmpty()) {
System.out.println("The set is empty.");
} else {
System.out.println("Elements in the set: " + set);
}
}
}

MapManager.java

package Task5;

import java.util.HashMap;
import java.util.Map;

public class MapManager {


private Map<String, String> map;

public MapManager() {
map = new HashMap<>();
}
public void addEntry(String key, String value) {
if (map.containsKey(key)) {
System.out.println("Key already exists in the
map.");
} else {
map.put(key, value);
System.out.println("Key-value pair added to the
map.");
}
}

public void removeEntry(String key) {


if (map.remove(key) != null) {
System.out.println("Key-value pair removed from the
map.");
} else {
System.out.println("Key not found in the map.");
}
}

public void displayEntries() {


if (map.isEmpty()) {
System.out.println("The map is empty.");
} else {
System.out.println("Key-value pairs in the map: " +
map);
}
}
}
Output:
6) Add new employees: The user can add details like employee ID, name, department,
and salary.
a) Update employee details: The user can update the name, department, or
salary of an existing employee based on their employee ID.
b) Delete an employee: The user can delete an employee from the system
based on their employee ID.
c) Display all employees: The user can view a list of all employees and their
details.
d) Search for an employee: The user can search for an employee by their
employee ID and view their details.
e) Requirements:
i) Use Object-Oriented Programming (OOP) principles and create an
Employee class with appropriate attributes and methods.
ii) Use appropriate data structures (e.g., ArrayList, HashMap) to store
the employee data.
iii) Implement exception handling to handle possible errors (e.g., invalid
employee ID, input validation).
iv) Provide a user-friendly console interface for the user to interact with
the Employee Management System.

Code:

Employee.java:

class Employee {
private String employeeID;
private String name;
private String department;
private double salary;

public Employee(String employeeID, String name, String department,


double salary) {
this.employeeID = employeeID;
this.name = name;
this.department = department;
this.salary = salary;
}
// Getters and setters for each attribute
public String getEmployeeID() {
return employeeID;
}

public void setEmployeeID(String employeeID) {


this.employeeID = employeeID;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getDepartment() {


return department;
}

public void setDepartment(String department) {


this.department = department;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

@Override
public String toString() {
return "Employee ID: " + employeeID + ", Name: " + name + ", De-
partment: " + department + ", Salary: " + salary;
}
}
EmployeeManagementSystem.java:

import java.util.*;

public class EmployeeManagementSystem {


private static Map<String, Employee> employees = new HashMap<>();

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("\nEmployee Management System");
System.out.println("1) Add new employee");
System.out.println("2) Update employee details");
System.out.println("3) Delete an employee");
System.out.println("4) Display all employees");
System.out.println("5) Search for an employee");
System.out.println("6) Exit");

System.out.print("Enter your choice (1-6): ");


int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline character

switch (choice) {
case 1:
addEmployee(scanner);
break;
case 2:
updateEmployee(scanner);
break;
case 3:
deleteEmployee(scanner);
break;
case 4:
displayAllEmployees();
break;
case 5:
searchEmployee(scanner);
break;
case 6:
System.out.println("Exiting program...");
scanner.close();
return;
default:
System.out.println("Invalid choice. Please enter a
valid option (1-6).");
}
}
}

private static void addEmployee(Scanner scanner) {


System.out.print("Enter employee ID: ");
String employeeID = scanner.nextLine();

if (employees.containsKey(employeeID)) {
System.out.println("Employee ID already exists. Please use a
unique ID.");
return;
}

System.out.print("Enter name: ");


String name = scanner.nextLine();

System.out.print("Enter department: ");


String department = scanner.nextLine();

System.out.print("Enter salary: ");


double salary = scanner.nextDouble();
scanner.nextLine(); // Consume newline character

Employee employee = new Employee(employeeID, name, department,


salary);
employees.put(employeeID, employee);
System.out.println("Employee added successfully.");
}

private static void updateEmployee(Scanner scanner) {


System.out.print("Enter employee ID to update: ");
String employeeID = scanner.nextLine();

Employee employee = employees.get(employeeID);


if (employee == null) {
System.out.println("Employee not found.");
return;
}

System.out.println("Current details: " + employee);


System.out.println("Enter new details (leave blank to keep cur-
rent value):");
System.out.print("Enter new name: ");
String name = scanner.nextLine();
if (!name.isEmpty()) {
employee.setName(name);
}

System.out.print("Enter new department: ");


String department = scanner.nextLine();
if (!department.isEmpty()) {
employee.setDepartment(department);
}

System.out.print("Enter new salary: ");


String salaryInput = scanner.nextLine();
if (!salaryInput.isEmpty()) {
try {
double salary = Double.parseDouble(salaryInput);
employee.setSalary(salary);
} catch (NumberFormatException e) {
System.out.println("Invalid salary input. Keeping current
value.");
}
}

System.out.println("Employee details updated successfully.");


}

private static void deleteEmployee(Scanner scanner) {


System.out.print("Enter employee ID to delete: ");
String employeeID = scanner.nextLine();

Employee removedEmployee = employees.remove(employeeID);


if (removedEmployee == null) {
System.out.println("Employee not found.");
} else {
System.out.println("Employee deleted successfully.");
}
}

private static void displayAllEmployees() {


if (employees.isEmpty()) {
System.out.println("No employees to display.");
} else {
for (Employee employee : employees.values()) {
System.out.println(employee);
}
}
}

private static void searchEmployee(Scanner scanner) {


System.out.print("Enter employee ID to search: ");
String employeeID = scanner.nextLine();

Employee employee = employees.get(employeeID);


if (employee == null) {
System.out.println("Employee not found.");
} else {
System.out.println(employee);
}
}
}

Output:

You might also like