Merged Assignment
Merged Assignment
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 {
Scanner s = new
Scanner(System.in);
System.out.print("Enter the
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:
Code:
import java.util.Scanner;
class fact{
int fac=1;
int n=s.nextInt();
fac=fac*i;
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{
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;
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{
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
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;
= m1; this.m2 =
this.avg = avg;
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;
5
}
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;
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();
String name=s.nextLine();
dept=s.nextLine();
id=s.nextInt();
float m1=s.nextFloat();
float m2=s.nextFloat();
float m3=s.nextFloat();
float avg=(m1+m2+m3)/3;
return avg;
7
Scanner s = new Scanner(System.in);
int n=s.nextInt();
for(int i=0;i<n;i++){
get_input(s,students,i);
display(students,n);
ch = s.nextInt();
s.nextLine();
if(ch==1){
String nm = s.nextLine();
name_search(students,n,nm);
else if(ch==2){
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
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:
If the type of the EB connection is commercial, calculate the amount to be paid as follows:
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;
consumer.Cons_name = s.nextLine();
consumer.Cons_type = s.nextLine();
consumer.Cons_no = s.nextInt();
consumer.pre_reading = s.nextFloat();
consumer.cur_reading = s.nextFloat();
consumer.unit=consumer.cur_reading - consumer.pre_reading;
System.out.println("Consumer no.:"+consumer.Cons_no);
System.out.println("Consumer name:"+consumer.Cons_name);
System.out.println("Consumer type:"+consumer.Cons_type);
amount:"+consumer.amt);
}
11
float amt=0;
if(consumer.Cons_type.equals("Domestic")){
if(consumer.unit<=100){
amt=consumer.unit*1f;
}
amt=100+(consumer.unit-100)*2.5f;
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;
amt=100+(consumer.unit-100)*4.50f;
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;
Scanner s =new
Scanner(System.in);
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;
= m1; this.m2 =
this.avg = avg;
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;
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;
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);
s.nextLine();
String name=s.nextLine();
dept=s.nextLine();
id=s.nextInt();
float m1=s.nextFloat();
float m2=s.nextFloat();
float m3=s.nextFloat();
float avg=(m1+m2+m3)/3;
return avg;
16
}
int n=s.nextInt();
for(int i=0;i<n;i++){
get_input(s,students,i);
display(students,n);
ch = s.nextInt();
s.nextLine();
if(ch==1){
String nm = s.nextLine();
search(students,n,nm);
else if(ch==2){
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;
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;
for(int i=0;i<n;i++){
emp[i].name = s.nextLine();
emp[i].design = s.nextLine();
System.out.print("Enter id of employee:");
emp[i].id = s.nextInt();
if(emp[i].design.equalsIgnoreCase("Intern")){
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{
emp[i].yrs_of_exp = s.nextFloat();
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")) {
s.nextLine();
cal_gross_and_net(emp,i);
}
System.out.println("\t\tPayslip");
System.out.println("==========================================");
21
System.out.println("Designation: " + emp[i].design);
System.out.println("==========================================\n");
(int i=0;i<n;i++){
if(emp[i].id==id){
(int i=0;i<n;i++){
if(emp[i].yrs_of_exp>=10){ System.out.println("\
n==========================================");
System.out.println("==========================================\n");
22
}
n =s.nextInt();
s.nextLine();
get_emp_input(emp,n,s);
display(emp,n);
promotion(emp,n);
23
Output:
24
Learning Outcomes:
25
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027
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{
for(int i=0;i<arr.length;i++){
if(e1==arr[i]){
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;
st=0,fnl=arr.length,mid; while(st<=fnl){
mid=(st+fnl)/2;
if(arr[mid]==e2){
break;
}
else if(arr[mid]<e2){
st=mid+1;
else if(arr[mid]>e2){
fnl=mid-1;
Scanner(System.in);
n=scan.nextInt();
for(int i=0;i<n;i++){
e1=scan.nextInt();
27
lin_search(arr,e1);
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{
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
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();
i=0;i<mat.length;i++){
for(int j=0;j<mat.length;j++){
mat[i][j]=scan.nextInt();
Scanner(System.in);
29
System.out.print("Enter the value n:"); int
n=scan.nextInt();
get_input(A,scan);
get_input(B,scan);
System.out.println("\nAddition Matrix:");
display(Add_mat); System.out.println("\
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.
●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{
Scanner(System.in);
System.out.print("Enter a Sentence:");
String sen=scan.nextLine();
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;
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{
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){
else{
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{
Scanner(System.in);
System.out.print("Enter a sentence:");
String str=scan.nextLine();
str=str.toUpperCase();
i=0;i<str.length();i++){
char j = str.charAt(i); if
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){
else{
for(int i=0;i<alpha.length;i++){
char c=(char)(i+'A');
System.out.println(c+":"+alpha[i]);
Output:
36
Learning Objectives:
2.Matrix Operations.
Learning Outcomes:
37
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027
Learning Objective:
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
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
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:
Things to do:
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;
}
}
System.out.print("Enter address:");
String address = scan.nextLine();
System.out.print("Enter program:");
String program = scan.nextLine();
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.print("Enter gender:");
char fac_gender = scan.next().charAt(0);
scan.nextLine();
System.out.print("Enter designation:");
String designation = scan.nextLine();
System.out.print("Enter department:");
String dept = scan.nextLine();
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
44
Circle
#radius:float=1.0
+Circle()
+Circle(radius)
+Circle(radius,color)
+getRadius():float
+setRadius(radius):void
+getArea():float
+getPerimeter():float
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
Square
+Square()
+Square(side)
+Square(side,color)
+getSide():float
+setSide(side):void
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;
}
}
}
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);
}
}
}
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;
}
}
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);
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
Learning Objective:
Learning Outcome:
- Private members
+ Public members
# Protected members
Class Person:
Perso
n
-name:String
-address:String
51
+Person(name,address)
+getName():String
+getAddress():String
+setAddress(address):void
+Employee(name,address,empid,dept,basic)
+getEmpid():int
+getDept():String
+setDept(dept):void
+getBasic():int
+setBasic(basic):void
+abs 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:
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.
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.
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{
this.name=name;
setAddress(address);
return name;
55
}
return address;
this.address=address;
super(name,address);
this.empid=empid;
setDept(dept);
setBasic(basic);
return empid;
return dept;
this.dept=dept;
56
}
return basic;
this.basic=basic;
super(name,address,empid,dept,basic);
setDesig(desig);
setCourse(course);
return designation;
this.designation=desig;
57
return course;
this.course=course;
return Net_salary;
interface Student{
super(name,address,empid,dept,basic);
this.project=project;
setCourse(course);
58
this.marks=marks;
return project;
return course;
this.course=course;
return marks;
float total_mark=0;
for(float mark:marks){
total_mark+=mark;
return total_mark/marks.length/10;
59
return Net_salary;
System.out.print("Enter name:");
System.out.print("Enter address:");
System.out.print("Enter empid:");
System.out.print("Enter department:");
scan.nextLine();
System.out.print("Enter designation:");
System.out.print("Enter 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.print("Enter name:");
System.out.print("Enter address:");
System.out.print("Enter empid:");
System.out.print("Enter department:");
scan.nextLine();
System.out.print("Enter project:");
System.out.print("Enter course:");
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.
int peep()
Implement this interface using a class with an integer array to store the elements to
perform the following stack operations.
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();
}
public StackImpl() {
stack = new int[MAX_SIZE];
top = -1;
}
64
public void push(int element) {
if (!isFull()) {
stack[++top] = element;
} else {
System.out.println("Stack is full");
}
}
if (ch == '('){
stack.push(ch);
}
else if (ch == ')'){
if (stack.isEmpty()){
return false;
65
}
else{
stack.pop();
}
}
}
return stack.isEmpty();
}
Output:
Learning Outcome:
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
}
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
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.
Aim:
72
Source Code:
import java.util.Scanner;
super(message);
super(message);
super(message);
super(message);
super(message);
super(message);
73
}
class BankAccount {
private static final double MIN_BALANCE = 5000; // Constant for minimum balance
// 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;
if (!isValidBranch(branch)) {
this.branch = branch;
74
throw new PANRequiredException("PAN number required for deposit over
₹25000.");
validatePAN();
this.balance += amount;
this.balance -= amount;
if (validBranch.equalsIgnoreCase(branch)) {
return true;
return false;
75
}
if (!this.PAN_num.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}")) {
if (!PAN_num.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}")) {
this.PAN_num = PAN_num;
String branch=sc.nextLine();
76
sc.nextLine();
try{
account.displayAccountDetails();
try {
account.deposit(30000);
} catch (PANRequiredException e) {
System.out.println(e.getMessage());
try {
account.setPAN(panInput);
account.deposit(30000);
System.out.println(ex.getMessage());
} catch (PANFormatMismatchException e) {
System.out.println(e.getMessage());
try {
account.withdraw(5000);
System.out.println(e.getMessage());
try {
account.withdraw(20000);
System.out.println(e.getMessage());
77
}
try {
account.withdraw(80000);
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
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";
}
}
Output:
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
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.
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;
}
}
84
private int size;
public generics1() {
head = null;
size = 0;
}
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--;
}
if (head.data.equals(data)) {
head = head.next;
size--;
return;
}
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:
Aim:
To write a java program to sort the various types of elements using the generic class
and methods
Code:
class Sort {
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]+" ");
}
}
}
}
Output:
90
Sri Sivasubramaniya Nadar College of Engineering
Department of Computer Science and Engineering
B.E Computer Science & Engineering
2023-2027
Learning Outcome:
Usage of ArrayList and LinkedList in Java
Perform operations using Collections Framework
Perform merge, union, intersection and comparison on ArrayLists
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;
}
}
}
94
Output:
2. Write a program to get two integer Arraylists. Write functions to perform the
following operations:
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);
different.removeAll(common);
different.addAll(list2);
different.removeAll(common);
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.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)
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