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

Merged Assignment

Uploaded by

nandakumar102005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Merged Assignment

Uploaded by

nandakumar102005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 102

Sri Sivasubramaniya Nadar College of Engineering

Department of Computer Science and Engineering


B.E Computer Science & Engineering
2023-2027

UCS2313 – Object Oriented Programming Lab

Exercise 1a: Basic Java Programs

1. Write a Java program to check whether the given number is odd or even.

Aim:

To write a Java program to check whether the given number is odd or even.

Code:

import

java.util.Scanner; class

oddoreven {

public static void main(String args[]){

Scanner s = new

Scanner(System.in);

System.out.print("Enter the

number:"); int n=s.nextInt();

if(n%2==0)

System.out.println("Even");

else

System.out.println("Odd");

Output:

1
2.Write a Java program to find the factorial of the given number.

Aim:

To write a Java program to find the factorial of the given number.

Code:

import java.util.Scanner;

class fact{

public static void main(String args[]){

Scanner s = new Scanner(System.in);

int fac=1;

System.out.print("Enter the number:");

int n=s.nextInt();

for (int i=1;i<=n;i++){

fac=fac*i;

System.out.print("Factorial of " + n + " is " + fac);

Output:

3. Write a Java program to find the sum of first ‘n’ Fibonacci numbers.

Aim:

To write a Java program to find the sum of first ‘n’ Fibonacci numbers.

Code:

import java.util.Scanner;

class fib_sum{

public static void main(String args[]){

Scanner s = new Scanner(System.in);

2
System.out.print("Enter the number:");

int n= s.nextInt();

int f1=0,f2=1,fib=0,sum=0;

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

sum+=f1

fib=f1+f2;

f1=f2;

f2=fib;

System.out.print("The sum of first " + n +" fibonacci number is "+sum);

Output:

4. Write a Java program to find whether the given number is an Armstrong number or not.

Aim:

To write a Java program to find whether the given number is an Armstrong number or not.

Code:

import java.util.Scanner;

import java.lang.Math;

class armstrong{

public static void main(String args[]){

Scanner s =new Scanner(System.in);

System.out.print("Enter the number:");

int n = s.nextInt();

int t1=n,t2=n,arm=0,c=0;
3
while(t1!=0){

t1=t1/10; c+

+;

while(t2!=0){

arm+=Math.pow((t2%10),c); t2=t2/10;

if(arm==n)

System.out.print("Armstrong number");

else

System.out.print("Not an Armstrong number");

Output:

5. Write a Java program to create a class named ‘Student’ with the following
attributes: name, id, dept, and the marks of three subjects as data members. Write a
function to take the inputs, calculate the average marks of each student, to display the
details and to search for a student based on his/her name or id.

Aim:

To write a Java program to create a class named ‘Student’ with the following attributes:
name, id, dept, and the marks of three subjects as data members and to write a function to take
the inputs, calculate the average marks of each student, to display the details and to search for a
student based on his/her name or id.

4
Code:

import java.util.Scanner;

class Student{

String name,dept;

int id;
float m1,m2,m3,avg;

public Student(String name, String dept, int id, float m1, float m2, float m3, float avg) { this.name

= name;

this.dept = dept;

this.id = id; this.m1

= m1; this.m2 =

m2; this.m3 = m3;

this.avg = avg;

public static void name_search(Student[] students,int n,String nam){

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

if(nam.equals(students[i].name)){

System.out.println("Name:"+students[i].name);

System.out.println("Dept:"+students[i].dept);

System.out.println("Id:"+students[i].id);

System.out.println("Mark-1:"+students[i].m1);

System.out.println("Mark-2:"+students[i].m2);

System.out.println("Mark-3:"+students[i].m3);

System.out.println("Average:"+students[i].avg);

return;

System.out.println("Student name not found.");

5
}

public static void id_search(Student[] students,int n,int id){

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

if(id==students[i].id){

System.out.println("Name:"+students[i].name);

System.out.println("Dept:"+students[i].dept);

System.out.println("Id:"+students[i].id);

System.out.println("Mark-1:"+students[i].m1);

System.out.println("Mark-2:"+students[i].m2);

System.out.println("Mark-3:"+students[i].m3);

System.out.println("Average:"+students[i].avg);

return;

System.out.println("Student id not found.");

public static void display(Student[] students,int n){

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

System.out.println("Student-"+(i+1)+" details:");

System.out.println("Name:"+students[i].name);

System.out.println("Dept:"+students[i].dept);

System.out.println("Id:"+students[i].id);

System.out.println("Mark-1:"+students[i].m1);

System.out.println("Mark-2:"+students[i].m2);

System.out.println("Mark-3:"+students[i].m3);

System.out.println("Average:"+students[i].avg);

6
public static void get_input(Scanner s,Student[] students,int i){

s.nextLine();

System.out.print("Enter the name of student:");

String name=s.nextLine();

System.out.print("Enter the department of student:"); String

dept=s.nextLine();

System.out.print("Enter the id of student:"); int

id=s.nextInt();

System.out.print("Enter the mark-1 of student:");

float m1=s.nextFloat();

System.out.print("Enter the mark-2 of student:");

float m2=s.nextFloat();

System.out.print("Enter the mark-3 of student:");

float m3=s.nextFloat();

float avg=avg_cal( m1,m2,m3);

students[i]= new Student(name, dept,id,m1,m2,m3,avg);

public static float avg_cal(float m1,float m2,float m3){

float avg=(m1+m2+m3)/3;
return avg;

public static void main(String[] args){

7
Scanner s = new Scanner(System.in);

System.out.print("Enter the number of students:");

int n=s.nextInt();

Student[] students = new Student[n];

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

System.out.println("Enter the student-"+(i+1)+" details:");

get_input(s,students,i);

display(students,n);

System.out.print("Enter 1-name or 2-id to search student details:"); int

ch = s.nextInt();

s.nextLine();

if(ch==1){

System.out.print("Enter name to search student details:");

String nm = s.nextLine();
name_search(students,n,nm);

else if(ch==2){

System.out.print("Enter id to search student details:"); int

ids = s.nextInt();

id_search(students,n,ids);

else{

System.out.println("Invalid choice");

8
Output:

9
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027

UCS2313 – Object Oriented Programming Lab


Exercise 1b: Classes, Objects and
Constructors

1. Develop a Java application to generate an electricity bill based on the slabs given
below. Create a class with the following members: Consumer no., consumer name,
previous month reading, current month reading, and type of EB connection (i.e
domestic or commercial).
Compute the bill amount using the following tariff.

If the type of the EB connection is domestic, calculate the amount to be paid as follows:

●First 100 units - Rs. 1 per unit

●101-200 units - Rs. 2.50 per unit

●201 -500 units - Rs. 4 per unit

●501 units - Rs. 6 per unit

If the type of the EB connection is commercial, calculate the amount to be paid as follows:

●First 100 units - Rs. 2 per unit

●101-200 units - Rs. 4.50 per unit

●201 -500 units - Rs. 6 per unit

●501 units - Rs. 7 per unit

Your program should take as input the following details for a consumer: Consumer no.,
consumer name, previous month reading, current month reading, and type of EB
connection (i.e domestic or commercial), and display the bill for the current month. The
bill should include the details about the consumer as well as the amount to be paid.

Aim:

To develop a Java application to generate an electricity bill based on the slabs given below.
Create a class with the following members: Consumer no., consumer name, previous month
reading, current month reading, and type of EB connection (i.e domestic or commercial).
Compute the bill amount

Code:

import java.util.Scanner;

class eb{

String Cons_name,Cons_type;

int Cons_no;

10
float amt,pre_reading,cur_reading,unit;

public static void get_cons_input(Scanner s,eb consumer){

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

consumer.Cons_name = s.nextLine();

System.out.print("Enter the consumer type(Domestic or Commercial):");

consumer.Cons_type = s.nextLine();

System.out.print("Enter the consumer no.:");

consumer.Cons_no = s.nextInt();

System.out.print("Enter the previous month reading:");

consumer.pre_reading = s.nextFloat();

System.out.print("Enter the current month reading:");

consumer.cur_reading = s.nextFloat();

consumer.unit=consumer.cur_reading - consumer.pre_reading;

public static void display(eb consumer){

System.out.println("Consumer no.:"+consumer.Cons_no);

System.out.println("Consumer name:"+consumer.Cons_name);

System.out.println("Consumer type:"+consumer.Cons_type);

System.out.println("Previous Month reading:"+consumer.pre_reading);

System.out.println("Current Month reading:"+consumer.cur_reading);

System.out.println("Total units:"+consumer.unit); System.out.println("Total

amount:"+consumer.amt);
}

public static void eb_amt_cal(eb consumer){

11
float amt=0;

if(consumer.Cons_type.equals("Domestic")){

if(consumer.unit<=100){

amt=consumer.unit*1f;
}

else if(101<=consumer.unit && consumer.unit<=200){

amt=100+(consumer.unit-100)*2.5f;

else if(201<=consumer.unit && consumer.unit<=500){

amt=100+(100*2.5f)+(consumer.unit-200)*4f;

else{

amt=100+(100*2.5f)+(300*4f)+(consumer.unit-500)*6f;

else if(consumer.Cons_type.equals("Commercial")){

if(consumer.unit<=100){
amt=consumer.unit*2f;

else if(101<=consumer.unit && consumer.unit<=200){

amt=100+(consumer.unit-100)*4.50f;

else if(201<=consumer.unit && consumer.unit<=500){

amt=100+(100*4.5f)+(consumer.unit-200)*6f;

else{

amt=100+(100*4.5f)+(300*6f)+(consumer.unit-500)*7f;

12
consumer.amt=amt;

public static void main(String args[]){

Scanner s =new

Scanner(System.in);

eb consumer =new eb();

get_cons_input(s,consumer);

eb_amt_cal(consumer);

display(consumer);

Output:

13
2. Write a Java program to create a class named ‘Student’ with the following
attributes: name, id, dept, and the marks of three subjects as data members. Write a
function that takes as input the details of ‘n’ students, calculates the average marks of
each student, and displays the details for each student. The program should also enable
searching for a student based on his/her name or id. Use method overloading to enable
search using id and dept.

Aim:

To write a Java program to create a class named ‘Student’ with the following attributes:
name, id, dept, and the marks of three subjects as data members. Write a function that takes as
input the details of ‘n’ students, calculates the average marks of each student, and displays the
details for each student. The program should also enable searching for a student based on
his/her name or id. Use method overloading to enable search using id and dept.

Code:

import java.util.Scanner;

class Student{

String name,dept;

int id;

float m1,m2,m3,avg;

public Student(String name, String dept, int id, float m1, float m2, float m3, float avg) { this.name

= name;

this.dept = dept;

this.id = id; this.m1

= m1; this.m2 =

m2; this.m3 = m3;

this.avg = avg;

public static void search(Student[] students,int n,String nam){

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

if(nam.equals(students[i].name)){

System.out.println("Name:"+students[i].name);

System.out.println("Dept:"+students[i].dept);
14
System.out.println("Id:"+students[i].id);

System.out.println("Mark-1:"+students[i].m1);

System.out.println("Mark-2:"+students[i].m2);

System.out.println("Mark-3:"+students[i].m3);

System.out.println("Average:"+students[i].avg);

return;

System.out.println("Student name not found.");

public static void search(Student[] students,int n,int id){ for(int

i=0;i<n;i++){

if(id==students[i].id){

System.out.println("Name:"+students[i].name);

System.out.println("Dept:"+students[i].dept);

System.out.println("Id:"+students[i].id);

System.out.println("Mark-1:"+students[i].m1);

System.out.println("Mark-2:"+students[i].m2);

System.out.println("Mark-3:"+students[i].m3);

System.out.println("Average:"+students[i].avg);

return;

System.out.println("Student id not found.");

public static void display(Student[] students,int n){

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

System.out.println("Student-"+(i+1)+" details:");

System.out.println("Name:"+students[i].name);

System.out.println("Dept:"+students[i].dept);
15
System.out.println("Id:"+students[i].id);

System.out.println("Mark-1:"+students[i].m1);

System.out.println("Mark-2:"+students[i].m2);

System.out.println("Mark-3:"+students[i].m3);

System.out.println("Average:"+students[i].avg);

public static void get_input(Scanner s,Student[] students,int i){

s.nextLine();

System.out.print("Enter the name of student:");

String name=s.nextLine();

System.out.print("Enter the department of student:"); String

dept=s.nextLine();

System.out.print("Enter the id of student:"); int

id=s.nextInt();

System.out.print("Enter the mark-1 of student:");

float m1=s.nextFloat();

System.out.print("Enter the mark-2 of student:");

float m2=s.nextFloat();

System.out.print("Enter the mark-3 of student:");

float m3=s.nextFloat();

float avg=avg_cal( m1,m2,m3);


students[i]= new Student(name, dept,id,m1,m2,m3,avg);

public static float avg_cal(float m1,float m2,float m3){

float avg=(m1+m2+m3)/3;

return avg;

16
}

public static void main(String[] args){

Scanner s = new Scanner(System.in);

System.out.print("Enter the number of students:");

int n=s.nextInt();

Student[] students = new Student[n];

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

System.out.println("Enter the student-"+(i+1)+" details:");

get_input(s,students,i);

display(students,n);

System.out.print("Enter 1-name or 2-id to search student details:"); int

ch = s.nextInt();

s.nextLine();

if(ch==1){

System.out.print("Enter name to search student details:");

String nm = s.nextLine();
search(students,n,nm);

else if(ch==2){

System.out.print("Enter id to search student details:"); int

ids = s.nextInt();
search(students,n,ids);

else{

System.out.println("Invalid choice");

17
}

Output:

18
3. Write a Java program to compute the gross and net pays of a set of employees in an
organization. Create a class named ‘Employee’ with name, ID, designation, years-of-
experience, basic-pay, DA, HRA, LIC, PF and no. of hours worked. Write functions to
calculate the gross pay and net pay, based on the details given in the table below. (CO1,
K3) Designation DA HRA Intern PF 2000 1000 Manager 40% of basic pay 10% of basic
pay 500 Trainee, Analyst, Software engineer, Team Lead 8% of basic pay 30% of basic
pay 10% of basic pay 8% of basic pay

●For the interns, compute the gross salary as follows, where hourly wage is fixed at
Rs.300 per
hour. Gross salary = worked hours * hourly wage + DA + HRA

●For the others, compute the gross salary as follows: Gross salary = Basic pay + DA +
HRA

●For everyone, compute the deductions and the net salary as follows: Deductions = LIC
premium amount (if opted) + PF Net salary = Gross salary - Deductions a. Calculate the
Payroll for ‘n’ employees and display the salary details for all employees. b. Prepare the
payslip for a particular employee, given the employee ID as input. c. If a particular
employee has completed 10 years of service, display that the employee is eligible for
promotion.

Aim:

To write a Java program to compute the gross and net pays of a set of employees in an
organization. Create a class named ‘Employee’ with name, ID, designation, years-of- experience,
basic-pay, DA, HRA, LIC, PF and no. of hours worked. Write functions to calculate the gross pay
and net pay, based on the details given in the table below.

Code:

import java.util.Scanner;

class Employee{

String name,design;

int id;

float yrs_of_exp,hrs_of_exp,bp,da,hra,lic,pf,no_hrs_wrk,gross,deduct,net;

public static void cal_gross_and_net(Employee[] emp,int i){

if(emp[i].design.equalsIgnoreCase("Intern")){

emp[i].gross=emp[i].hrs_of_exp*300f+emp[i].da+emp[i].hra;

emp[i].deduct=emp[i].lic+emp[i].pf;

emp[i].net=emp[i].gross-emp[i].deduct;

else if(emp[i].design.equalsIgnoreCase("Manager") ||

19
emp[i].design.equalsIgnoreCase("Trainee") || emp[i].design.equalsIgnoreCase("Analyst") ||
emp[i].design.equalsIgnoreCase("Software engineer")
||emp[i].design.equalsIgnoreCase("Team Lead")){

emp[i].gross=emp[i].bp+emp[i].da+emp[i].hra;

emp[i].deduct=emp[i].lic+emp[i].pf;

emp[i].net=emp[i].gross-emp[i].deduct;

public static void get_emp_input(Employee[] emp,int n,Scanner s){

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

emp[i] = new Employee();

System.out.print("\nEnter name of employee:");

emp[i].name = s.nextLine();

System.out.print("Enter designation of employee:");

emp[i].design = s.nextLine();

System.out.print("Enter id of employee:");

emp[i].id = s.nextInt();

if(emp[i].design.equalsIgnoreCase("Intern")){

System.out.print("Enter hours of experience of employee:");

emp[i].hrs_of_exp = s.nextFloat();

emp[i].bp = 0;

emp[i].da = 2000f;

emp[i].hra = 1000f;

emp[i].pf = 500f;

cal_gross_and_net(emp,i);

20
else{

System.out.print("Enter years of experience of employee:");

emp[i].yrs_of_exp = s.nextFloat();

System.out.print("Enter basic pay of employee:");

emp[i].bp = s.nextFloat();

if(emp[i].design.equalsIgnoreCase("Manager")){

emp[i].da = emp[i].bp*0.4f;

emp[i].hra = emp[i].bp*0.1f;

emp[i].pf = emp[i].bp*0.08f;

else if (emp[i].design.equalsIgnoreCase("Trainee") ||
emp[i].design.equalsIgnoreCase("Analyst") || emp[i].design.equalsIgnoreCase("Software
Engineer") || emp[i].design.equalsIgnoreCase("Team Lead")) {

emp[i].da = emp[i].bp * 0.3f;

emp[i].hra = emp[i].bp * 0.1f;

emp[i].pf = emp[i].bp * 0.08f;

s.nextLine();

cal_gross_and_net(emp,i);
}

public static void display(Employee[] emp, int n) {

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


System.out.println("\n==========================================");

System.out.println("\t\tPayslip");

System.out.println("==========================================");

System.out.println("Employee ID: " + emp[i].id);

System.out.println("Name: " + emp[i].name);

21
System.out.println("Designation: " + emp[i].design);

System.out.println("Gross Salary: " + emp[i].gross);

System.out.println("Deductions: " + emp[i].deduct);

System.out.println("Net Salary: " + emp[i].net);

System.out.println("==========================================\n");

public static void search(Employee[] emp,int n,int id){ for

(int i=0;i<n;i++){

if(emp[i].id==id){

System.out.println("\nEmployee ID: " + emp[i].id);

System.out.println("Name: " + emp[i].name);

System.out.println("Designation: " + emp[i].design);

System.out.println("Gross Salary: " + emp[i].gross);

System.out.println("Deductions: " + emp[i].deduct);

System.out.println("Net Salary: " + emp[i].net); return;

System.out.println("Employee ID not found");

public static void promotion(Employee[] emp,int n){ for

(int i=0;i<n;i++){

if(emp[i].yrs_of_exp>=10){ System.out.println("\

n==========================================");

System.out.print("This Employee Eligible to promotion."); search(emp,n,emp[i].id);

System.out.println("==========================================\n");

22
}

public static void main(String[] args){

Scanner s =new Scanner(System.in);

System.out.print("Enter the n number of employees:"); int

n =s.nextInt();

s.nextLine();

Employee[] emp = new Employee[n];

get_emp_input(emp,n,s);

display(emp,n);

System.out.print("Enter the employee ID to search:");

int ids =s.nextInt();


search(emp,n,ids);

promotion(emp,n);

23
Output:

24
Learning Outcomes:

●Understand the difference between classes and objects

●Create different objects of same class

●Examine the need of constructors

●Apply different types of constructors based on the need

25
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027

UCS2313 – Object Oriented Programming Lab

Exercise 2: Arrays and Strings

1. Write a Java program that takes as input ‘n’ elements, and searches for an element using
both
linear search and binary search.

Aim:

To write a Java program that takes as input ‘n’ elements, and searches for an element
using both linear search and binary search.

Code:

import java.util.Scanner;

class

lin_and_bin_search{

static void lin_search(int[] arr,int e1){

for(int i=0;i<arr.length;i++){
if(e1==arr[i]){

System.out.println("Element:" + arr[i] + " at index:"+i);

static int[] bin_sort(int[] arr){

int temp,n=arr.length; for(int

i=0;i<n-1;i++){

for(int j=i+1;j<n;j++){

if(arr[i]>arr[j]){

temp=arr[i];

arr[i]=arr[j];

arr[j]=temp;

26
}

}
return arr;

static void bin_search(int arr[],int e2){ int

st=0,fnl=arr.length,mid; while(st<=fnl){

mid=(st+fnl)/2;

if(arr[mid]==e2){

System.out.println("The element:" + e2 + " at index:" + mid);

break;
}

else if(arr[mid]<e2){

st=mid+1;

else if(arr[mid]>e2){

fnl=mid-1;

public static void main(String[] args){

Scanner scan =new

Scanner(System.in);

System.out.print("Enter the value n:"); int

n=scan.nextInt();

int[] arr = new int[n];

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

System.out.print("Enter "+ (i+1) +"-element:"); arr[i]=scan.nextInt();


}

System.out.print("Enter element to linear search:"); int

e1=scan.nextInt();

27
lin_search(arr,e1);

System.out.print("Enter element to binary search:"); int

e2=scan.nextInt();

arr=bin_sort(arr);

bin_search(arr,e2);

Output:

2. Write a Java program that takes as input two n X n matrices A and B, and displays:
a. A+B
b. A-B
c.A x B

Aim:

To write a Java program that takes as input two n X n matrices A and B, and displays
add,sub,multiply of the two matrices A and B.

Code:

import java.util.Scanner;

class matrix{

static void add_sub_mul(int[][] A ,int[][] B,int[][] Add_mat,int[][] Sub_mat,int[][] Mul_mat){ int

n=A.length;
28
for(int i=0;i<n;i++){

for(int j=0;j<n;j++){

Add_mat[i][j]=A[i][j]+B[i][j];

Sub_mat[i][j]=A[i][j]-B[i][j]; for

(int k=0;k<n; k++) {


Mul_mat[i][j]+=A[i][k]*B[k][j];

static void display(int[][] mat){

for(int i=0;i<mat.length;i++){

for(int j=0;j<mat.length;j++){

System.out.print(mat[i][j]+" ");
}

System.out.println();

static void get_input(int[][] mat,Scanner scan){ for(int

i=0;i<mat.length;i++){

for(int j=0;j<mat.length;j++){

mat[i][j]=scan.nextInt();

public static void main(String[] args){

Scanner scan =new

Scanner(System.in);
29
System.out.print("Enter the value n:"); int

n=scan.nextInt();

int[][] A = new int[n][n];

int[][] B = new int[n][n];

int[][] Add_mat = new int[n][n];

int[][] Sub_mat = new int[n][n];

int[][] Mul_mat = new int[n][n];

System.out.println("\nEnter elements for matrix A:");

get_input(A,scan);

System.out.println("\nEnter elements for matrix B:");

get_input(B,scan);

add_sub_mul(A, B, Add_mat, Sub_mat, Mul_mat);

System.out.println("\nAddition Matrix:");

display(Add_mat); System.out.println("\

nSubraction Matrix:"); display(Sub_mat);

System.out.println("\nMultiplication Matrix:");

display(Mul_mat);

30
Output:

3. Write a Java program that takes as input an English sentence and displays the longest
word in it. Also, print the index position of the first character of that word.

●Sample Input: Java is a programming language.

●Output: programming, 11

Aim:

To write a Java program that takes as input an English sentence and displays the longest
word in it. Also, print the index position of the first character of that word.

31
Code:

import java.util.Scanner;

class Largest_word{

public static void main(String[] args){

Scanner scan =new

Scanner(System.in);

System.out.print("Enter a Sentence:");

String sen=scan.nextLine();

String[] word = sen.split(" ");

int index=0,n=0;

String large=word[0];

for(String w:word){

if(large.length()<=w.length()){

large=w;
index=n;

n+=w.length()+1;

System.out.print("Largest word:"+large+"\nIts index:"+index);

Output:

4. Write a Java program that takes as input a string, and displays whether it is a
Palindrome or not.

Aim:

To write a Java program that takes as input a string, and displays whether it is a

32
Palindrome or not.

33
Code:

import java.util.Scanner;

class palindrome{

public static void main(String[] args){

Scanner scan =new

Scanner(System.in);

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

String str=scan.nextLine();

int i=0,f=str.length()-1,p=1;

while(i<f){

if(str.charAt(i)!=str.charAt(f)){ p=0;

break;

} i+

+;

f--;

if(p==1){

System.out.println("The string is a palindrome.");

else{

System.out.println("The string is not a palindrome.");

Output:

34
5. A Pangram is a sentence in which all the letters of a given alphabet occur at least once.
Write a Java program that displays if a given sentence is a Pangram or not. Also, display
the number of occurrences of each letter in the sentence.

Aim:

To write a Java program that displays if a given sentence is a Pangram or not. Also,
display the number of occurrences of each letter in the sentence.

Code:

import java.util.Scanner;

class Pangram{

public static void main(String[] args){

Scanner scan =new

Scanner(System.in);

System.out.print("Enter a sentence:");

String str=scan.nextLine();

str=str.toUpperCase();

int[] alpha=new int[26]; for(int

i=0;i<str.length();i++){

char j = str.charAt(i); if

(j >= 'A' && j <= 'Z') {

int z = j - 'A';

alpha[z] += 1;
}

int f=1;

for(int i=0;i<alpha.length;i++){

if(alpha[i]<1){
f=0;

break;

35
if(f==1){

System.out.println("Yes, the given sentence is pangram.");

else{

System.out.println("The sentence is not a pangram.");

for(int i=0;i<alpha.length;i++){

char c=(char)(i+'A');

System.out.println(c+":"+alpha[i]);

Output:

36
Learning Objectives:

1.Understanding Basic Search Algorithms.

2.Matrix Operations.

3.String Manipulation and Analysis.

4.Problem Solving and Logical Thinking.

5.Implementing Algorithmic Solutions.

Learning Outcomes:

1.Apply Search Algorithms.

2.Perform Matrix Operations.

3.String Manipulation Skills.

4.Identifying Palindromes and Pangrams.

37
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027

UCS2313 – Object Oriented Programming Lab


Exercise 3: Inheritance

Learning Objective:

● To test the following inheritance types: single-level, multi-level and


hierarchical inheritance.
● To test the scope of private and protected variables, constructors in
inheritedclass hierarchy.

Learning Outcomes:
● Need of inheritance and its implementation in Java
● Type of inheritance
● Working of constructors in inherited class
● Accessing inherited class through base class reference
● Method overloading and overriding in inheritance

1. Create a class hierarchy for the classes defined below. The notations to
denote the access specifiers for the attributes and methods are as follows:
(CO2 - K3)

- Private members
+ Public members
# Protected members
~ Default (Package private)

38
Class Person:
Person
-aadhaar:int
-name:String
-address:String
-gender:char

+Person(aadhaar,name,address,gender)
+getName():String
+getAddress():String
+setAddress(address):void
+getGender():char

A sub-class Student of class Person:

Student
-program:String
-year:int
-totalmark:float

+Student(aadhaar,name,address,gender,program,year,total)
+getProgram():String
+getYear():int
+setYear(year):void
+getTotal():float
+setTotal(tot):void
+calGPA():float

A sub-class Faculty of class Person:

Faculty
-designation:String
-department:String
-basicpay:float

+Faculty(aadhaar,name,address,gender,designation,dept,pay)
+getDesig():String
+setDesig(desig):void
+setBasic(basic):void
+getBasic():float
+calSalary():float

39
Note the following:

● Person -> Student (or) Person -> Faculty is a single-level inheritance.


● The type of the entire class hierarchy (Person -> Student , Person ->
Faculty)is hierarchical Inheritance.
● Note the use of constructors at all levels of class hierarchy.

Things to do:

● Draw the class diagram of the above class hierarchy.


● Write a test driver called TestInheritanceto test all the public methodsthat
display the student and the faculty details.
● Use the following to calculate the Net Salary of a faculty:
Gross salary = Basic pay + DA as 60% of basic + HRA as 10% of basic
Deductions = Medical Insurance as 8.5% of basic + PF as 8% of basic
Net salary = Gross salary – Deductions

Aim:

To write a java program using for Person -> Student (or) Person -> Faculty is a
single-level inheritance.

Source code:

import java.util.Scanner;
class Person{
private int aadhaar;
private String name;
private String address;
private char gender;
public Person(int aadhaar,String name,String address,char gender){
this.aadhaar=aadhaar;
this.name=name;
setAddress(address);
this.gender=gender;
}
public String getName(){ return
name;
}
public String getAddress(){ return
address;
}
public void setAddress(String address){
this.address=address;
}
public char getGender(){ return
gender;
40
}
}
class Student extends
Person{ private String
program; private int year;
private float totalmark;
public Student(int aadhaar,String name,String address,char gender,String program,int
year,float total){
super(aadhaar,name,address,gender);
this.program=program; setYear(year);
setTotal(total);
}
public String getProgram(){ return
program;
}
public int getYear(){ return
year;
}
public void setYear(int year){
this.year=year;
}
public float getTotal(){ return
totalmark;
}
public void setTotal(float tot){ this.totalmark=tot;
}
public float calGPA(){ return
totalmark/10;
}
}

class Faculty extends


Person{ private String
designation; private String
department; private float
basicpay;
public Faculty(int aadhaar,String name,String address,char gender,String
designation,String dept,float pay){
super(aadhaar,name,address,gender);
setDesig(designation); this.department=dept;
setBasic(pay);
}
public String getDesig(){ return
41
designation;
}
public void setDesig(String desig){
this.designation=desig;
}
public void setBasic(float basic){
this.basicpay=basic;
}
public float getBasic(){ return
basicpay;
}
public float calSalary(){
float gross_salary = basicpay + basicpay*0.6f + basicpay*0.1f; float
deduct = basicpay*0.085f + basicpay*0.08f;
float net_salary = gross_salary - deduct;
return net_salary;
}
}

public class testInheritance{


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

System.out.println("Enter Student details:"); System.out.print("Enter


name:");
String name = scan.nextLine();

System.out.print("Enter aadhaar:"); int


aadhaar = scan.nextInt();
scan.nextLine();

System.out.print("Enter gender:"); char


gender = scan.next().charAt(0);
scan.nextLine();

System.out.print("Enter address:");
String address = scan.nextLine();

System.out.print("Enter program:");
String program = scan.nextLine();

System.out.print("Enter year:"); int


year = scan.nextInt();

System.out.print("Enter total mark:"); float


totalmark = scan.nextFloat();

42
Student stud = new Student(aadhaar, name, address, gender, program, year,
totalmark);

System.out.println("\nName:"+stud.getName());
System.out.println("Gender:"+stud.getGender());
System.out.println("Aadhaar:"+aadhaar);
System.out.println("Address:"+stud.getAddress());
System.out.println("Program:"+stud.getProgram());
System.out.println("Year:"+stud.getYear()); System.out.println("Total
mark:"+stud.getTotal()); System.out.println("GPA:"+stud.calGPA());

System.out.println("\nEnter Faculty details:"); scan.nextLine();


System.out.print("Enter name:"); String
fac_name = scan.nextLine();

System.out.print("Enter aadhaar:"); int


fac_aadhaar = scan.nextInt();
scan.nextLine();

System.out.print("Enter gender:");
char fac_gender = scan.next().charAt(0);
scan.nextLine();

System.out.print("Enter address:"); String


fac_address = scan.nextLine();

System.out.print("Enter designation:");
String designation = scan.nextLine();

System.out.print("Enter department:");
String dept = scan.nextLine();

System.out.print("Enter basic pay:"); float pay


= scan.nextFloat();

Faculty fac = new Faculty(fac_aadhaar, fac_name, fac_address, fac_gender,


designation, dept, pay);

System.out.println("\nName:"+fac.getName());
System.out.println("Gender:"+fac.getGender());
System.out.println("Aadhaar:"+fac_aadhaar);
System.out.println("Address:"+fac.getAddress());
System.out.println("Designation:"+fac.getDesig());
System.out.println("Department:"+dept); System.out.println("Basic
pay:"+fac.getBasic()); System.out.println("Net salary:"+fac.calSalary());
}
}

43
Output:

2. Create a class hierarchy for the classes/interface as defined below: (CO2 -K3)

Class Shape:
Shape
#color:String=”red”
+Shape()
+Shape(color)
+getColor():String
+setColor(color):void

A sub-class Circle of class Shape:

44
Circle
#radius:float=1.0
+Circle()
+Circle(radius)
+Circle(radius,color)
+getRadius():float
+setRadius(radius):void
+getArea():float
+getPerimeter():float

A sub-class Rectangle of class Shape:

Rectangle
#width:float=1.0 #length:float=1.0

+Rectangle()
+Rectangle(width,length)
+Rectangle(width,length,color
)
+getWidth():float
+setWidth(width):void
+getLength():float
+setLength(length):void
+getArea():float
+getPerimeter():float

A sub-class Square of class Rectangle:

Square

+Square()
+Square(side)
+Square(side,color)
+getSide():float
+setSide(side):void

Note the following:


● The hierarchy Shape --> Rectangle --> Square is a multi-level inheritance.
● The type of above entire class hierarchy is hierarchical Inheritance.
● Note the constructor overloading at all the levels.
45
● # denotes a protected variable. The protected variables can be
accessed byits subclasses and classes in the same package.

Things to do:
1. Draw the class diagram of the above class hierarchy.
2. Write a test driver called TestShape to test all the public methods. Use
anarray of objects of type Shape and display the area and perimeter of all
the shapes (Circle, Rectangle and Square).
3. Note down the scope of the variable declared as protected.

Aim:
To write a java program using for the hierarchy Shape --> Rectangle -->
Square is a multi-level inheritance.

Source code:

import
java.util.Scanner; class
Shape{
protected String color = "red";

public Shape(){
}
public Shape(String color){
setColor(color);
}
public String getColor(){ return
color;
}
public void setColor(String color){
this.color=color;
}
}

class Circle extends


Shape{ protected float
radius=1.0f; public Circle(){
}
public Circle(float radius){
setRadius(radius);
}
public Circle(float radius,String color){
super(color);
setRadius(radius);
46
}
public float getRadius(){ return
radius;
}
public void setRadius(float radius){
this.radius=radius;
}
public float getArea(){
return 3.14f*radius*radius;
}
public float getPerimeter(){ return
2f*3.14f*radius;
}
}

class Rectangle extends


Shape{ protected float
width=1.0f; protected float
length=1.0f;
public Rectangle(){

}
public Rectangle(float width,float length) {
setWidth(width);
setLength(length);
}
public Rectangle(float width,float length,String color){ super(color);
setWidth(width);
setLength(length);
}
public float getWidth(){ return
width;
}
public void setWidth(float width){
this.width=width;
}
public float getLength(){ return
length;
}
public void setLength(float length){

47
this.length=length;
}
public float getArea(){ return
width*length;
}
public float getPerimeter(){ return
2f*(length+width);
}
}

class Square extends

Rectangle{ public Square(){

}
public Square(float side){
super(side,side);
}
public Square(float side,String color){
super(side,side,color);
}
public float getSide(){ return
length;
}
public void setSide(float side){
this.length=side;
}
}

public class testShape{


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

Shape[] shape = new Shape[3];


//shape[0] = new Circle();
//shape[0] = new Circle(12f); System.out.print("\
nEnter circle radius:"); float rad =
scan.nextFloat(); scan.nextLine();
System.out.print("Enter circle color:");
String c_col = scan.nextLine(); shape[0] =
new Circle(rad,c_col);

48
//shape[1] = new Rectangle();
//shape[1] = new Rectangle(10f,20f);
System.out.print("\nEnter rectangle length:"); float
len = scan.nextFloat(); System.out.print("Enter
rectangle width:"); float wid = scan.nextFloat();
scan.nextLine(); System.out.print("Enter
circle color:"); String r_col =
scan.nextLine();
shape[1] = new Rectangle(wid,len,r_col);

//shape[2] = new Square();


//shape[2] = new Square(5f);
System.out.print("\nEnter square side:"); float
sid = scan.nextFloat(); scan.nextLine();
System.out.print("Enter circle color:");
String s_col = scan.nextLine(); shape[2] =
new Square(sid,s_col);

for(Shape s:shape){
if(s instanceof Circle)
{ Circle cir = (Circle)
s;
System.out.println("\nColor:"+cir.getColor());
System.out.println("Radius:"+cir.getRadius());
System.out.println("Area:"+cir.getArea());
System.out.println("Perimeter:"+cir.getPerimeter());
}
else if(s instanceof Rectangle)
{ Rectangle rec = (Rectangle) s;
System.out.println("\nColor:"+rec.getColor());
System.out.println("Length:"+rec.getLength());
System.out.println("Width:"+rec.getWidth());
System.out.println("Area:"+rec.getArea());
System.out.println("Perimeter:"+rec.getPerimeter());
}
}
}
}

49
Output:

50
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027

UCS2313 – Object Oriented Programming Lab


Exercise 4: Abstract Classes and Interfaces

Learning Objective:

● To test the following Inheritance type: multiple inheritance.


● To test the Polymorphism through Interface / abstract classes
by method overriding.

Learning Outcome:

● Need of interface and its implementation in Java


● Need of abstract class and its implementation in Java
● Multiple inheritance
● Accessing the derived class objects through base class/interface
reference – Dynamic method dispatch/Dynamic binding

1. Create a class hierarchy for the classes defined below. The


notations to denote the access specifiers for the attributes and
methods are as follows:

- Private members

+ Public members

# Protected members

~ Default (Package private)

Class Person:
Perso
n
-name:String
-address:String

51
+Person(name,address)
+getName():String
+getAddress():String
+setAddress(address):void

A sub-class Employee of class Person:


Employe
e
-empid:String
-dept:String
-basic:int

+Employee(name,address,empid,dept,basic)
+getEmpid():int
+getDept():String
+setDept(dept):void
+getBasic():int
+setBasic(basic):void
+abs calSalary():float

A sub-class Faculty of class Employee:


Facult
y
-designation:String
-course:String
+Faculty(name,address,empid,dept,basic,desig,course)
+getDesig():String
+setDesig(desig):void
+getCourse():float
+setCourse(course):void
+calSalary():float

An interface Student:
<<Student>>

52
+getMarks():float []

+calcGPA():float
A sub-class TeachingAssistant of class Employee that implements interface

Student:

TeachingAssista
nt
-project:String
-course:String
-marks:float []

+TeachingAssistant(name,address,empid,dept,basic,project,course,marks)
+getProject():String
+getCourse():String
+setCourse(course):void
+getMarks():float []
+calcGPA():float
+calSalary():float

Things to do:

1. Draw the class diagram of the above class hierarchy.


2. Implement the above class hierarchy by using Interface and Abstract
class.

Hint:

To write an Interface:
● Only abstract methods can be declared inside the Interface.
● Identify the common behavior of the set of objects and
declare that as abstract methods inside the Interface.
● The classes that implement the Interface will provide
the actual implementation of those abstract methods.

To write an Abstract class:

1. An abstract class can have constructor(s), abstract or non-abstract


method(s).
2. Define the constructors and non-abstract methods in the

53
Abstract class Shape. Declare the common behavior as the
abstract method.
3. Let the classes define its own constructors, member variables and
methods.

54
4. Write a test driver function to get inputs for Faculty and
TeachingAssistant and display their details.
5. Find the class that can be declared as abstract.

6. Note down the differences while implementing the Inheritance


through Interface and Abstract class.
7. Note the run-time polymorphism in resolving the method call
exhibited by Java through method overriding.

Aim:

To write a test driver function to get inputs for Faculty and Teaching Assistant
and display their details using abstract classes and interfaces.

Source code:

import java.util.Scanner;

class Person{

private String name;

private String address;

public Person(String name,String address){

this.name=name;

setAddress(address);

public String getName(){

return name;
55
}

public String getAddress(){

return address;

public void setAddress(String address){

this.address=address;

abstract class Employee extends Person{

private String empid;

private String dept;

private int basic;

public Employee(String name,String address,String empid,String dept,int basic){

super(name,address);

this.empid=empid;

setDept(dept);

setBasic(basic);

public String getEmpid(){

return empid;

public String getDept(){

return dept;

public void setDept(String dept){

this.dept=dept;

56
}

public int getBasic(){

return basic;

public void setBasic(int basic){

this.basic=basic;

public abstract float calSalary();

class Faculty extends Employee{

private String designation;

private String course;

public Faculty(String name,String address,String empid,String dept,int basic,String


desig,String course){

super(name,address,empid,dept,basic);

setDesig(desig);

setCourse(course);

public String getDesig(){

return designation;

public void setDesig(String desig){

this.designation=desig;

public String getCourse(){

57
return course;

public void setCourse(String course){

this.course=course;

public float calSalary(){

float Gross_salary = (float)getBasic() + 0.6f*getBasic() + 0.1f*getBasic();

float Deductions = 0.085f*getBasic() + 0.08f*getBasic();

float Net_salary = Gross_salary - Deductions;

return Net_salary;

interface Student{

public float[] getMarks();

public float calcGPA();

class TeachingAssistant extends Employee implements Student{

private String project;

private String course;

private float[] marks;

public TeachingAssistant(String name,String address,String empid,String dept,int


basic,String project,String course,float[] marks){

super(name,address,empid,dept,basic);

this.project=project;

setCourse(course);

58
this.marks=marks;

public String getProject(){

return project;

public String getCourse(){

return course;

public void setCourse(String course){

this.course=course;

public float[] getMarks(){

return marks;

public float calcGPA(){

float total_mark=0;

for(float mark:marks){

total_mark+=mark;

return total_mark/marks.length/10;

public float calSalary(){

float Gross_salary = (float)getBasic() + 0.6f*getBasic() + 0.1f*getBasic();

float Deductions = 0.085f*getBasic() + 0.08f*getBasic();

float Net_salary = Gross_salary - Deductions;

59
return Net_salary;

public class test{

public static void main(String[] args){

Scanner scan = new Scanner(System.in);

System.out.println("\nEnter Faculty details:");

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

String fac_name = scan.nextLine();

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

String fac_address = scan.nextLine();

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

String fac_empid = scan.nextLine();

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

String fac_dept = scan.nextLine();

System.out.print("Enter basic pay:");

int fac_basic = scan.nextInt();

scan.nextLine();

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

String fac_desig = scan.nextLine();

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

String fac_course = scan.nextLine();

Faculty fac = new Faculty(fac_name, fac_address, fac_empid, fac_dept,


fac_basic, fac_desig, fac_course);

System.out.println("\nName:"+fac.getName());

60
System.out.println("Address:"+fac.getAddress());

System.out.println("Empid:"+fac.getEmpid());

System.out.println("Department:"+fac.getDept());

System.out.println("Basic pay:"+fac.getBasic());

System.out.println("Designation:"+fac.getDesig());

System.out.println("Course:"+fac.getCourse());

System.out.println("Net salary:"+fac.calSalary());

System.out.println("\nEnter Teaching Assistant details:");

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

String name = scan.nextLine();

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

String address = scan.nextLine();

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

String empid = scan.nextLine();

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

String dept = scan.nextLine();

System.out.print("Enter basic pay:");

int basic = scan.nextInt();

scan.nextLine();

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

String project = scan.nextLine();

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

String course = scan.nextLine();

System.out.print("Enter n for marks:");

int n=scan.nextInt();

61
float[] marks = new float[n];

for(int i=0;i<marks.length;i++){

System.out.print("Enter mark"+(i+1)+":");

marks[i]=scan.nextInt();

TeachingAssistant ta = new
TeachingAssistant(name,address,empid,dept,basic,project,course,marks);

System.out.println("\nName:"+ta.getName());

System.out.println("Address:"+ta.getAddress());

System.out.println("Empid:"+ta.getEmpid());

System.out.println("Department:"+ta.getDept());

System.out.println("Basic pay:"+ta.getBasic());

System.out.println("Project:"+ta.getProject());

System.out.println("Course:"+ta.getCourse());

for(int i=0;i<ta.getMarks().length;i++){

System.out.println("Mark"+(i+1)+":"+marks[i]);

System.out.println("GPA:"+ta.calcGPA());

System.out.println("Net salary:"+ta.calSalary());

62
Output:

2.Design a Java interface for ADT Stack with the following methods.

Maximum size of stack=15 boolean


isFull()

boolean isEmpty() void


push(int element) int
pop()

int peep()
Implement this interface using a class with an integer array to store the elements to
perform the following stack operations.

Boolean balanceParanthesis(String expression) boolean

63
checkTwoStacks(Stack s1, Stack s2)
Aim:

To implement this interface using a class with an integer array to store the elements to
perform the following stack operations.

Source code:

interface Stack {
int MAX_SIZE = 15;
boolean isFull();
boolean isEmpty();
void push(int element);

int pop();
int peep();
}

class StackImpl implements Stack {


private int[] stack;
private int top;

public StackImpl() {
stack = new int[MAX_SIZE];
top = -1;
}

public boolean isFull() {


return top == MAX_SIZE - 1;
}

public boolean isEmpty() {


return top == -1;
}

64
public void push(int element) {
if (!isFull()) {
stack[++top] = element;
} else {
System.out.println("Stack is full");
}
}

public int pop() {


if (!isEmpty()) {
return stack[top--];
} else {
System.out.println("Stack is empty");
return -1;
}
}

public int peep() {


if (!isEmpty()) {
return stack[top];
} else {
System.out.println("Stack is empty");
return -1;
}
}

public boolean balanceParanthesis(String expr) {


StackImpl stack = new StackImpl();
for (int i = 0; i < expr.length(); i++){
char ch = expr.charAt(i);

if (ch == '('){
stack.push(ch);
}
else if (ch == ')'){
if (stack.isEmpty()){
return false;
65
}
else{
stack.pop();
}
}
}
return stack.isEmpty();
}

public boolean checkTwoStacks(StackImpl s1, StackImpl s2) {


if (s1.top != s2.top) {
return false;
}
for (int i = 0; i <= s1.top; i++) {
if (s1.stack[i] != s2.stack[i]) {
return false;
}
}
return true;
}
}

public class stackOperation{


public static void main(String[] args) {

StackImpl stack1 = new StackImpl();


stack1.push(10);
System.out.println(10 + " poped in the stack1");
stack1.push(20);
System.out.println(20 + " poped in the stack1");
stack1.push(30);
System.out.println(30 + " poped in the stack1");

StackImpl stack2 = new StackImpl();


stack2.push(10);
System.out.println(10 + " poped in the stack2");
stack2.push(20);
66
System.out.println(20 + " poped in the stack2");
stack2.push(30);
System.out.println(30 + " poped in the stack3");

System.out.println("Are the two stacks equal? :" + stack1.checkTwoStacks(stack1,


stack2));

String expression = "(())()";


System.out.println("Is the expression balanced? :" +
stack1.balanceParanthesis(expression));
}
}

Output:

Sri Sivasubramaniya Nadar College of Engineering


Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027

UCS2313 – Object Oriented Programming Lab


67
Exercise 5: Exception Handling

Learning Outcome:

● Need of exception handling and it’s implementation in Java


● User defined exception creation and usage
● Usage of try, catch, finally, throw, throws

1. Create a class named Citizen that:


a. has the following instance variables: String name, int age, String
aadharNumber
b. has the following methods: getInput(), display(), canVote(),
hasAadhar()
c. throws the built-in exception NumberFormatException, if the age is
input as alphabets
d. throws a user-defined exception namely MinorCitizenException, if the age of
the citizen is < 18 printing a message that the citizen is not eligible to vote.
e. throws the built-in exception NullPointerException, if the Aadhar number
given as input is invalid. In order to validate an Aadhaar number, you
may store a set of 5 values in an array of Strings which are assumed to
be valid Aadhar numbers.

Aim:

To write the java program to implement exceptional handling for the method getInput(),
canVote () and hasAadhar() .

68
Source Code:

import java.util.*;
class MinorCitizenException extends Exception {
public MinorCitizenException(String message) {
super(message);
}
}
class Citizen {
private String Name;
private int age;
private String aadharNumber;
private String[] validAadharNo= {"123456789","987654321","987456321"};
public void getInput() throws NumberFormatException, NullPointerException {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter the Name:");
Name=sc.nextLine();
System.out.print("Enter the Age:");
String ageip=sc.nextLine();
age=Integer.parseInt(ageip);
System.out.print("Enter the Aadhar Number:");
aadharNumber=sc.nextLine();
}
catch(NumberFormatException e) {
throw new NumberFormatException("Invalid Input for Age, Please enter
a valid Number.");
}
catch(NullPointerException e) {
throw new NullPointerException("Invalid Aadhar Number, Please enter a
valid Aadhar Number.");
}
}

69
public void canVote() throws MinorCitizenException {
if(age>=18) {
System.out.println("The Person can Vote!!");
}
else {
throw new MinorCitizenException("The Person is ineligble to vote!!");
}
}
public void display() {
System.out.println("Name: "+Name);
System.out.println("Age: "+age);
System.out.println("Aadhar Number: "+aadharNumber);
}
public void hasAadhar() {
try {
validateAadhar(aadharNumber);
System.out.println("The person has valid Aadhar Number!!");
}
catch(NullPointerException e) {
System.out.println("The person does not have valid Aadhaar Number");
}
}
void validateAadhar(String No) {
boolean isValid = false;
for(String valid:validAadharNo) {
if(valid.equals(No)) {
isValid = true;
break;
}
}
if(!isValid) {
throw new NullPointerException("Invalid Aadhar Number");
}
70
}

public static void main(String[] args) {


Citizen cz = new Citizen();
try {
cz.getInput();
cz.canVote();
cz.hasAadhar();
}
catch (NumberFormatException e) {
System.out.println(e.getMessage());
}
catch (MinorCitizenException e) {
System.out.println(e.getMessage());
}
catch (NullPointerException e) {
System.out.println(e.getMessage());
}
finally {
cz.display();
}
}
}

Output:

71
2. Create a class named BankAccount that is a template for a Bank Account, and:
a. has the following instance variables: String name, String acct_num, String
branch, double balance, and String PAN_num

b. has functions that do the following:


i. deposit money into that account: If a customer deposits more than
₹25000, then throw a user-defined exception PANRequiredException, obtain
the PAN number as input and then proceed with the deposit.

ii. withdraw money from that account: If the customer is withdrawing money,
then check if there is a minimum balance in the account. This amount may
be declared as a constant MIN_BALANCE. If the account does not have the
required minimum balance, then throw a user-defined exception, namely
MinBalRequiredException. If the withdrawal amount is more than the balance
amount, then throw a user-defined exception InsufficientBalanceException.

iii. checks for existence of a particular account number during deposit and
withdrawal: If the account number is not present, then throw a user-defined
exception AccountNotFoundException. Else, display details of that account.

iv. checks for validity of PAN number during deposit: On entering the PAN
number, check if it has 10 characters with first 5 being alphabets followed by
4 digits and then one alphabet. If the format is not matched then throw a
user-defined exception PANFormatMismatchException.

v. checks for a valid bank branch during creation of a bank account: On


account creation, if a user gives a non existing branch, then throw a user-
defined exception BranchNotFoundException.

Aim:

To write java program to implement exception handling method in banking interface


which handles various exceptions such as BranchNotFound, PanFormatMismatch,
AccountNotFound, MinBalRequired and InsufficientBalance.

72
Source Code:

import java.util.Scanner;

class PANRequiredException extends Exception {

public PANRequiredException(String message) {

super(message);

class MinBalRequiredException extends Exception {

public MinBalRequiredException(String message) {

super(message);

class InsufficientBalanceException extends Exception {

public InsufficientBalanceException(String message) {

super(message);

class AccountNotFoundException extends Exception {

public AccountNotFoundException(String message) {

super(message);

class PANFormatMismatchException extends Exception {

public PANFormatMismatchException(String message) {

super(message);

class BranchNotFoundException extends Exception {

public BranchNotFoundException(String message) {

super(message);

73
}

class BankAccount {

private static final double MIN_BALANCE = 5000; // Constant for minimum balance

private String name;

private String acct_num;

private String branch;

private double balance;

private String PAN_num;

// Constructor

public BankAccount(String name, String acct_num, String branch, double balance, String
PAN_num) throws BranchNotFoundException {

this.name = name;

this.acct_num = acct_num;

this.balance = balance;

this.PAN_num = PAN_num;

// Validate branch during account creation

if (!isValidBranch(branch)) {

throw new BranchNotFoundException("Branch not found: " + branch);

this.branch = branch;

public void deposit(double amount) throws PANRequiredException,


PANFormatMismatchException, AccountNotFoundException {

if (this.acct_num == null || this.acct_num.isEmpty()) {

throw new AccountNotFoundException("Account not found.");

if (amount > 25000) {

if (this.PAN_num == null || this.PAN_num.isEmpty()) {

74
throw new PANRequiredException("PAN number required for deposit over
₹25000.");

validatePAN();

this.balance += amount;

System.out.println("Deposit successful. New balance: ₹" + this.balance);

public void withdraw(double amount) throws MinBalRequiredException,


InsufficientBalanceException, AccountNotFoundException {

if (this.acct_num == null || this.acct_num.isEmpty()) {

throw new AccountNotFoundException("Account not found.");

if (this.balance - amount < MIN_BALANCE) {

throw new MinBalRequiredException("Minimum balance of ₹" + MIN_BALANCE + " is


required.");

if (amount > this.balance) {

throw new InsufficientBalanceException("Insufficient balance for the requested


withdrawal.");

this.balance -= amount;

System.out.println("Withdrawal successful. New balance: ₹" + this.balance);

private boolean isValidBranch(String branch) {

String[] validBranches = {"Mumbai", "Delhi", "Bangalore", "Chennai"};

for (String validBranch : validBranches) {

if (validBranch.equalsIgnoreCase(branch)) {

return true;

return false;
75
}

private void validatePAN() throws PANFormatMismatchException {

if (!this.PAN_num.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}")) {

throw new PANFormatMismatchException("PAN number format is invalid.");

public void setPAN(String PAN_num) throws PANFormatMismatchException {

if (!PAN_num.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}")) {

throw new PANFormatMismatchException("PAN number format is invalid.");

this.PAN_num = PAN_num;

public void displayAccountDetails() {

System.out.println("Account Holder: " + this.name);

System.out.println("Account Number: " + this.acct_num);

System.out.println("Branch: " + this.branch);

System.out.println("Balance: ₹" + this.balance);

System.out.println("PAN: " + this.PAN_num);

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter the name of person: ");

String name = sc.nextLine();

System.out.print("Enter acc no: ");

String acc = sc.nextLine();

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

String branch=sc.nextLine();

System.err.print("Enter the inital balance: ");

double bal = sc.nextDouble();

76
sc.nextLine();

try{

BankAccount account = new BankAccount(name, acc, branch, bal, "");

account.displayAccountDetails();

try {

System.out.println("\nAttempting to deposit ₹30000...");

account.deposit(30000);

} catch (PANRequiredException e) {

System.out.println(e.getMessage());

System.out.print("Please provide a valid PAN number: ");

String panInput = sc.nextLine();

try {

account.setPAN(panInput);

account.deposit(30000);

} catch (PANFormatMismatchException | PANRequiredException ex) {

System.out.println(ex.getMessage());

} catch (PANFormatMismatchException e) {

System.out.println(e.getMessage());

try {

System.out.println("\nAttempting to withdraw ₹5000...");

account.withdraw(5000);

} catch (MinBalRequiredException | InsufficientBalanceException e) {

System.out.println(e.getMessage());

try {

System.out.println("\nAttempting to withdraw ₹20000...");

account.withdraw(20000);

} catch (MinBalRequiredException | InsufficientBalanceException e) {

System.out.println(e.getMessage());

77
}

try {

System.out.println("\nAttempting to withdraw ₹80000...");

account.withdraw(80000);

} catch (MinBalRequiredException | InsufficientBalanceException e) {

System.out.println(e.getMessage());

catch (BranchNotFoundException e) {

System.out.println(e.getMessage());

} catch (AccountNotFoundException e) {

System.out.println(e.getMessage());

sc.close();

Output:

78
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027

UCS2313 – Object Oriented Programming Lab


Exercise 6: Packages

Learning Outcome:
 Create a user defined package and access it outside the package
 Create subpackages and their usage

1. Create a package named machines with the following three java classes.
a. Class HomeAppliance
b. Class Vehicle
c. Class FactoryEquipment
The classes should contain methods to return the fuelType (electricity, petrol, or diesel)
and energyConsumption (in units per hour in case of electricity, and km per litre in case
of petrol/diesel). Use this package to develop a Java program to print the type of fuel
and energy consumed. This program should be in a Java file outside the package
machines.

Aim:
To write a java program to execute java program which contains classes is from user-
defined package.

Source Code:
Vehicle.java (which is in folder of machine)
package machine;
public class Vehicle{
public String fuelType(){
return "Petrol";
}
public String energyConsumption(){
return "45 Km per litre";
}
}
79
FactoryEquipment.java (which is in folder of machine)
package machine;
public class FactoryEquipment{
public String fuelType(){
return "Diesel";
}
public String energyConsumption(){
return "20 rotation per litre";
}
}

HomeAppliance.java (which is in folder of machine)


package machine;
public class HomeAppliance{
public String fuelType(){
return "Electricity";
}
public String energyConsumption(){
return "10 units per hour";
}
}

PackageImplementation.java (It should be in same project folder of machine package)


import machine.*;
class PackageImplementation{
public static void main(String[] args){
Vehicle v = new Vehicle();
System.out.println(v.fuelType()+" "+v.energyConsumption());
HomeAppliance Hp = new HomeAppliance();
System.out.println(Hp.fuelType()+" "+Hp.energyConsumption());
FactoryEquipment fe = new FactoryEquipment();
System.out.println(fe.fuelType()+" "+fe.energyConsumption());
}
80
}

Output:

2. Write a program to create a package maths.operations having three classes:


Addition, Multiplication and Subtraction. Define suitable methods in each class to
perform basic operations. Inside the package maths, write a Java program to take as
input two numbers, and perform the specified operations by creating classes as
applicable.

Aim:
To create java program to implement subpackage of user which contains the class of
Addition, Subtraction and Multiplication

Source Code:
Addition.java (which is in folder of maths.operation)
package maths.operation;
public class Addition {
public int doAdd(int a, int b){
return a+b;
}
}
Subtraction.java (which is in folder of maths.operation)
package maths.operation;
public class Subtraction {
public int doSub(int a, int b){
return a-b;
}
}

81
Multiplication.java (which is in folder of maths.operation)
package maths.operation;
public class Multiplication {
public int doMul(int a, int b){
return a*b;
}
}
Main.java (which is in folder of maths)
package maths;
import maths.operation.*;
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Choose 1 for Addition\n 2 for Subtraction\n 3 for Multiplication:
");
int no = sc.nextInt();
System.out.print("Enter two Number: ");
int x = sc.nextInt();
int y = sc.nextInt();
if(no==1){
Addition ad = new Addition();
System.out.print("The sum of two numbers is "+ad.doAdd(x, y));
}
else if(no==2){
Subtraction sb = new Subtraction();
System.out.print("The sum of two numbers is "+sb.doSub(x, y));
}
else if(no==3){
Multiplication mt = new Multiplication();
System.out.print("The sum of two numbers is "+mt.doMul(x, y));
}

82
else{
System.out.println("Enter the correct option");
}
sc.close();
}
}

Output:

83
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027

UCS2313 – Object Oriented Programming Lab


Exercise 7: Generics

Learning Outcome:
 Learning to create a generic class and method
 Use the generic class to store/manipulate elements of different data types

1. Write a Java program that defines a generic type MyLinkedList. The nodes in the
linked list should be capable of holding data of any of the following types
Integer,Double, Character, String. You should define functions to achieve the
functionality specified below:

a. Add new nodes: If a position is specified, then the new node should get
added immediately after the specified position. If no position is
specified,then the node should get added as the last node in the list.

b. Remove nodes: If a position is specified, then the node at that position


should get deleted. If a data value is given, then the first node holding that
data should get deleted.

c. Get data: The data at a given position should be returned.

Aim:
To write a java program to implement the Generics in Data Structure of Linked List
which can handle the Integer, Double, Character and String.

Code:
class LinkedList<l> {
l data;
LinkedList<l> next;

LinkedList(l data) {
this.data = data;
this.next = null;
}
}

public class generics1<l> {


private LinkedList<l> head;

84
private int size;

public generics1() {
head = null;
size = 0;
}

public void add(l data) {


LinkedList<l> link = new LinkedList<>(data);
if (head == null) {
head = link;
} else {
LinkedList<l> current = head;
while (current.next != null) {
current = current.next;
}
current.next = link;
}
size++;
}

public void add(l data, int position) {

LinkedList<l> link = new LinkedList<>(data);


if (position == 0) {
link.next = head;
head = link;
} else {
LinkedList<l> current = head;
for (int i = 0; i < position - 1; i++) {
current = current.next;
}
link.next = current.next;
current.next = link;
}
size++;
}

public void remove(int position) {

if (position == 0) {
head = head.next;
} else {
LinkedList<l> current = head;
for (int i = 0; i < position - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}

85
size--;
}

public void remove(l data) {


if (head == null) return;

if (head.data.equals(data)) {
head = head.next;
size--;
return;
}

LinkedList<l> temp = head;


while (temp.next != null) {
if (temp.next.data.equals(data)) {
temp.next = temp.next.next;
size--;
return;
}
temp = temp.next;
}
}

public l getdata(int position) {

LinkedList<l> temp = head;


for (int i = 0; i < position; i++) {
temp = temp.next;
}
return temp.data;
}

public int size() {


return size;
}

public static void main(String[] args) {


generics1<Object> list = new generics1<>();
list.add(10);
list.add(20.5);
list.add("Hello");
list.add("World", 2);

System.out.println("List after additions:");


for (int i = 0; i < list.size(); i++) {
System.out.println(list.getdata(i));
}

list.remove(1);
System.out.println("\nList after removing position 1:");
for (int i = 0; i < list.size(); i++) {

86
System.out.println(list.getdata(i));
}

list.remove("Hello");
System.out.println("\nList after removing 'Hello':");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.getdata(i));
}

if (list.size() > 1) {
System.out.println("\nData at position 1: " + list.getdata(1));
} else {
System.out.println("\nNo data at position 1.");
}
}
}

Output:

2. Write a Java program that defines a generic type ShapeBox that is capable of
holding different types of shapes. The ShapeBox class should allow you to add
shapes of different types (e.g., Circle, Square, Triangle) and provide a method to
calculate the total area of all shapes in the box.
a. Shape - An abstract class representing a shape with an abstract method
double getArea() to calculate the area of the shape.
b. Circle - A class representing a circle, which is a subclass of Shape. It
should have a constructor that takes the radius. It should implement the
getArea method to calculate the area of the circle.

87
c. Rectangle - A class representing a rectangle, which is a subclass of
Shape. It should have a constructor that takes the length and width. It
should also implement the getArea method to calculate the area of the
rectangle.
d. ShapeBox<T> - A generic class that can hold shapes of any type T that
extends the Shape class. It should have methods to add shapes to the
box and calculate the total area of all shapes in the box.
Write a Java program that demonstrates the usage of these classes by creating a
ShapeBox, adding various shapes to it, and calculating the total area of all the shapes
in the box. Your program should output the total area of the shapes in the box.

Aim:
To write a java program to demonstrate the generic class ShapeBox which contains
different methods to add shape and calculating the area of shapes.

Code:
abstract class Shape{
abstract double getarea();
}
class Circle extends Shape{
private int radius;
Circle(int radius){
this.radius = radius;
}
double getarea(){
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape{
private int length;
private int width;
Rectangle(int length, int width){
this.length = length;
this.width = width;
}
double getarea(){
return length * width;
}
}
class S<s extends Shape> {
private s[] shapes;
private int count;
public S(int length){
shapes = (s[]) new Shape[length];
count = 0;
}
void add(s shape){
88
if(count < shapes.length)
shapes[count++] = shape;
else
System.out.println("Shapes is full");

}
public double total_area(){
double total = 0.0;
for(int i = 0; i < count; i++){
total += shapes[i].getarea();
}
return total;
}
}
public class generics2 {
public static void main(String[] args) {
S <Shape> sh= new S<>(10);
sh.add(new Rectangle(4,5));
sh.add(new Circle(9));
System.out.println("The total area is "+sh.total_area());
}
}

Output:

3. Write a Java program to perform a sorting operation on various types of


elements using a generic method.

Aim:

To write a java program to sort the various types of elements using the generic class
and methods

Code:

class Sort {

public static<s extends Number> void sort(s[] array) {


int n = array.length;
89
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (array[j].doubleValue() > array[j + 1].doubleValue()) {

s temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(array[i]+" ");
}
}

public class generics3 {


public static void main(String[] args) {
Integer arr[] = {5,1,6,9,78,10};
Sort.sort(arr);
System.out.println();

Double arr1[] = {10.1,3.2,5.6,4.8,9.1};


Sort.sort(arr1);

}
}

Output:

90
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027

UCS2313 – Object Oriented Programming Lab


Exercise 8: Collections Framework

Learning Outcome:
 Usage of ArrayList and LinkedList in Java
 Perform operations using Collections Framework
 Perform merge, union, intersection and comparison on ArrayLists

1. Write a program to perform operations on an ArrayList of strings. Specifically,


write functions for the following:
a. Append to the list
b. Insert at a particular index in the list
c. Search for an element, and find its index, if it exists
d. Display the list
e. Display all strings in the list that start with the given letter
f. Display all strings that contain a given string as a substring
g. Sort the elements in ArrayList
h. Remove a particular element
i. Replace one element with another element
j. Remove duplicate elements

Aim:
To write a java program to implement ArrayList of strings and also implement the
following given methods given.
Code:
import java.util.*;
public class StringArrayListOperations {
private ArrayList<String> stringList;

91
public StringArrayListOperations() {
stringList = new ArrayList<>();
}
public void append(String str) {
stringList.add(str);
}
public void insertAt(int index, String str) {
if (index >= 0 && index <= stringList.size()) {
stringList.add(index, str);
} else {
System.out.println("Index out of bounds.");
}
}
public int search(String str) {
return stringList.indexOf(str);
}
public void display() {
System.out.println("Current List: " + stringList);
}
public void displayStartingWith(char letter) {
System.out.println("Strings starting with '" + letter + "':");
for (String str : stringList) {
if (str.startsWith(String.valueOf(letter))) {
System.out.println(str);
}
}
}
public void displayContaining(String substring) {
System.out.println("Strings containing '" + substring + "':");
for (String str : stringList) {
if (str.contains(substring)) {
System.out.println(str);
}
92
}
}
public void sort() {
Collections.sort(stringList);
}
public void remove(String str) {
stringList.remove(str);
}
public void replace(String oldStr, String newStr) {
int index = stringList.indexOf(oldStr);
if (index != -1) {
stringList.set(index, newStr);
} else {
System.out.println("Element not found.");
}
}
public void removeDuplicates() {
ArrayList<String> uniqueList = new ArrayList<>();
for (String str : stringList) {
if (!uniqueList.contains(str)) {
uniqueList.add(str);
}
}
stringList = uniqueList;
}

public static void main(String[] args) {


StringArrayListOperations operations = new StringArrayListOperations();
operations.append("Anil");
operations.append("Anush");
operations.append("Bhuvan");
operations.append("Rohit");
operations.append("Rahul");
93
operations.append("Gopal");
operations.display();
operations.insertAt(3, "Shyam");
operations.insertAt(5, "Arav");
operations.insertAt(6, "Anuju");
operations.append("Gopal");
operations.display();

int indexFound = operations.search("Shyam");


if (indexFound != -1) {
System.out.println("Element found at index: " + indexFound);
} else {
System.out.println("Element not found.");
}
operations.display();
operations.displayStartingWith('R');
operations.displayContaining("sh");
operations.sort();
operations.remove("Rahul");
operations.display();
operations.replace("Shyam", "Gopal");
operations.display();
operations.removeDuplicates();
operations.display();

}
}

94
Output:

2. Write a program to get two integer Arraylists. Write functions to perform the
following operations:

a. Merge the two lists

b. Find union of the two lists

c. Find intersection of the two lists

d. Compare the two lists, and list elements that are common in both, and
those that are different in both.

Aim:
To write a java program to implement integer ArrayList and performing the following
given operations.

Code:
import java.util.*;
public class IntegerArrayListOperations {
public static ArrayList<Integer> merge(ArrayList<Integer> list1, ArrayList<Integer>
list2) {
ArrayList<Integer> mergedList = new ArrayList<>(list1);
mergedList.addAll(list2);
return mergedList;
}
public static ArrayList<Integer> union(ArrayList<Integer> list1, ArrayList<Integer>
list2) {
Set<Integer> set = new HashSet<>(list1);
set.addAll(list2);
return new ArrayList<>(set);

95
}
public static ArrayList<Integer> intersection(ArrayList<Integer> list1,
ArrayList<Integer> list2) {
ArrayList<Integer> intersectionList = new ArrayList<>();
for (Integer element : list1) {
if (list2.contains(element)) {
intersectionList.add(element);
}
}
return intersectionList;
}
public static void compareLists(ArrayList<Integer> list1, ArrayList<Integer> list2) {
ArrayList<Integer> common = new ArrayList<>();
ArrayList<Integer> different = new ArrayList<>(list1);

for (Integer element : list1) {


if (list2.contains(element)) {
common.add(element);
}
}

different.removeAll(common);
different.addAll(list2);
different.removeAll(common);

System.out.println("Common elements: " + common);


System.out.println("Different elements: " + different);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();

96
System.out.print("Enter elements for the first list (comma separated): ");
String[] input1 = scanner.nextLine().split(",");
for (String s : input1) {
list1.add(Integer.parseInt(s.trim()));
}

System.out.print("Enter elements for the second list (comma separated): ");


String[] input2 = scanner.nextLine().split(",");
for (String s : input2) {
list2.add(Integer.parseInt(s.trim()));
}

System.out.println("\nList 1: " + list1);


System.out.println("List 2: " + list2);
System.out.println("\nMerged list: " + merge(list1, list2));
System.out.println("Union of lists: " + union(list1, list2));
System.out.println("Intersection of lists: " + intersection(list1, list2));

System.out.println("\nComparison of lists:");
compareLists(list1, list2);

scanner.close();
}
}

97
Output:

3. Using the Collections framework, create a doubly linked list of integers and
perform the following operations.

a. Insert an element on either side of the list (take the side also as input)

b. Delete element from either side (take the side also as input)

c. Insert an element at a particular position

d. Delete a particular element

e. Search for a particular element

f. Display the list in forward order and backward order

g. Sort the elements in the list

h. Replace one element in the list with another list

i. Remove duplicate elements

Aim:
To write a java program to implement doubly linked list of integers and implementing
the given following functions.

Code:
import java.util.*;
public class DoublyLinkedListOperations {
private LinkedList<Integer> linkedList;
public DoublyLinkedListOperations() {
linkedList = new LinkedList<>();
}
public void insertAtSide(int element, String side) {

98
if (side.equalsIgnoreCase("front")) {
linkedList.addFirst(element);
} else if (side.equalsIgnoreCase("rear")) {
linkedList.addLast(element);
}
}
public void deleteFromSide(String side) {
if (linkedList.isEmpty()) {
System.out.println("List is empty.");
} else if (side.equalsIgnoreCase("front")) {
linkedList.removeFirst();
} else if (side.equalsIgnoreCase("rear")) {
linkedList.removeLast();
}
}
public void insertAtPosition(int index, int element) {
if (index >= 0 && index <= linkedList.size()) {
linkedList.add(index, element);
} else {
System.out.println("Index out of bounds.");
}
}
public void deleteElement(int element) {
if (linkedList.contains(element)) {
linkedList.remove(Integer.valueOf(element));
} else {
System.out.println("Element not found.");
}
}
public boolean search(int element) {
return linkedList.contains(element);
}
public void displayForward() {
99
System.out.println("List (Forward): " + linkedList);
}
public void displayBackward() {
System.out.print("List (Backward): ");
ListIterator<Integer> iterator = linkedList.listIterator(linkedList.size());
while (iterator.hasPrevious()) {
System.out.print(iterator.previous() + " ");
}
System.out.println();
}
public void sort() {
linkedList.sort(Integer::compareTo);
System.out.println("List sorted.");
}
public void replaceElement(int oldElement, int newElement) {
int index = linkedList.indexOf(oldElement);
if (index != -1) {
linkedList.set(index, newElement);
} else {
System.out.println("Element not found.");
}
}
public void removeDuplicates() {
LinkedList<Integer> uniqueList = new LinkedList<>();
for (Integer element : linkedList) {
if (!uniqueList.contains(element)) {
uniqueList.add(element);
}
}
linkedList = uniqueList;
System.out.println("Duplicates removed.");
}

100
public static void main(String[] args) {
DoublyLinkedListOperations operations = new DoublyLinkedListOperations();
operations.insertAtSide(10,"front");
operations.insertAtSide(12,"rear");
operations.insertAtSide(17,"rear");
operations.insertAtSide(11,"rear");
operations.insertAtSide(17,"rear");
operations.insertAtSide(15,"front");
operations.displayForward();
operations.deleteFromSide("rear");
operations.displayForward();
operations.insertAtPosition(3,20);
operations.insertAtPosition(4,30);
operations.deleteFromSide("front");
operations.displayForward();
if (operations.search(12)) {
System.out.println("Element found.");
} else {
System.out.println("Element not found.");
}
operations.sort();
operations.displayForward();
operations.replaceElement(20,12);
operations.displayForward();
operations.removeDuplicates();
operations.displayForward();
operations.displayBackward();
}
}

101
Output:

102

You might also like