✅ Question 1 — ShapePkg: Interface with Circle & Rectangle
ShapePkg/
├── Shape.java (interface)
├── Circle.java (implements Shape)
├── Rectangle.java (implements Shape)
└── Main.java (main class)
💻 Code
Shape.java
javapackage ShapePkg;
public interface Shape {
double area();
double perimeter();
}
Circle.java
javapackage ShapePkg;
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public double perimeter() {
return 2 * Math.PI * radius;
}
}
Rectangle.java
javapackage ShapePkg;
public class Rectangle implements Shape {
private double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double area() {
return length * width;
}
@Override
public double perimeter() {
return 2 * (length + width);
}
}
Main.java
javapackage ShapePkg;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter radius of Circle: ");
double radius = sc.nextDouble();
Circle c = new Circle(radius);
System.out.printf("Circle -> Area: %.2f, Perimeter: %.2f%n",
c.area(), c.perimeter());
System.out.print("Enter length of Rectangle: ");
double length = sc.nextDouble();
System.out.print("Enter width of Rectangle: ");
double width = sc.nextDouble();
Rectangle r = new Rectangle(length, width);
System.out.printf("Rectangle -> Area: %.2f, Perimeter: %.2f%n",
r.area(), r.perimeter());
sc.close();
}
}
✅ Question 2 — MultiInterfacePkg: Multiple Interface Implementation
💻 Code
Printable.java
javapackage MultiInterfacePkg;
public interface Printable {
void print();
}
Showable.java
javapackage MultiInterfacePkg;
public interface Showable {
void show();
}
Document.java
javapackage MultiInterfacePkg;
public class Document implements Printable, Showable {
private String content;
public Document(String content) {
this.content = content;
}
@Override
public void print() {
System.out.println("Printing document: " + content);
}
@Override
public void show() {
System.out.println("Showing document on screen: " + content);
}
}
Main.java
javapackage MultiInterfacePkg;
public class Main {
public static void main(String[] args) {
Document doc = new Document("Java Assignment Report");
doc.print();
doc.show();
// Polymorphic references
Printable p = doc;
p.print();
Showable s = doc;
s.show();
}
}
✅ Question 3 — MathOperationsPkg: Calculator with Packages
💻 Code
Calculator.java (in MathOperationsPkg)
javapackage MathOperationsPkg;
public class Calculator {
public double add(double a, double b) {
return a + b;
}
public double subtract(double a, double b) {
return a - b;
}
public double multiply(double a, double b) {
return a * b;
}
public double divide(double a, double b) {
if (b == 0) {
System.out.println("Error: Cannot divide by zero!");
return 0;
}
return a / b;
}
}
Main.java (in MainPkg — different package)
javapackage MainPkg;
import MathOperationsPkg.Calculator; // explicit import
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Calculator calc = new Calculator();
System.out.print("Enter first number: ");
double a = sc.nextDouble();
System.out.print("Enter second number: ");
double b = sc.nextDouble();
System.out.println("Choose operation: 1-Add 2-Sub 3-Mul 4-Div");
int choice = sc.nextInt();
switch (choice) {
case 1: System.out.println("Result: " + calc.add(a, b)); break;
case 2: System.out.println("Result: " + calc.subtract(a, b)); break;
case 3: System.out.println("Result: " + calc.multiply(a, b)); break;
case 4: System.out.println("Result: " + calc.divide(a, b)); break;
default: System.out.println("Invalid choice");
}
sc.close();
}
}
✅ Question 4 — StudentPkg: Access Modifiers
💻 Code
Student.java (in StudentPkg)
javapackage StudentPkg;
public class Student {
public String name = "Alice"; // accessible everywhere
protected int rollNo = 101; // accessible in subclass & same pkg
String grade = "A"; // default: same package only
private double gpa = 9.5; // only within this class
public void displayAll() {
// All accessible within the same class
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
System.out.println("Grade: " + grade);
System.out.println("GPA: " + gpa);
}
}
AccessTest.java (in OtherPkg — different package)
javapackage OtherPkg;
import StudentPkg.Student;
public class AccessTest {
public static void main(String[] args) {
Student s = new Student();
// ✅ public — accessible
System.out.println("Name: " + s.name);
// ❌ protected — NOT accessible from different non-subclass package
// System.out.println(s.rollNo); // Compile error
// ❌ default — NOT accessible from different package
// System.out.println(s.grade); // Compile error
// ❌ private — never accessible outside class
// System.out.println(s.gpa); // Compile error
System.out.println("Only public members are accessible from OtherPkg!");
// Call public method (which internally accesses all)
s.displayAll();
}
}
✅ Question 5 — UtilityPkg: StringUtility with Import Types
💻 Code
StringUtility.java (in UtilityPkg)
javapackage UtilityPkg;
public class StringUtility {
public String reverse(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
public String toUpperCase(String str) {
return str.toUpperCase();
}
}
MainExplicit.java — uses explicit import
javapackage MainPkg;
import UtilityPkg.StringUtility; // explicit import
public class MainExplicit {
public static void main(String[] args) {
StringUtility su = new StringUtility();
String word = "hello world";
System.out.println("Original: " + word);
System.out.println("Reversed: " + su.reverse(word));
System.out.println("Uppercase: " + su.toUpperCase(word));
}
}
MainWildcard.java — uses wildcard import
javapackage MainPkg2;
import UtilityPkg.*; // wildcard import
public class MainWildcard {
public static void main(String[] args) {
StringUtility su = new StringUtility();
String word = "Java Programming";
System.out.println("Original: " + word);
System.out.println("Reversed: " + su.reverse(word));
System.out.println("Uppercase: " + su.toUpperCase(word));
}
}
✅ Question 6 — StudentDataPkg: Accept & Calculate Marks
💻 Code
Student.java (in StudentDataPkg)
javapackage StudentDataPkg;
import java.util.Scanner;
public class Student {
String name;
int rollNo;
double marks1, marks2, marks3;
double total, average;
public void acceptDetails() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
name = sc.nextLine();
System.out.print("Enter Roll Number: ");
rollNo = sc.nextInt();
System.out.print("Enter Marks of Subject 1: ");
marks1 = sc.nextDouble();
System.out.print("Enter Marks of Subject 2: ");
marks2 = sc.nextDouble();
System.out.print("Enter Marks of Subject 3: ");
marks3 = sc.nextDouble();
total = marks1 + marks2 + marks3;
average = total / 3;
}
public void displayDetails() {
System.out.println("\n===== Student Details =====");
System.out.println("Name : " + name);
System.out.println("Roll No : " + rollNo);
System.out.println("Marks : " + marks1 + ", " + marks2 + ", " + marks3);
System.out.printf("Total : %.2f%n", total);
System.out.printf("Average : %.2f%n", average);
}
}
Main.java
javapackage StudentDataPkg;
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.acceptDetails();
s.displayDetails();
}
}
✅ Question 7 — ExceptionPkg: try-catch-finally
💻 Code
Division.java (in ExceptionPkg)
javapackage ExceptionPkg;
public class Division {
public double divide(int a, int b) {
return a / b; // throws ArithmeticException if b == 0
}
}
Main.java
javapackage ExceptionPkg;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Division d = new Division();
System.out.print("Enter numerator: ");
int a = sc.nextInt();
System.out.print("Enter denominator: ");
int b = sc.nextInt();
try {
double result = d.divide(a, b);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Finally block: Division operation attempted.");
}
sc.close();
}
}
✅ Question 8 — AgePkg: throw and throws
💻 Code
AgeValidator.java (in AgePkg)
javapackage AgePkg;
public class AgeValidator {
// 'throws' tells callers: this method might throw an exception
public void checkAge(int age) throws Exception {
if (age < 18) {
// 'throw' actually creates and throws the exception
throw new Exception("Age " + age + " is below 18. Access denied!");
}
System.out.println("Age " + age + " is valid. Access granted!");
}
}
Main.java
javapackage AgePkg;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
AgeValidator av = new AgeValidator();
System.out.print("Enter your age: ");
int age = sc.nextInt();
try {
av.checkAge(age);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
sc.close();
}
}
✅ Question 9 — EmployeePkg: Custom Exception
💻 Code
InvalidSalaryException.java (in EmployeePkg)
javapackage EmployeePkg;
// Custom checked exception
public class InvalidSalaryException extends Exception {
public InvalidSalaryException(String message) {
super(message); // passes message to parent Exception class
}
}
Employee.java
javapackage EmployeePkg;
public class Employee {
private String name;
private double salary;
private static final double MIN_SALARY = 15000.0;
public Employee(String name, double salary) throws InvalidSalaryException {
if (salary < MIN_SALARY) {
throw new InvalidSalaryException(
"Salary Rs." + salary + " is below minimum limit of Rs." + MIN_SALARY
);
}
this.name = name;
this.salary = salary;
}
public void display() {
System.out.println("Employee: " + name + " | Salary: Rs." + salary);
}
}
Main.java
javapackage EmployeePkg;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter employee name: ");
String name = sc.next();
System.out.print("Enter salary: ");
double salary = sc.nextDouble();
try {
Employee emp = new Employee(name, salary);
emp.display();
} catch (InvalidSalaryException e) {
System.out.println("Custom Exception Caught: " + e.getMessage());
}
sc.close();
}
}
✅ Question 10 — ArrayListPkg: Student Manager
💻 Code
Student.java (in ArrayListPkg)
javapackage ArrayListPkg;
public class Student {
int id;
String name;
double marks;
public Student(int id, String name, double marks) {
this.id = id;
this.name = name;
this.marks = marks;
}
@Override
public String toString() {
return "ID: " + id + " | Name: " + name + " | Marks: " + marks;
}
}
StudentManager.java
javapackage ArrayListPkg;
import java.util.ArrayList;
public class StudentManager {
private ArrayList<?Student> list = new ArrayList<>();
public void addStudent(Student s) {
list.add(s);
System.out.println("Student added: " + s.name);
}
public void removeStudent(int id) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).id == id) {
System.out.println("Removed: " + list.get(i).name);
list.remove(i);
return;
}
}
System.out.println("Student with ID " + id + " not found.");
}
public void searchStudent(int id) {
for (Student s : list) {
if (s.id == id) {
System.out.println("Found: " + s);
return;
}
}
System.out.println("Student with ID " + id + " not found.");
}
public void displayAll() {
if (list.isEmpty()) {
System.out.println("No students in list.");
return;
}
System.out.println("===== All Students =====");
for (Student s : list) {
System.out.println(s);
}
}
}
Main.java
javapackage ArrayListPkg;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StudentManager sm = new StudentManager();
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n1-Add 2-Remove 3-Search 4-Display 5-Exit");
System.out.print("Choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("ID: "); int id = sc.nextInt();
System.out.print("Name: "); String name = sc.next();
System.out.print("Marks: "); double marks = sc.nextDouble();
sm.addStudent(new Student(id, name, marks));
break;
case 2:
System.out.print("Enter ID to remove: ");
sm.removeStudent(sc.nextInt());
break;
case 3:
System.out.print("Enter ID to search: ");
sm.searchStudent(sc.nextInt());
break;
case 4:
sm.displayAll();
break;
}
} while (choice != 5);
sc.close();
}
}
✅ Question 11 — ArrayListSortPkg: Sorting with Comparator
💻 Code
Employee.java (in ArrayListSortPkg)
javapackage ArrayListSortPkg;
public class Employee {
int id;
String name;
double salary;
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return "ID: " + id + " | " + name + " | Salary: " + salary;
}
}
Main.java
javapackage ArrayListSortPkg;
import java.util.;
import java.util.stream.;
public class Main {
public static void main(String[] args) {
ArrayList <?Employee> empList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("How many employees? ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("Enter ID, Name, Salary: ");
int id = sc.nextInt();
String name = sc.next();
double salary = sc.nextDouble();
empList.add(new Employee(id, name, salary));
}
// Sort by salary using Comparator (lambda)
Collections.sort(empList, (a, b) -> Double.compare(a.salary, b.salary));
System.out.println("\n--- Sorted by Salary (Ascending) ---");
for (Employee e : empList) {
System.out.println(e);
}
// Filter employees with salary above threshold
System.out.print("\nEnter salary threshold to filter: ");
double threshold = sc.nextDouble();
List<Employee> filtered = empList.stream()
.filter(e -> e.salary > threshold)
.collect(Collectors.toList());
System.out.println("--- Employees with salary above " + threshold + " ---");
if (filtered.isEmpty()) System.out.println("None found.");
else filtered.forEach(System.out::println);
sc.close();
}
}
✅ Question 12 — LinkedListPkg: Task Manager
💻 Code
Task.java (in LinkedListPkg)
javapackage LinkedListPkg;
public class Task {
int taskId;
String taskName;
public Task(int taskId, String taskName) {
this.taskId = taskId;
this.taskName = taskName;
}
@Override
public String toString() {
return "Task[" + taskId + "]: " + taskName;
}
}
TaskManager.java
javapackage LinkedListPkg;
import java.util.LinkedList;
public class TaskManager {
private LinkedList<?Task> taskList = new LinkedList<>();
public void addAtBeginning(Task t) {
taskList.addFirst(t);
System.out.println("Added at beginning: " + t);
}
public void addAtEnd(Task t) {
taskList.addLast(t);
System.out.println("Added at end: " + t);
}
public void removeTask(int taskId) {
boolean found = taskList.removeIf(t -> t.taskId == taskId);
System.out.println(found ? "Task " + taskId + " removed."
: "Task " + taskId + " not found.");
}
public void displayTasks() {
if (taskList.isEmpty()) {
System.out.println("No tasks.");
return;
}
System.out.println("--- Task List ---");
for (Task t : taskList) System.out.println(t);
}
}
Main.java
javapackage LinkedListPkg;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
TaskManager tm = new TaskManager();
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n1-Add Beginning 2-Add End 3-Remove 4-Display 5-Exit");
System.out.print("Choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
case 2:
System.out.print("Task ID: "); int id = sc.nextInt();
System.out.print("Task Name: "); String name = sc.next();
Task t = new Task(id, name);
if (choice == 1) tm.addAtBeginning(t);
else tm.addAtEnd(t);
break;
case 3:
System.out.print("Enter Task ID to remove: ");
tm.removeTask(sc.nextInt());
break;
case 4:
tm.displayTasks();
break;
}
} while (choice != 5);
sc.close();
}
}
✅ Question 13 — QueuePkg: Queue Simulation
💻 Code
QueueDemo.java (in QueuePkg)
javapackage QueuePkg;
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
private Queue<?Integer> queue = new LinkedList<>();
public void enqueue(int value) {
queue.offer(value);
System.out.println(value + " enqueued.");
}
public void dequeue() throws Exception {
if (queue.isEmpty()) {
throw new Exception("Queue Underflow! Queue is empty.");
}
System.out.println(queue.poll() + " dequeued.");
}
public void peek() throws Exception {
if (queue.isEmpty()) {
throw new Exception("Queue is empty! Nothing to peek.");
}
System.out.println("Front element: " + queue.peek());
}
public void display() {
System.out.println("Queue: " + queue);
}
}
Main.java
javapackage QueuePkg;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
QueueDemo q = new QueueDemo();
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n1-Enqueue 2-Dequeue 3-Peek 4-Display 5-Exit");
System.out.print("Choice: ");
choice = sc.nextInt();
try {
switch (choice) {
case 1:
System.out.print("Enter value: ");
q.enqueue(sc.nextInt());
break;
case 2: q.dequeue(); break;
case 3: q.peek(); break;
case 4: q.display(); break;
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
} while (choice != 5);
sc.close();
}
}
✅ Question 14 — VectorPkg: Thread-Safe Vector
💻 Code
Product.java (in VectorPkg)
javapackage VectorPkg;
public class Product {
int id;
String name;
double price;
public Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Product[" + id + "]: " + name + " @ Rs." + price;
}
}
Main.java
javapackage VectorPkg;
import java.util.Vector;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Vector<?Product> products = new Vector<>();
Scanner sc = new Scanner(System.in);
System.out.print("How many products to add? ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("Enter ID, Name, Price: ");
int id = sc.nextInt();
String name = sc.next();
double price = sc.nextDouble();
products.add(new Product(id, name, price));
}
System.out.println("\n--- All Products ---");
for (Product p : products) System.out.println(p);
System.out.print("\nEnter index to remove (0-based): ");
int idx = sc.nextInt();
if (idx >= 0 && idx < products.size()) {
System.out.println("Removed: " + products.remove(idx));
} else {
System.out.println("Invalid index.");
}
System.out.println("\n--- After Removal ---");
products.forEach(System.out::println);
// Demonstrate thread-safe behavior
System.out.println("\nVector size: " + products.size());
System.out.println("Vector is synchronized (thread-safe).");
sc.close();
}
}
✅ Question 15 — StackPkg: Postfix Expression Evaluator
💻 Code
StackDemo.java (in StackPkg)
javapackage StackPkg;
import java.util.Stack;
public class StackDemo {
private Stack<?Double> stack = new Stack<>();
public double evaluatePostfix(String expression) throws Exception {
String[] tokens = expression.trim().split("\\s+");
for (String token : tokens) {
if (isNumber(token)) {
stack.push(Double.parseDouble(token));
} else if (isOperator(token)) {
if (stack.size() < 2) {
throw new Exception("Invalid expression: not enough operands.");
}
double b = stack.pop();
double a = stack.pop();
double result = applyOperator(token, a, b);
stack.push(result);
System.out.println(" " + a + " " + token + " " + b + " = " + result);
} else {
throw new Exception("Unknown token: " + token);
}
}
if (stack.size() != 1) {
throw new Exception("Invalid expression.");
}
return stack.pop();
}
private boolean isNumber(String s) {
try { Double.parseDouble(s); return true; }
catch (NumberFormatException e) { return false; }
}
private boolean isOperator(String s) {
return s.equals("+") || s.equals("-") ||
s.equals("*") || s.equals("/");
}
private double applyOperator(String op, double a, double b) throws Exception {
switch (op) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/":
if (b == 0) throw new Exception("Division by zero!");
return a / b;
default: throw new Exception("Unknown operator: " + op);
}
}
// Stack operations
public void push(double val) { stack.push(val); System.out.println("Pushed: " + val); }
public double pop() throws Exception {
if (stack.isEmpty()) throw new Exception("Stack Underflow!");
double val = stack.pop(); System.out.println("Popped: " + val); return val;
}
public double peek() throws Exception {
if (stack.isEmpty()) throw new Exception("Stack is empty!");
return stack.peek();
}
}
Main.java
javapackage StackPkg;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
StackDemo sd = new StackDemo();
System.out.println("Enter postfix expression (e.g., 3 4 + 2 *):");
sc.nextLine();
String expr = sc.nextLine();
try {
double result = sd.evaluatePostfix(expr);
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
sc.close();
}
}
✅ Question 16 — HashSetPkg: Unique Courses
💻 Code
Course.java (in HashSetPkg)
javapackage HashSetPkg;
import java.util.Objects;
public class Course {
int courseId;
String courseName;
public Course(int courseId, String courseName) {
this.courseId = courseId;
this.courseName = courseName;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Course)) return false;
Course c = (Course) obj;
return this.courseId == c.courseId &&
this.courseName.equals(c.courseName);
}
@Override
public int hashCode() {
return Objects.hash(courseId, courseName);
}
@Override
public String toString() {
return "Course[" + courseId + "]: " + courseName;
}
}
Main.java
javapackage HashSetPkg;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<?Course> courseSet = new HashSet<>();
courseSet.add(new Course(101, "Java Programming"));
courseSet.add(new Course(102, "Data Structures"));
courseSet.add(new Course(101, "Java Programming")); // duplicate — will be ignored
courseSet.add(new Course(103, "Web Development"));
System.out.println("Unique Courses (size=" + courseSet.size() + "):");
for (Course c : courseSet) {
System.out.println(c);
}
}
}
✅ Question 17 — LinkedHashSetPkg: Insertion-Order Books
💻 Code
Book.java (in LinkedHashSetPkg)
javapackage LinkedHashSetPkg;
import java.util.Objects;
public class Book {
int bookId;
String bookName;
public Book(int bookId, String bookName) {
this.bookId = bookId;
this.bookName = bookName;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Book)) return false;
Book b = (Book) o;
return bookId == b.bookId && bookName.equals(b.bookName);
}
@Override
public int hashCode() {
return Objects.hash(bookId, bookName);
}
@Override
public String toString() {
return "Book[" + bookId + "]: " + bookName;
}
}
Main.java
javapackage LinkedHashSetPkg;
import java.util.LinkedHashSet;
public class Main {
public static void main(String[] args) {
LinkedHashSet<?Book> bookSet = new LinkedHashSet<>();
bookSet.add(new Book(1, "Clean Code"));
bookSet.add(new Book(2, "Effective Java"));
bookSet.add(new Book(3, "Design Patterns"));
bookSet.add(new Book(1, "Clean Code")); // duplicate — ignored
bookSet.add(new Book(4, "The Pragmatic Programmer"));
System.out.println("Books (insertion order maintained, size=" + bookSet.size() + "):");
for (Book b : bookSet) {
System.out.println(b);
}
}
}
✅ Question 18 — TreeSetPkg: Sorted Players using Comparable
💻 Code
Player.java (in TreeSetPkg)
javapackage TreeSetPkg;
public class Player implements Comparable<?Player> {
int id;
int score;
public Player(int id, int score) {
this.id = id;
this.score = score;
}
@Override
public int compareTo(Player other) {
// Sort by score ascending; if equal, sort by id
if (this.score != other.score)
return Integer.compare(this.score, other.score);
return Integer.compare(this.id, other.id);
}
@Override
public String toString() {
return "Player[ID=" + id + ", Score=" + score + "]";
}
}
Main.java
javapackage TreeSetPkg;
import java.util.TreeSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
TreeSet<?Player> playerSet = new TreeSet<>();
Scanner sc = new Scanner(System.in);
System.out.print("How many players? ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("Enter player ID and Score: ");
int id = sc.nextInt();
int score = sc.nextInt();
playerSet.add(new Player(id, score));
}
System.out.println("\n--- Players sorted by Score ---");
for (Player p : playerSet) {
System.out.println(p);
}
sc.close();
}
}
✅ Question 19 — TreeMapPkg: Library with TreeMap
💻 Code
Library.java (in TreeMapPkg)
javapackage TreeMapPkg;
import java.util.TreeMap;
import java.util.Map;
public class Library {
private TreeMap<?Integer, String> books = new TreeMap<>();
public void addBook(int id, String name) {
books.put(id, name);
System.out.println("Added: [" + id + "] " + name);
}
public void removeBook(int id) {
if (books.containsKey(id)) {
System.out.println("Removed: [" + id + "] " + books.remove(id));
} else {
System.out.println("Book ID " + id + " not found.");
}
}
public void searchBook(int id) {
String name = books.get(id);
if (name != null) System.out.println("Found: [" + id + "] " + name);
else System.out.println("Book ID " + id + " not found.");
}
public void displayAll() {
if (books.isEmpty()) { System.out.println("Library is empty."); return; }
System.out.println("--- Library (sorted by Book ID) ---");
for (Map.Entry<Integer, String> entry : books.entrySet()) {
System.out.println("[" + entry.getKey() + "] " + entry.getValue());
}
}
}
Main.java
javapackage TreeMapPkg;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Library lib = new Library();
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("\n1-Add 2-Remove 3-Search 4-Display 5-Exit");
System.out.print("Choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Book ID: "); int id = sc.nextInt();
System.out.print("Book Name: "); String name = sc.next();
lib.addBook(id, name);
break;
case 2:
System.out.print("Book ID to remove: ");
lib.removeBook(sc.nextInt());
break;
case 3:
System.out.print("Book ID to search: ");
lib.searchBook(sc.nextInt());
break;
case 4:
lib.displayAll();
break;
}
} while (choice != 5);
sc.close();
}
}
1 Create a base class Animal with a method eat() and extend it with a subclass Dog that includes an additional method bark(). Demonstrate how inheritance allows the Dog class to access both its own method and the inherited method.
CODE:
class Animal { void eat(){
System.out.println("This animal eats foods.");
}
}
class Dog extends Animal{
void bark(){
System.err.println("The dog barks.");
}
public static void main(String[] args) {
Dog obj= new Dog();
obj.eat();
obj.bark();
} }
2 Design three classes A, B, and C such that class B inherits from A and class C inherits from B. Show how multilevel inheritance enables class C to access properties and methods of both A and B.
CODE:
class A {
void showA(){
System.out.println("This is class A.");
}
} class B extends A{
void showB(){
System.out.println("This class B will inherit from A.");
}
}
class C extends B{
void showC(){
System.out.println("This class C will inherit from B & A both.");
}
public static void main(String[]args){
C obj = new C();
obj.showA();
obj.showB();
obj.showC();
}
}
3 Create a parent class Parent and derive two child classes Child1 and Child2 from it. Illustrate how hierarchical inheritance allows both child classes to share common features of the parent class.
CODE:
class Parent{
void showParent(){
System.out.println("This is the Parent class.");
}
}
class Son extends Parent{
void showSon(){
System.out.println("This is the first child.");
}
}
class Daughter extends Parent{
void showDaughter(){
System.out.println("This is the second child.");
}
public static void main(String[]args){
Son obj1=new Son();
obj1.showParent();
obj1.showSon();
Daughter obj2= new Daughter();
obj2.showParent();
obj2.showDaughter();
}
}
4 Create a class that contains multiple methods named add() with different parameter lists. Demonstrate how method overloading achieves compile-time polymorphism by selecting the appropriate method based on arguments.
CODE:
class Mathematics{
int add(int a, int b){
return a+b;
}
double add(double a,double b){
return a+b;
}
int add(int a, int b, int c){
return a+b+c;
}
public static void main(String[] args){
Mathematics obj = new Mathematics();
System.out.println(obj.add(12,22));
System.out.println(obj.add(33.9,9.0));
System.out.println(obj.add(44,3,22));
}
}
5 Define a method in a parent class and override the same method in a child class. Demonstrate runtime polymorphism by calling the overridden method using a parent class reference.
CODE:
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}
class Dogs extends Animal {
@Override
void sound() {
System.out.println("Dog is barking.");
}
public static void main(String[] args) {
Animal obj = new Dogs();
obj.sound();
}
}
6 Create an abstract class Shape with an abstract method draw(). Implement this method in a subclass and demonstrate how abstraction hides implementation details.
CODE:
abstract class Shape{
abstract void draw();
}
class Circle extends Shape{
void draw(){
System.out.println("Draw a circle");
}
public static void main(String[]args){
Shape obj = new Circle();
obj.draw();
}
}
7 Create a class with private data members and provide public getter and setter methods to access them. Demonstrate how encapsulation ensures data hiding and controlled access.
CODE:
class Student{
private int age;
private String name;
public int getAge(){
return age;
}
public void setAge(int age){
this.age=age;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public static void main(String[]args){
Student obj =new Student();
obj.setAge(21);
obj.setName("Anuja");
System.out.println("Age:"+ obj.getAge());
System.out.println("Name:"+ obj.getName());
}}
8 Create a class that includes both a default constructor and a parameterized constructor. Show how constructors are used to initialize objects in different ways.
CODE:
class Students{
int age;
String name;
Students(){
age=18;
name="Default";
}
Students(int a,String n){
age = a;
name=n;
}
void display(){
System.out.println("Age: "+age + ", Name: "+ name);
}
public static void main(String[]args){
Students s1 = new Students();
s1.display();
Students s2 = new Students(21,"Anuja");
s2.display();
}
}
9 Create a class with multiple constructors and use this() to call one constructor from another. Demonstrate how constructor chaining helps in code reusability and proper initialization.
CODE:
class Studentss {int age;
String name; Studentss() {
this(18, "Default");
System.out.println("Default constructor called");
}
Studentss(int age, String name) {
this.age = age;
this.name = name;
System.out.println("Parameterized constructor called");
}
void display() {
System.out.println("Age: " + age + ", Name: " + name);
}
public static void main(String[] args) {
Studentss s1 = new Studentss();
s1.display();
}
}
10.Create a class that demonstrates the use of final, static, and abstract keywords. Illustrate how these modifiers affect variables, methods, and class behavior in Java.
CODE:
abstract class Shapes {
static String type = "Shapes";
final int sides = 0;
abstract void draw();
final void showType() {
System.out.println("This is a " + type);
}
static void info() {
System.out.println("Static method in abstract class");
}
}
class Circle extends Shapes {
void draw() {
System.out.println("Draw a circle");
}
public static void main(String[] args) {
Shapes.info();
Circle obj = new Circle();
obj.draw();
obj.showType();
System.out.println("Sides: " + obj.sides);
}
}