Java Assign2
Java Assign2
Div :- A
RollNo :- 2501064
Assignment 2
Interfaces, Packages and Exception Handling & The Collection Framework
1. Create a package ShapePkg. In this package, write an interface Shape having methods area() and
perimeter(). Create two classes Circle and Rectangle that implement this interface and override its
methods. Write another class with main() method to create objects of both classes, accept input
using Scanner, and display the results.
Code :-
//
package ShapePkg;
double area();
double perimeter();
} //
package ShapePkg;
[Link]=radius;
return [Link]*radius*radius;
}
return 2*[Link]*radius;
} //
double length;
double width;
[Link]=length;
[Link]=width;
return length*width;
return 2*(length+width);
//
package ShapePkg; import
[Link]; import
[Link]; import
[Link]; public
class TestShape
[Link]("-----Circle-----");
double rd=[Link]();
[Link]("-----Rectangle-----");
double l=[Link]();
double w=[Link]();
}
Output :-
2. Create a package MultiInterfacePkg. Define two interfaces Printable and Showable with methods
print() and show(). Create a class Document that implements both interfaces and provides method
definitions. Write a main class to create an object of Document and call both methods. Code :-
void print();
} //
interface Showable
void show();
} //
} //
package MultiInterfacePkg;
import MultiInterfacePkg.*;
[Link]();
[Link]();
Output :-
3. Create a package MathOperationsPkg. In this package, write a class Calculator with methods for
addition, subtraction, multiplication, and division. Create another class in a different package to
import this package and use its methods. Write the main method to perform operations based on
user input. Code :-
package MathOperationsPkg;
return a+b;
}
public double subtraction(double a,double b)
return a-b;
return a*b;
return a/b;
} //
class CalculatorDemo
Number :");
int a=[Link]();
[Link]("[Link]");
[Link]("[Link]");
[Link]("[Link]"); [Link]("Enter
switch(ch)
case 1:
[Link]("Result :"+[Link](a,b));
break;
case 2:
[Link]("Result :"+[Link](a,b));
break;
case 3:
[Link]("Result :"+[Link](a,b));
break;
case 4:
[Link]("Result :"+[Link](a,b));
break;
default:
[Link]("Invalid Choice!");
[Link]();
Output :-
4. Create a package StudentPkg. Define a class Student with variables having different access
modifiers (public, protected, default). Create another package and write a class to access these
variables. Write a main method to demonstrate which members are accessible and which are not.
Code :- package StudentPkg; public class Student
age=20;
String course="MCA";
} //
package StudentPkg;
class TestStudent
[Link]("Name (public):"+[Link]);
[Link]("Age (protected):"+[Link]);
[Link]("Course (default):"+[Link]);
}}
Output :-
5. Create a package UtilityPkg. Write a class StringUtility with methods reverse() and toUpperCase().
Create another class that imports this package using both explicit import and wildcard import. Write
a main method to call these methods and display output. Code :- package UtilityPkg; public class
StringUtility
String rev="";
for(int i=[Link]()-1;i>=0;i--)
rev+=[Link](i);
return rev;
return [Link]();
//
package UtilityPkg;
import UtilityPkg.*;
import [Link].*;
String str=[Link]();
[Link]("Reversed String :"+[Link](str));
Output :-
6. Create a package StudentDataPkg. Write a class Student to accept name, roll number, and marks
of 3 subjects using Scanner. Calculate total and average marks. Write a main class to create object
and display student details. Code :- package StudentDataPkg;
class StudentData
rollno; double
m1,m2,m3;
double total,average;
rollno=[Link]();
name=[Link]();
m1=[Link]();
m2=[Link](); m3=[Link]();
}
public void calculate()
total=m1+m2+m3;
average=total/3;
[Link]("Student Details");
[Link]("Roll No :"+rollno);
[Link]("Name :"+name);
package StudentDataPkg;
class StudentTest
[Link]();
[Link](); [Link]();
Output :-
7. Create a package ExceptionPkg. Write a class Division to perform division of two numbers. Handle
ArithmeticException using try-catch and use finally block to display a message. Write a main class to
test the program with user input. Code :- package ExceptionPkg;
try
[Link]("Result :"+result);
catch(ArithmeticException ae)
finally
}
} //
ExceptionPkg.*;
class TestDivision
Number :");
int n1=[Link]();
int n2=[Link]();
[Link](n1,n2);
Output :-
8. Create a package AgePkg. Write a class AgeValidator with a method checkAge(int age) that throws
an exception if age is less than 18 using throw. Use throws in method declaration. Write a main class
to call this method and handle the exception. Code :- package AgePkg; public class AgeValidator
{
public void checkAge(int age) throws Exception
if(age<18)
} //
package AgePkg;
int age=[Link]();
try
[Link](age);
catch(Exception e)
[Link]("Exception :"+[Link]());
Output :-
9. Create a package EmployeePkg. Define a user-defined exception class InvalidSalaryException.
Write a class Employee that throws this exception if salary is below a given limit. Write a main class
to accept salary input and handle the exception with a proper message. Code :- package
EmployeePkg;
super(msg);
//
class Employee
double salary;
if(salary<min_salary)
else
[Link]=salary;
[Link]("Salary Accepted :"+salary);
} //
package EmployeePkg;
import [Link].*;
class TestEmployee
double salary=[Link]();
try
[Link](salary);
catch(InvalidSalaryException ee)
[Link]("Exception :"+[Link]());
Output :-
10. Create a package ArrayListPkg. In this package, write a class Student with attributes id, name, and
marks. Create another class StudentManager that uses ArrayList to store multiple student objects.
Include methods to add, remove, search, and display students. Write a main class to perform all
operations using user input and display results. Code :- package ArrayListPkg; public class Student
int id;
String name;
double marks;
super();
= name; [Link]
= marks;
[Link]; public
class StudentManager
[Link](s);
[Link]("Student Added");
boolean found=false;
for(Student s:a)
if([Link]==id)
[Link](s);
[Link]("Student Removed..");
found=true;
break;
if(!found)
boolean found=false;
for(Student s:a)
if([Link]==id)
break;
if(!found)
if([Link]())
else
for(Student s:a)
} //
package ArrayListPkg;
import ArrayListPkg.*;
class StudentMain
{
public static void main(String[] args)
int ch;
do {
[Link]("1:Add Student");
[Link]("2:Remove Student");
[Link]("3:Search Student");
[Link]("4:Display All");
[Link]("5:Exit");
ch=[Link]();
switch(ch)
case 1:
[Link]("Enter Id :");
int id=[Link]();
double marks=[Link]();
break;
case 2:
[Link]([Link]());
break;
case 3:
[Link]([Link]());
break;
case 4:
[Link]();
break;
case 5:
[Link]("Exit");
break;
default:
[Link]("Invalid Choice...");
while(ch!=5);
Output :-
11. Create a package ArrayListSortPkg. Write a class Employee with attributes id, name, and salary.
Use ArrayList to store employee objects and implement sorting based on salary using Comparator.
Also filter employees with salary above a given value. Write a main class to demonstrate sorting and
filtering operations.
Code :- package
ArrayListSortPkg; public
class Employee
[Link] = id;
[Link] = name;
[Link] = salary;
} //
package ArrayListSortPkg;
[Link]; import
[Link];
[Link](e);
[Link](list,new Comparator<Employee>()
{ @Override
public int compare(Employee e1, Employee e2) { return
[Link]([Link], [Link]);
});
for(Employee e:list)
if([Link] >limit)
[Link]();
for(Employee e:list)
[Link]();
} //
package ArrayListSortPkg;
EmployeeMain
{
int n=[Link]();
for(int i=0;i<n;i++)
[Link]("Employee Id :");
int id=[Link]();
double Salary=[Link]();
[Link]("\n-----Before Sorting-----");
[Link]();
[Link]();
[Link]("\n-----After Sorting-----");
[Link]();
[Link](limit);
}
Output :-
12. Create a package LinkedListPkg. Write a class Task with attributes taskId and taskName. Create a
class TaskManager that uses LinkedList to manage tasks. Implement methods to add tasks at
beginning/end, remove tasks, and display tasks. Write a main class to demonstrate all operations
using user input. Code :- package LinkedListPkg; public class Task
int taskId;
String taskName;
super();
[Link] = taskId;
[Link] = taskName;
}
public void display()
} //
[Link]; public
class TaskManager
[Link](t);
[Link](t);
boolean found=false;
for(Task t:list)
if([Link]==taskId)
{
[Link](t);
[Link]("Task removed..");
found=true;
break;
if(!found)
{ if([Link]())
else
for(Task t:list)
[Link]();
} //
LinkedListPkg.*; import
[Link]; public class
TaskMain
int ch;
do {
[Link]("[Link] Task");
[Link]("[Link] Task");
[Link]("[Link]");
ch=[Link]();
switch(ch)
case 1:
int id1=[Link]();
String name1=[Link]();
break;
case 2:
int id2=[Link]();
String name2=[Link]();
[Link](new Task(id2, name2));
break;
case 3:
int id=[Link]();
[Link](id);
break;
case 4:
[Link]();
break;
case 5:
[Link]("Exit..");
break;
default:
[Link]("Invalid Choice..");
while(ch!=5);
Output :-
13. Create a package QueuePkg. Write a class QueueDemo that uses LinkedList to simulate queue
operations like enqueue, dequeue, and peek. Handle underflow condition using exception
handling. Write a main class to test queue operations. Code :-
package QueuePkg;
import [Link];
{
[Link](data);
try
if([Link]())
int removed=[Link]();
[Link]("Dequeued :"+removed);
catch(Exception e) {
[Link]([Link]());
{ try
if([Link]())
catch(Exception e)
{
[Link]([Link]());
if([Link]())
[Link]("Queue is empty.");
else
[Link]("Queue :"+queue);
} //
import [Link];
int ch;
do
{
[Link]("1:Enqueue.");
[Link]("2:Dequeue.");
[Link]("3:Peek");
[Link]("4:Display.");
[Link]("5:Exit.");
ch=[Link]();
switch(ch)
case 1:
int data=[Link]();
[Link](data);
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
[Link]();
break;
case 5:
[Link]("Exit");
break;
default:
[Link]("Invalid Choice!");
}
}while(ch!=5);
Output :-
14. Create a package VectorPkg. Write a class Product with attributes id, name, and price. Use Vector
to store product objects and demonstrate thread-safe operations by adding and removing elements.
Write a main class to perform operations and display results. Code :- package VectorPkg; public class
Product
{
int id;
super();
[Link] = id;
[Link] = name;
[Link] = price;
} //
package VectorPkg;
[Link](p);
[Link]("Product Added..");
if([Link]==id)
{
[Link](p);
found=true;
[Link]("Product removed..");
break;
if(!found)
if([Link]())
else
for(Product p:v)
[Link]();
//
package VectorPkg;
import [Link];
import VectorPkg.*; public
class TestProduct {
int ch;
do
[Link]("1:Add Product");
[Link]("2:Remove product");
[Link]("3:Display product");
[Link]("4:Exit");
ch=[Link]();
switch (ch) {
case 1:
int id = [Link]();
[Link]();
= [Link](); [Link](new
case 2:
[Link]([Link]());
break;
case 3:
[Link]();
break;
case 4:
[Link]("Exiting...");
break;
default:
[Link]("Invalid Choice.");
while(ch!=4);
Output :-
15. Create a package StackPkg. Write a class StackDemo that uses Stack to evaluate a postfix
expression. Implement push, pop, and peek operations and handle empty stack using exception
handling. Write a main class to input expression and display result. Code :- package StackPkg;
import [Link]; public class StackDemo
[Link](value);
{
if([Link]())
return [Link]();
try
for(int i=0;i<[Link]();i++)
char ch=[Link](i);
if([Link](ch))
push(ch-'0');
else
int b=pop();
int a=pop();
switch(ch)
case '+':
push(a+b);
break;
case '-':
push(a-b);
break;
case '*':
push(a*b);
break;
case '/':
push(a/b);
break;
default:
return pop();
catch(Exception e)
[Link]("Error :"+[Link]());
return -1;
} //
[Link]; public
class TestStack
String exp=[Link]();
if(result!=-1)
[Link]("Result :"+result);
Output :-
16. Create a package HashSetPkg. Write a class Course with attributes courseId and courseName. Use
HashSet to store course objects and ensure no duplicate entries are allowed. Override equals() and
hashCode() methods. Write a main class to add and display unique courses. Code :- package
HashSetPkg;
int cid;
String cname;
super(); [Link]
= cid;
[Link] = cname;
@Override
@Override
if (this == obj)
return true;
return false;
} //
package HashSetPkg;
class TestCourse {
{
Scanner sc=new Scanner([Link]);
int n=[Link]();
for(int i=0;i<n;i++)
[Link]("Course Id :");
int id=[Link]();
String name=[Link]();
if([Link](c))
[Link]("course added..");
else
[Link]("\n--------Unique Course---------");
for(Course c:set)
{
[Link]();
Output :-
17. Create a package LinkedHashSetPkg. Write a class Book with attributes bookId and bookName.
Use LinkedHashSet to store book objects and maintain insertion order while avoiding duplicates.
Write a main class to demonstrate insertion and display order. Code :- package
LinkedHashSetPkg;
import [Link];
int bookid;
String bookName;
super(); [Link]
= bookid;
[Link] = bookName;
}
@Override
return bookid+[Link]();
@Override
if (this == obj)
return true;
return false;
} //
[Link]; import
TestBook {
public static void main(String[] args)
int n=[Link]();
for(int i=0;i<n;i++)
int id=[Link]();
String name=[Link]();
if([Link](b))
[Link]("Book Added..");
else
{
[Link]();
Output :-
18. Create a package TreeSetPkg. Write a class Player with attributes id and score. Use TreeSet to
store player objects in sorted order based on score using Comparable. Write a main class to add
players and display sorted output. Code :- package TreeSetPkg; public class Player implements
Comparable<Player>
int id;
int score;
super();
[Link] = id;
[Link] = score; }
@Override
{
return [Link];
} //
[Link]; import
[Link];
int n=[Link]();
for(int i=0;i<n;i++)
id=[Link]();
[Link]("Score :");
int score=[Link]();
for(Player p:set)
[Link]();
Output :-
19. Create a package TreeMapPkg. Write a class Library that uses TreeMap to store book ID and book
name as key-value pairs. Implement operations like add, remove, search, and display entries in
sorted order of keys. Write a main class to perform all operations using user input.
Code :-
package TreeMapPkg;
class Library
{
TreeMap<Integer,String> map=new TreeMap<Integer, String>();
[Link](id, name);
[Link]("Book added..");
if([Link](id))
[Link](id);
[Link]("Book removed..");
else
if([Link](id))
else
if([Link]())
else
for(Integer id:[Link]())
} //
package TreeMapPkg;
int ch;
do
[Link]("1:Add Book");
[Link]("2:Remove Book");
[Link]("3:Search Book");
[Link]("4:Display Books");
[Link]("5:Exit");
ch=[Link]();
switch(ch)
case 1:
int id=[Link]();
String name=[Link]();
[Link](id, name);
break;
case 2:
[Link]([Link]());
break;
case 3:
[Link]([Link]());
break;
case 4:
[Link]();
break;
case 5:
[Link]("Exit");
break;
default:
[Link]("Invalid choice");
}while(ch!=5);
Output :-