Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Ankit Raj February - Full - Stack24 Java Assignment

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

Ankit Raj February - Full - Stack24 Java Assignment

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

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
Generalization and Specialization

Code:- // a) Class and Object


class Animal {
String name;

void display() {
System.out.println("I am an animal.");
}
}

// b) Class constructor
class Dog extends Animal implements Pet {
Dog(String name) {
this.name = name;
}

void display() {
System.out.println("I am a dog. My name is " + name);
}

// Implement the play method from the Pet interface


@Override
public void play() {
System.out.println("Playing fetch with " + name);
}
}

// c) Polymorphism
class Cat extends Animal {
void display() {
System.out.println("I am a cat. My name is " + name);
}
}

// d) Method overloading
class MathOperation {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

// e) Method overriding
class Bird extends Animal {
void display() {
System.out.println("I am a bird. My name is " + name);
}
}

// f) Inheritance
class Sparrow extends Bird {
void display() {
System.out.println("I am a sparrow. My name is " + name);
}
}

// g) Interface
interface Pet {
void play();
}

// h) Abstract class
abstract class Vehicle {
abstract void start();
}

// i) Abstraction and Encapsulation


class Car extends Vehicle {
private String model;

Car(String model) {
this.model = model;
}

void start() {
System.out.println("Car " + model + " is starting.");
}

public String getModel() {


return model;
}
}

// j) Composition and Aggregation


class Engine {
String type;

Engine(String type) {
this.type = type;
}

String getType() {
return type;
}
}

class CarWithEngine {
private Engine engine; // Composition

CarWithEngine(String engineType) {
this.engine = new Engine(engineType);
}

String getEngineType() {
return engine.getType();
}
}

// k) Generalization and Specialization


class Employee {
String name;
int age;

void work() {
System.out.println(name + " is working.");
}
}

class Programmer extends Employee {


void code() {
System.out.println(name + " is coding.");
}
}

// Main class to demonstrate all concepts


public class OOPSDemo {
public static void main(String[] args) {
// a) Class and Object
Animal animal = new Animal();
animal.display();

// b) Class constructor
Dog dog = new Dog("Buddy");
dog.display();

// c) Polymorphism
Animal cat = new Cat();
cat.name = "Whiskers";
cat.display();

// d) Method overloading
MathOperation math = new MathOperation();
System.out.println("Sum of integers: " + math.add(5, 10));
System.out.println("Sum of doubles: " + math.add(5.5, 10.5));

// e) Method overriding
Bird bird = new Bird();
bird.name = "Tweety";
bird.display();

// f) Inheritance
Sparrow sparrow = new Sparrow();
sparrow.name = "Jack";
sparrow.display();

// g) Interface
Pet petDog = new Dog("Max");
petDog.play();

// h) Abstract class
Car car = new Car("Tesla Model S");
car.start();

// i) Abstraction and Encapsulation


System.out.println("Car model: " + car.getModel());

// j) Composition and Aggregation


CarWithEngine carWithEngine = new CarWithEngine("V8");
System.out.println("Car engine type: " + carWithEngine.getEngineType());

// k) Generalization and Specialization


Programmer programmer = new Programmer();
programmer.name = "Alice";
programmer.work();
programmer.code();
}
}

Output:-

1) 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);
boolean continueProgram = true;

while (continueProgram) {
System.out.println("Choose an operation:");
System.out.println("1. Concatenate Strings");
System.out.println("2. Find Length of a String");
System.out.println("3. Convert to Uppercase and Lowercase");
System.out.println("4. Extract Substring");
System.out.println("5. Split a Sentence");
System.out.println("6. Reverse a String");
System.out.println("7. Exit");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter the second string: ");
String str2 = scanner.nextLine();
System.out.println("Concatenated String: " + str1 + str2);
break;
case 2:
System.out.print("Enter a string: ");
String strLength = scanner.nextLine();
System.out.println("Length of the string: " + strLength.length());
break;
case 3:
System.out.print("Enter a string: ");
String strCase = scanner.nextLine();
System.out.println("Uppercase: " + strCase.toUpperCase());
System.out.println("Lowercase: " + strCase.toLowerCase());
break;
case 4:
System.out.print("Enter a string: ");
String strSubstring = scanner.nextLine();
System.out.print("Enter the starting index: ");
int start = scanner.nextInt();
System.out.print("Enter the ending index: ");
int end = scanner.nextInt();
scanner.nextLine(); // Consume newline
if (start >= 0 && end <= strSubstring.length() && start < end) {
System.out.println("Substring: " + strSubstring.substring(start, end));
} else {
System.out.println("Invalid indices.");
}
break;
case 5:
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);
}
break;
case 6:
System.out.print("Enter a string: ");
String strReverse = scanner.nextLine();
String reversed = new StringBuilder(strReverse).reverse().toString();
System.out.println("Reversed String: " + reversed);
break;
case 7:
continueProgram = false;
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please try again.");
}

System.out.println();
}

scanner.close();
}
}

Output:-
1) 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.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class FileOperations {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
boolean continueProgram = true;

while (continueProgram) {
System.out.println("Choose an operation:");
System.out.println("1. Create a new directory");
System.out.println("2. Create a new text file and write content to it");
System.out.println("3. Read content from an existing text file");
System.out.println("4. Append new content to an existing text file");
System.out.println("5. Copy content from one text file to another");
System.out.println("6. Delete a text file");
System.out.println("7. List all files and directories in a given directory");
System.out.println("8. Search for a specific file in a directory and its subdirectories");
System.out.println("9. Rename a file");
System.out.println("10. Get information about a file");
System.out.println("11. Exit");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
System.out.print("Enter the directory name to create: ");
String dirName = scanner.nextLine();
createDirectory(dirName);
break;
case 2:
System.out.print("Enter the file name to create: ");
String fileName = scanner.nextLine();
System.out.print("Enter the content to write: ");
String content = scanner.nextLine();
createFile(fileName, content);
break;
case 3:
System.out.print("Enter the file name to read: ");
String readFileName = scanner.nextLine();
readFile(readFileName);
break;
case 4:
System.out.print("Enter the file name to append content to: ");
String appendFileName = scanner.nextLine();
System.out.print("Enter the content to append: ");
String appendContent = scanner.nextLine();
appendToFile(appendFileName, appendContent);
break;
case 5:
System.out.print("Enter the source file name: ");
String sourceFileName = scanner.nextLine();
System.out.print("Enter the destination file name: ");
String destFileName = scanner.nextLine();
copyFile(sourceFileName, destFileName);
break;
case 6:
System.out.print("Enter the file name to delete: ");
String deleteFileName = scanner.nextLine();
deleteFile(deleteFileName);
break;
case 7:
System.out.print("Enter the directory name to list files: ");
String listDirName = scanner.nextLine();
listFiles(listDirName);
break;
case 8:
System.out.print("Enter the directory name to search: ");
String searchDirName = scanner.nextLine();
System.out.print("Enter the file name to search for: ");
String searchFileName = scanner.nextLine();
searchFile(searchDirName, searchFileName);
break;
case 9:
System.out.print("Enter the current file name: ");
String currentFileName = scanner.nextLine();
System.out.print("Enter the new file name: ");
String newFileName = scanner.nextLine();
renameFile(currentFileName, newFileName);
break;
case 10:
System.out.print("Enter the file name to get information about: ");
String infoFileName = scanner.nextLine();
getFileInfo(infoFileName);
break;
case 11:
continueProgram = false;
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please try again.");
}

System.out.println();
}

scanner.close();
}

// Create a new directory


public static void createDirectory(String dirName) {
File dir = new File(dirName);
if (dir.mkdirs()) {
System.out.println("Directory created successfully.");
} else {
System.out.println("Failed to create directory.");
}
}

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


public static void createFile(String fileName, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(content);
System.out.println("File created and content written successfully.");
} catch (IOException e) {
System.out.println("An error occurred while creating/writing the file.");
e.printStackTrace();
}
}

// Read the content from an existing text file


public static void readFile(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
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.printStackTrace();
}
}

// Append new content to an existing text file


public static void appendToFile(String fileName, String content) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {
writer.write(content);
writer.newLine();
System.out.println("Content appended successfully.");
} catch (IOException e) {
System.out.println("An error occurred while appending to the file.");
e.printStackTrace();
}
}

// Copy the content from one text file to another


public static void copyFile(String sourceFileName, String destFileName) {
try (InputStream in = new FileInputStream(sourceFileName);
OutputStream out = new FileOutputStream(destFileName)) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("An error occurred while copying the file.");
e.printStackTrace();
}
}

// Delete a text file


public static void deleteFile(String fileName) {
File file = new File(fileName);
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
}

// List all files and directories in a given directory


public static void listFiles(String dirName) {
File dir = new File(dirName);
if (dir.isDirectory()) {
String[] files = dir.list();
if (files != null && files.length > 0) {
for (String file : files) {
System.out.println(file);
}
} else {
System.out.println("No files or directories found in the specified directory.");
}
} else {
System.out.println("The specified name is not a directory.");
}
}

// Search for a specific file in a directory and its subdirectories


public static void searchFile(String dirName, String fileName) {
File dir = new File(dirName);
if (dir.isDirectory()) {
searchFileRecursively(dir, fileName);
} else {
System.out.println("The specified name is not a directory.");
}
}

private static void searchFileRecursively(File dir, String fileName) {


File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
searchFileRecursively(file, fileName);
} else if (file.getName().equals(fileName)) {
System.out.println("File found: " + file.getAbsolutePath());
}
}
}
}

// Rename a file
public static void renameFile(String currentFileName, String newFileName) {
File oldFile = new File(currentFileName);
File newFile = new File(newFileName);
if (oldFile.renameTo(newFile)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename the file.");
}
}

// Get information about a file


public static void getFileInfo(String fileName) {
File file = new File(fileName);
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 SimpleDateFormat("dd/MM/yyyy
HH:mm:ss").format(new Date(file.lastModified())));
} else {
System.out.println("File not found.");
}
}
}

1) 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.

Code:-

import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;

public class MultithreadingDemo {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int choice;

do {
System.out.println("\nMultithreading Demonstration:");
System.out.println("1. Create and start multiple threads");
System.out.println("2. Synchronize threads");
System.out.println("3. Thread communication using wait() and notify()");
System.out.println("4. Use sleep() to pause threads");
System.out.println("5. Demonstrate thread interruption and termination");
System.out.println("6. Use thread pools");
System.out.println("7. Thread synchronization using locks and conditions");
System.out.println("8. Demonstrate deadlock and avoidance");
System.out.println("9. Use thread-local variables");
System.out.println("10. Producer-consumer problem");
System.out.println("11. Use Executors and Callable");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
ThreadExamples.startMultipleThreads();
break;
case 2:
ThreadExamples.synchronizeThreads();
break;
case 3:
ThreadExamples.threadCommunication();
break;
case 4:
ThreadExamples.useSleep();
break;
case 5:
ThreadExamples.threadInterruption();
break;
case 6:
ThreadExamples.useThreadPools();
break;
case 7:
ThreadExamples.synchronizationUsingLocks();
break;
case 8:
ThreadExamples.demonstrateDeadlock();
break;
case 9:
ThreadExamples.threadLocalVariables();
break;
case 10:
ThreadExamples.producerConsumerProblem();
break;
case 11:
ThreadExamples.executorsAndCallable();
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);

scanner.close();
}

static class ThreadExamples {

public static void startMultipleThreads() {


Runnable task = () -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

Thread t1 = new Thread(task);


Thread t2 = new Thread(task);

t1.start();
t2.start();
}

public static void synchronizeThreads() {


class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

Counter counter = new Counter();

Runnable task = () -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
};

Thread t1 = new Thread(task);


Thread t2 = new Thread(task);

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final count: " + counter.getCount());


}

public static void threadCommunication() {


class SharedResource {
private boolean available = false;

public synchronized void produce() throws InterruptedException {


while (available) {
wait();
}
System.out.println("Produced");
available = true;
notify();
}

public synchronized void consume() throws InterruptedException {


while (!available) {
wait();
}
System.out.println("Consumed");
available = false;
notify();
}
}

SharedResource resource = new SharedResource();

Runnable producer = () -> {


try {
for (int i = 0; i < 5; i++) {
resource.produce();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};

Runnable consumer = () -> {


try {
for (int i = 0; i < 5; i++) {
resource.consume();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};

Thread t1 = new Thread(producer);


Thread t2 = new Thread(consumer);

t1.start();
t2.start();
}

public static void useSleep() {


Runnable task = () -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is sleeping");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);

t1.start();
t2.start();
}

public static void threadInterruption() {


Thread t1 = new Thread(() -> {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Thread running");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
});

t1.start();

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}

t1.interrupt();
}

public static void useThreadPools() {


ExecutorService executor = Executors.newFixedThreadPool(3);

Runnable task = () -> {


for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

for (int i = 0; i < 5; i++) {


executor.execute(task);
}
executor.shutdown();
}

public static void synchronizationUsingLocks() {


Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();

class SharedResource {
private boolean available = false;

public void produce() throws InterruptedException {


lock.lock();
try {
while (available) {
condition.await();
}
System.out.println("Produced");
available = true;
condition.signal();
} finally {
lock.unlock();
}
}

public void consume() throws InterruptedException {


lock.lock();
try {
while (!available) {
condition.await();
}
System.out.println("Consumed");
available = false;
condition.signal();
} finally {
lock.unlock();
}
}
}

SharedResource resource = new SharedResource();

Runnable producer = () -> {


try {
for (int i = 0; i < 5; i++) {
resource.produce();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};

Runnable consumer = () -> {


try {
for (int i = 0; i < 5; i++) {
resource.consume();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};

Thread t1 = new Thread(producer);


Thread t2 = new Thread(consumer);

t1.start();
t2.start();
}

public static void demonstrateDeadlock() {


class Resource {
private final String name;

public Resource(String name) {


this.name = name;
}

public String getName() {


return name;
}

public synchronized void lockResource(Resource other) {


System.out.println("Locked " + this.name + ", waiting for " + other.getName());
other.lockResource(this);
System.out.println("Acquired lock on " + other.getName());
}
}

Resource resource1 = new Resource("Resource 1");


Resource resource2 = new Resource("Resource 2");

Thread t1 = new Thread(() -> resource1.lockResource(resource2));


Thread t2 = new Thread(() -> resource2.lockResource(resource1));

t1.start();
t2.start();
}
public static void threadLocalVariables() {
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

Runnable task = () -> {


int value = threadLocal.get();
value++;
threadLocal.set(value);
System.out.println(Thread.currentThread().getName() + " thread-local value: " +
threadLocal.get());
};

Thread t1 = new Thread(task);


Thread t2 = new Thread(task);

t1.start();
t2.start();
}

public static void producerConsumerProblem() {


class SharedQueue {
private final int[] buffer = new int[10];
private int count = 0;

public synchronized void produce(int value) throws InterruptedException {


while (count == buffer.length) {
wait();
}
buffer[count++] = value;
notifyAll();
}

public synchronized int consume() throws InterruptedException {


while (count == 0) {
wait();
}
int value = buffer[--count];
notifyAll();
return value;
}
}

SharedQueue queue = new SharedQueue();

Runnable producer = () -> {


try {
for (int i = 0; i < 10; i++) {
queue.produce(i);
System.out.println("Produced " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};

Runnable consumer = () -> {


try {
for (int i = 0; i < 10; i++) {
int value = queue.consume();
System.out.println("Consumed " + value);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
};

Thread t1 = new Thread(producer);


Thread t2 = new Thread(consumer);

t1.start();
t2.start();
}

public static void executorsAndCallable() {


ExecutorService executor = Executors.newFixedThreadPool(3);

Callable<Integer> task = () -> {


int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
Thread.sleep(100);
}
return sum;
};

Future<Integer> future = executor.submit(task);

try {
System.out.println("Sum: " + future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}

executor.shutdown();
}
}
}

Output:-

1) 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

Code:-

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();

int choice;

do {
System.out.println("\nCollection Management System:");
System.out.println("1. Manage Lists");
System.out.println("2. Manage Sets");
System.out.println("3. Manage Maps");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
manageList(scanner, listManager);
break;
case 2:
manageSet(scanner, setManager);
break;
case 3:
manageMap(scanner, mapManager);
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);

scanner.close();
}

private static void manageList(Scanner scanner, ListManager listManager) {


int choice;
do {
System.out.println("\nManage Lists:");
System.out.println("1. Add an element");
System.out.println("2. Remove an element");
System.out.println("3. Display all elements");
System.out.println("0. Back to main menu");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter element to add: ");
String listElementToAdd = scanner.next();
listManager.addElement(listElementToAdd);
break;
case 2:
System.out.print("Enter element to remove: ");
String listElementToRemove = scanner.next();
listManager.removeElement(listElementToRemove);
break;
case 3:
listManager.displayElements();
break;
case 0:
System.out.println("Returning to main menu...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
}

private static void manageSet(Scanner scanner, SetManager setManager) {


int choice;
do {
System.out.println("\nManage Sets:");
System.out.println("1. Add an element");
System.out.println("2. Remove an element");
System.out.println("3. Display all elements");
System.out.println("0. Back to main menu");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter element to add: ");
String setElementToAdd = scanner.next();
setManager.addElement(setElementToAdd);
break;
case 2:
System.out.print("Enter element to remove: ");
String setElementToRemove = scanner.next();
setManager.removeElement(setElementToRemove);
break;
case 3:
setManager.displayElements();
break;
case 0:
System.out.println("Returning to main menu...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
}

private static void manageMap(Scanner scanner, MapManager mapManager) {


int choice;
do {
System.out.println("\nManage Maps:");
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("0. Back to main menu");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
System.out.print("Enter key to add: ");
String keyToAdd = scanner.next();
System.out.print("Enter value to add: ");
String valueToAdd = scanner.next();
mapManager.addKeyValuePair(keyToAdd, valueToAdd);
break;
case 2:
System.out.print("Enter key to remove: ");
String keyToRemove = scanner.next();
mapManager.removeKeyValuePair(keyToRemove);
break;
case 3:
mapManager.displayKeyValuePairs();
break;
case 0:
System.out.println("Returning to main menu...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);
}
}

abstract class CollectionManager<T> {


public abstract void addElement(T element);
public abstract void removeElement(T element);
public abstract void displayElements();
}

class ListManager extends CollectionManager<String> {


private List<String> list = new ArrayList<>();

@Override
public void addElement(String element) {
list.add(element);
System.out.println("Added " + element + " to the list.");
}
@Override
public void removeElement(String element) {
if (list.remove(element)) {
System.out.println("Removed " + element + " from the list.");
} else {
System.out.println("Element " + element + " not found in the list.");
}
}

@Override
public void displayElements() {
System.out.println("List elements: " + list);
}
}

class SetManager extends CollectionManager<String> {


private Set<String> set = new HashSet<>();

@Override
public void addElement(String element) {
if (set.add(element)) {
System.out.println("Added " + element + " to the set.");
} else {
System.out.println("Element " + element + " is already in the set.");
}
}

@Override
public void removeElement(String element) {
if (set.remove(element)) {
System.out.println("Removed " + element + " from the set.");
} else {
System.out.println("Element " + element + " not found in the set.");
}
}

@Override
public void displayElements() {
System.out.println("Set elements: " + set);
}
}

class MapManager {
private Map<String, String> map = new HashMap<>();

public void addKeyValuePair(String key, String value) {


if (map.containsKey(key)) {
System.out.println("Key " + key + " already exists with value " + map.get(key));
} else {
map.put(key, value);
System.out.println("Added key-value pair (" + key + ", " + value + ") to the map.");
}
}

public void removeKeyValuePair(String key) {


if (map.containsKey(key)) {
map.remove(key);
System.out.println("Removed key-value pair with key " + key + " from the map.");
} else {
System.out.println("Key " + key + " not found in the map.");
}
}

public void displayKeyValuePairs() {


System.out.println("Map key-value pairs: " + map);
}
}

Output:-

2) 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:-

import java.util.*;

class Employee {
private int id;
private String name;
private String department;
private double salary;

public Employee(int id, String name, String department, double salary) {


this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}

public int getId() {


return id;
}

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: " + id + ", Name: " + name + ", Department: " + department + ",
Salary: " + salary;
}
}

public class EmployeeManagementSystem {


private static Map<Integer, Employee> employeeMap = new HashMap<>();

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int choice;

do {
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("0. Exit");
System.out.print("Enter your choice: ");
while (!scanner.hasNextInt()) {
System.out.print("Invalid input. Enter a number: ");
scanner.next();
}
choice = scanner.nextInt();

switch (choice) {
case 1:
addNewEmployee(scanner);
break;
case 2:
updateEmployeeDetails(scanner);
break;
case 3:
deleteEmployee(scanner);
break;
case 4:
displayAllEmployees();
break;
case 5:
searchForEmployee(scanner);
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 0);

scanner.close();
}

private static void addNewEmployee(Scanner scanner) {


try {
System.out.print("Enter Employee ID: ");
while (!scanner.hasNextInt()) {
System.out.print("Invalid input. Enter a valid Employee ID: ");
scanner.next();
}
int id = scanner.nextInt();
if (employeeMap.containsKey(id)) {
System.out.println("Employee ID already exists. Try again.");
return;
}
scanner.nextLine(); // Consume newline

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


String name = scanner.nextLine();

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


String department = scanner.nextLine();

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


while (!scanner.hasNextDouble()) {
System.out.print("Invalid input. Enter a valid salary: ");
scanner.next();
}
double salary = scanner.nextDouble();

Employee employee = new Employee(id, name, department, salary);


employeeMap.put(id, employee);
System.out.println("Employee added successfully.");
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please try again.");
scanner.next(); // Consume invalid input
}
}

private static void updateEmployeeDetails(Scanner scanner) {


try {
System.out.print("Enter Employee ID to update: ");
while (!scanner.hasNextInt()) {
System.out.print("Invalid input. Enter a valid Employee ID: ");
scanner.next();
}
int id = scanner.nextInt();
if (!employeeMap.containsKey(id)) {
System.out.println("Employee ID not found. Try again.");
return;
}
scanner.nextLine(); // Consume newline

Employee employee = employeeMap.get(id);

System.out.print("Enter new Name (leave blank to keep unchanged): ");


String name = scanner.nextLine();
if (!name.isEmpty()) {
employee.setName(name);
}

System.out.print("Enter new Department (leave blank to keep unchanged): ");


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

System.out.print("Enter new Salary (enter -1 to keep unchanged): ");


while (!scanner.hasNextDouble()) {
System.out.print("Invalid input. Enter a valid salary: ");
scanner.next();
}
double salary = scanner.nextDouble();
if (salary >= 0) {
employee.setSalary(salary);
}

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


} catch (InputMismatchException e) {
System.out.println("Invalid input. Please try again.");
scanner.next(); // Consume invalid input
}
}

private static void deleteEmployee(Scanner scanner) {


try {
System.out.print("Enter Employee ID to delete: ");
while (!scanner.hasNextInt()) {
System.out.print("Invalid input. Enter a valid Employee ID: ");
scanner.next();
}
int id = scanner.nextInt();
if (employeeMap.remove(id) != null) {
System.out.println("Employee deleted successfully.");
} else {
System.out.println("Employee ID not found. Try again.");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please try again.");
scanner.next(); // Consume invalid input
}
}

private static void displayAllEmployees() {


if (employeeMap.isEmpty()) {
System.out.println("No employees found.");
} else {
employeeMap.values().forEach(System.out::println);
}
}

private static void searchForEmployee(Scanner scanner) {


try {
System.out.print("Enter Employee ID to search: ");
while (!scanner.hasNextInt()) {
System.out.print("Invalid input. Enter a valid Employee ID: ");
scanner.next();
}
int id = scanner.nextInt();
Employee employee = employeeMap.get(id);
if (employee != null) {
System.out.println(employee);
} else {
System.out.println("Employee ID not found.");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please try again.");
scanner.next(); // Consume invalid input
}
}
}

Output:-

You might also like