Ankit Raj February - Full - Stack24 Java Assignment
Ankit Raj February - Full - Stack24 Java Assignment
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);
}
// 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;
}
// 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();
}
Car(String model) {
this.model = model;
}
void start() {
System.out.println("Car " + model + " is starting.");
}
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();
}
}
void work() {
System.out.println(name + " is working.");
}
}
// 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();
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.
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");
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:
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");
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();
}
// 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.");
}
}
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;
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();
}
t1.start();
t2.start();
}
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.start();
t2.start();
}
t1.start();
t2.start();
}
t1.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.interrupt();
}
class SharedResource {
private boolean available = false;
t1.start();
t2.start();
}
t1.start();
t2.start();
}
public static void threadLocalVariables() {
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
t1.start();
t2.start();
}
t1.start();
t2.start();
}
try {
System.out.println("Sum: " + future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
}
}
}
Output:-
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.*;
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();
}
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);
}
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);
}
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);
}
}
@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);
}
}
@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<>();
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;
@Override
public String toString() {
return "Employee ID: " + id + ", Name: " + name + ", Department: " + department + ",
Salary: " + salary;
}
}
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();
}
Output:-