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

AnandJAVA

This document is a lab record for a Java programming course at Cochin University of Science and Technology, detailing the work of a student named Anand Kumar. It includes a certificate of completion, a list of programming titles covered in the lab, and sample Java programs with their respective outputs for various problems such as saddle points in matrices, character counting, and calculating areas of geometric shapes. The document serves as a comprehensive record of the student's practical work in Java programming.

Uploaded by

psingh80437
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

AnandJAVA

This document is a lab record for a Java programming course at Cochin University of Science and Technology, detailing the work of a student named Anand Kumar. It includes a certificate of completion, a list of programming titles covered in the lab, and sample Java programs with their respective outputs for various problems such as saddle points in matrices, character counting, and calculating areas of geometric shapes. The document serves as a comprehensive record of the student's practical work in Java programming.

Uploaded by

psingh80437
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

DEPARTMENT OF COMPUTER APPLICATIONS

COCHIN UNIVERSITY OF SCIENCE AND TECHNOLOGY

LAB RECORD
22-382-0206 JAVA LAB
DEPARTMENT OF COMPUTER APPLICATIONS
COCHIN UNIVERSITY OF SCIENCE AND TECHNOLOGY

CERTIFICATE
Certified that this is a bonafide record of work done by ANAND KUMAR, Reg. No.
24100336, MCA Semester-II, during the sessions of 22-382-0206 Java Lab in the Department
of Computer Applications, Cochin University of Science and Technology.

Faculty in Charge Head of the Department


List of Titles for Lab Record

Sl No Title

1. SADDLE POINTS OF A MATRIX

2. CHARACTER COUNT

3. ROOTS OF A QUADRATIC EQUATION

4. COMMAND LINE ADDITION

5. AREA OF RECTANGLE & CIRCLE

6. AREA OF A CIRCLE FROM COORDINATES

7. STUDENT DATABASE

8. MATRIX ADDITION

9. POLYNOMIAL ADDITION

10. METHOD OVERLOADING

11. THE CONSTRUCTOR

12. INHERITANCE

13. METHOD OVERRIDING

14. ABSTRACT CLASSES

15. INTERFACES

16. GUI
17. EXCEPTION HANDLING

18. MULTITHREADING

19. MUTUAL EXCLUSION BY THREADS


Program No: 1

SADDLE POINT OF A MATRIX

Problem:
Write a Java program to print the saddle point of an integer matrix.

Program:
import java.io.*;
import java.util.Scanner;
class SaddlePoint
{
public static void main(String args[])
{
int a[][]=new int[10][10],r,c;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the row limit:");
r=sc.nextInt();
System.out.print("Enter the column limit:");
c=sc.nextInt();
System.out.println("Enter the numbers:");
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
a[i][j]=sc.nextInt();
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
System.out.print(" "+a[i][j]);
}
System.out.println();
}
System.out.println();

//for getting Saddle Point


for(int i=0;i<r;i++)
{
int min_row=a[i][0], col_ind=0;
for(int j=1;j<c;j++)
{
if(min_row>a[i][j])
{
min_row=a[i][j];
col_ind=j;
}
}
int k;
for(k=0;k<r;k++)
{
if(min_row<a[k][col_ind])
break;
}
if(k==r)
{
System.out.println("Value of Saddle Point
"+min_row);
System.exit(0);
}
}
System.out.println("No Saddle Point");
}
}

OUTPUT:
OUTPUT-1
--------------------
Enter the row limit:3
Enter the column limit:3
Enter the numbers:
1
2
3
4
5
6
7
8
9
1 2 3
4 5 6
7 8 9

Value of Saddle Point 7

OUTPUT-2
-------------------------
Enter the row limit:3
Enter the column limit:3
Enter the numbers:
1
2
3
4
5
6
10
18
4
1 2 3
4 5 6
10 18 4

No Saddle Point
OUTPUT-3
------------------------
Enter the row limit:3
Enter the column limit:3
Enter the numbers:
4
16
12
2
8
14
1
3
6
4 16 12
2 8 14
1 3 6

Value of Saddle Point 4


Program No: 2

CHARACTER COUNT

Problem

Program to print the number of occurrences of each character of a string.

Program:
import java.io.*;
import java.util.Scanner;
class OccurrenceOfChar
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string:");
String inputString=sc.nextLine();
sc.close();
int[] charOccurrences=new int[256];
for(int i=0;i< inputString.length();i++)
{
char currentChar=inputString.charAt(i);
charOccurrences[currentChar]++;
}
System.out.println("Occurrences of each character:");
for(int i=0;i< charOccurrences.length;i++)
if(charOccurrences[i]>0)
{
System.out.println((char) i + " : " +
charOccurrences[i]);
}
}
}

OUTPUT:
OUTPUT-1
---------------------------
Enter a string:Ashutosh
Occurrences of each character:
A : 1
h : 2
o : 1
s : 2
t : 1
u : 1
OUTPUT-2
----------------------------
Enter a string:Aashutosh
Occurrences of each character:
A : 1
a : 1
h : 2
o : 1
s : 2
t : 1
u : 1
OUTPUT-3
-------------------------------
Enter a string:Aashutosh kumar
Occurrences of each character:
: 1
A : 1
a : 2
h : 2
k : 1
m : 1
o : 1
r : 1
s : 2
t : 1
u : 2
Program No:3

ROOTS OF A QUADRATIC EQUATION

Problem:
Program to find the roots of a quadratic equation. The coefficients and the constant are given.

Program:
import java.io.*;
import java.util.Scanner;
import java.lang.Math;
class quadratic
{
public static void main(String args[])
{
double a,b,c,d,roots,root1,root2;
System.out.print("Enter coefficient of x2:");
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
System.out.print("Enter coefficient of x:");
b=sc.nextInt();
System.out.print("Enter the constant:");
c=sc.nextInt();
d=Math.sqrt(b*b-4*a*c);
if(d==0)
{
System.out.print("Equation will have unique
solution:"+(roots=(-b+d)/(2*a)));
}
else if(d>0)
{
System.out.print("First root:"+(root1=(-
b+d)/(2*a)));
System.out.print("Second root:"+(root2=(-b-
d)/(2*a)));
}
else
{
System.out.println("Imaginary roots");
}
}
}

OUTPUT:
Enter coefficient of x2:1
Enter coefficient of x:-4
Enter the constant:4
Equation will have unique solution:2.0
Program No: 4

COMMAND LINE ADDITION


Problem:
Program to add two real numbers. Read the input as command line arguments.

Program:
import java.io.*;
import java.util.Scanner;
class sum_of_two_numbers
{
public static void main(String args[])
{
double num1,num2;
System.out.print("Enter first number:");
Scanner sc=new Scanner(System.in);
num1=sc.nextDouble();
System.out.print("Enter second number:");
num2=sc.nextDouble();
//System.out.println("Sum: "+(num1 + num2));
System.out.printf("Sum: %.2f\n",num1 + num2);
}
}

OUTPUT:
Enter first number:4.6
Enter second number:2.62
Sum: 7.22
Program No: 5

AREA OF A RECTANGLE & CIRCLE

Problem:
Menu driven program to calculate the area of a rectangle from its length and width and that of
a circle from its radius.

Class Design
class Rectangle
● Properties
○ length, breadth.
● Methods
○ SetSides(): To assign values to the properties
○ calcArea(): To calculate and print the area of the rectangle
area=length*breadth
print(area)
class Circle
● Properties
○ radius.
● Methods
○ SetSides(): To assign values to the properties
○ calcCirArea(): To calculate and print the area of the circle
area=3.14*radius*radius
print(area)

Program:
import java.io.*;
import java.util.Scanner;
class Rectangle
{
double length,breadth;
void setSides(double l,double b)
{
this.length=l;
this.breadth=b;
}
void calcRecArea()
{
double area;
area=length*breadth;
System.out.println("Area of the rectangle="+area);
}
}
class Circle
{
double radius;
void setSides(double r)
{
this.radius=r;
}
void calCirArea()
{
double area;
area=3.14*radius*radius;
System.out.println("Area of the circle="+area);
}
}

class Area_of_Rect_Circ
{
public static void main(String args[])
{
int choice;
double l,b,r;
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.println("1:Area of the
Rectangle:\n2:Area of Circle:\n..........");
choice=sc.nextInt();
switch(choice)
{
case 1: System.out.print("Enter the length and
breadth of the rectagle:");
Rectangle rect=new Rectangle();
l=sc.nextDouble();
b=sc.nextDouble();
rect.setSides(l,b);
rect.calcRecArea();
break;
case 2: System.out.println("Enter the radius
of the circle:");
Circle cir=new Circle();
r=sc.nextDouble();
cir.setSides(r);
cir.calCirArea();
break;
case 3:System.exit(0);
}
}
}
}

OUTPUT:
1:Area of the Rectangle:
2:Area of Circle:
..........
1
Enter the length and breadth of the rectagle:2 3
Area of the rectangle=6.0
1:Area of the Rectangle:
2:Area of Circle:
..........
2
Enter the radius of the circle:
3
Area of the circle=28.259999999999998
1:Area of the Rectangle:
2:Area of Circle:
..........
3
Program No: 6

AREA OF A CIRCLE FROM COORDINATES


Problem:
Program to calculate the area of a circle given the coordinates of its centre and that of a point
on its boundary.

Program:
import java.util.Scanner;
class Circle_area_coordinates
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the x-coordinates of the
center:");
double centerX=sc.nextDouble();
System.out.print("Enter the y-coordinates of the
center:");
double centerY=sc.nextDouble();

System.out.print("Enter the x-coordinate of a point on


the boundary:");
double pointX=sc.nextDouble();
System.out.print("Enter the y-coordinates of a point
on the boundary:");
double pointY=sc.nextDouble();

double radius=calculateDistance(centerX, centerY,


pointX, pointY);
double area=calculateCircleArea(radius);
System.out.println("The area of the circle is:
"+area);
sc.close();
}
private static double calculateDistance(double x1, double
y1, double x2, double y2)
{
return Math.sqrt(Math.pow(x2 - x1,2) + Math.pow(y2 -
y1,2));
}

private static double calculateCircleArea(double radius)


{
return Math.PI * Math.pow(radius,2);
}
}

OUTPUT:

Enter the x-coordinates of the center:0


Enter the y-coordinates of the center:0
Enter the x-coordinate of a point on the boundary:3
Enter the y-coordinates of a point on the boundary:4
The area of the circle is: 78.53981633974483
Program No: 7

STUDENT DATABASE

Problem:
Program to store student data which include name, register number and marks obtained in 4
subjects and to print the results. The result should contain name, register number, marks,
passed/failed per subject, passed/failed in the whole examination and total marks if passed in
all the subjects. The maximum total per subject is 50 and 25 is required for a pass.
Class Design
class student
● Properties
○ name, reg, m1, m2, m3, m4, sum.
● Methods
○ setter(): To assign values to the properties
○ printData(): To print the name , registration number, marks and
result.

Program:
import java.io.*;
import java.util.Scanner;
class Student
{
String name,reg;
double m1,m2,m3,m4,sum;
void setter(String name,String reg,double m1,double
m2,double m3,double m4)
{
this.name=name;
this.reg=reg;
this.m1=m1;
this.m2=m2;
this.m3=m3;
this.m4=m4;
}
void printData()
{
System.out.println("Name: "+this.name);
System.out.println("Registration No.: "+this.reg);
if(m1>=25)
{
System.out.println("Marks of subject1="+m1 +
"\tPass");
}
else
{
System.out.println("Marks of subject1="+m1 +
"\tFail");
}
if(m2>=25)
{
System.out.println("Marks of subject2="+m2 +
"\tPass");
}
else
{
System.out.println("Marks of subject1="+m2 +
"\tFail");
}
if(m3>=25)
{
System.out.println("Marks of subject3="+m3 +
"\tPass");
}
else
{
System.out.println("Marks of subject1="+m3 +
"\tFail");
}
if(m4>=25)
{
System.out.println("Marks of subject4="+m4 +
"\tPass");
}
else
{
System.out.println("Marks of subject1="+m4 +
"\tFail");
}

if((this.m1 >=25 && this.m2>=25 && this.m3>=25 &&


this.m4>=25))
{
System.out.println("\nResult:-\t Pass"+"\nTotal
Marks="+(this.m1 + this.m2 + this.m3 + this.m4)+"\n");
}
else
{
System.out.println("\nResult:-\tFail\n");
}
}
}
class Q7
{
public static void main(String args[])
{
int num;
double m1,m2,m3,m4,sum;
String name,reg;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of Student:");
num=sc.nextInt();
Student studData[]=new Student[num];
for(int i=0;i<num;i++)
{
sc.nextLine();
System.out.print("Name:");
name=sc.nextLine();
System.out.print("Registration Number:");
reg=sc.nextLine();
System.out.print("Enter marks of subject1 upto
50:");
m1=sc.nextDouble();
System.out.print("Enter marks of subject2 upto
50:");
m2=sc.nextDouble();
System.out.print("Enter marks of subject3 upto
50:");
m3=sc.nextDouble();
System.out.print("Enter mark of subject4 upto
50:");
m4=sc.nextDouble();
studData[i]=new Student();
studData[i].setter(name,reg,m1,m2,m3,m4);

}
System.out.println("\n------------Student Data as
follows-------------");
for(Student stud:studData)
{
stud.printData();
}
}
}

OUTPUT:

Enter the number of Student:2


Name:abc
Registration Number:R01
Enter marks of subject1 upto 50:50
Enter marks of subject2 upto 50:26
Enter marks of subject3 upto 50:50
Enter mark of subject4 upto 50:50
Name:efg
Registration Number:R02
Enter marks of subject1 upto 50:50
Enter marks of subject2 upto 50:25
Enter marks of subject3 upto 50:12
Enter mark of subject4 upto 50:32

------------Student Data as follows-------------


Name: abc
Registration No.: R01
Marks of subject1=50.0 Pass
Marks of subject2=26.0 Pass
Marks of subject3=50.0 Pass
Marks of subject4=50.0 Pass

Result:- Pass
Total Marks=176.0

Name: efg
Registration No.: R02
Marks of subject1=50.0 Pass
Marks of subject2=25.0 Pass
Marks of subject1=12.0 Fail
Marks of subject4=32.0 Pass

Result:- Fail
PROGRAM No: 8
MATRIX ADDITION
Problem:
Write a java program to add two integer matrices.

Program:
import java.util.Scanner;

class Matrix
{
private int rows;
private int cols;
private int[][] matrix;

public Matrix(int rows, int cols)


{
this.rows = rows;
this.cols = cols;
matrix = new int[rows][cols];
}

public void readMatrix()


{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter elements of the matrix:");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = scanner.nextInt();
}
}
}

public Matrix add(Matrix other)


{
if (this.rows != other.rows || this.cols !=
other.cols)
{
System.out.println("Error: Matrices must have the
same dimensions for addition.");
return null;
}

Matrix sum = new Matrix(rows, cols);


for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
sum.matrix[i][j] = this.matrix[i][j] +
other.matrix[i][j];
}
}
return sum;
}

public void printMatrix()


{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

class Main
{

public static void main(String[] args)


{
Scanner scanner = new Scanner(System.in);

System.out.println("Enter dimensions of Matrix 1 (rows


cols): ");
int rows1 = scanner.nextInt();
int cols1 = scanner.nextInt();

System.out.println("Enter dimensions of Matrix 2 (rows


cols): ");
int rows2 = scanner.nextInt();
int cols2 = scanner.nextInt();

if (rows1 != rows2 || cols1 != cols2)


{
System.out.println("Error: Matrices must have the
same dimensions for addition.");
return;
}

Matrix matrix1 = new Matrix(rows1, cols1);


matrix1.readMatrix();

Matrix matrix2 = new Matrix(rows2, cols2);


matrix2.readMatrix();

Matrix sum = matrix1.add(matrix2);

if (sum != null)
{
System.out.println("Sum of matrices:");
sum.printMatrix();
}
}
}

OUTPUT:
Enter dimensions of Matrix 1 (rows cols):
3 3
Enter dimensions of Matrix 2 (rows cols):
3 3
Enter elements of the matrix:
1 1 1
2 2 2
3 3 3
Enter elements of the matrix:
7 7 7
8 8 8
9 9 9
Sum of matrices:
8 8 8
10 10 10
12 12 12
Program No: 9
Quadratic Polynomial Addition
Problem:
Write a java program to print the quadratic polynomial addition.

Program:

import java.io.*;
import java.util.Scanner;

class Polynomial
{
double quad,linear,constant;
void setValues(double a,double b,double c)
{
this.quad=a;
this.linear=b;
this.constant=c;
}

Polynomial add(Polynomial obj)


{
Polynomial sum=new Polynomial();
sum.quad=this.quad + obj.quad;
sum.linear=this.linear + obj.linear;
sum.constant=this.constant + obj.constant;
return sum;
}

void printSelf()
{
System.out.println("X^2("+quad+")+x("+linear+")+"+constant);
}
}

class main
{
public static void main(String args[])
{
double quad,linear,constant;
Scanner s=new Scanner(System.in);
System.out.println("Polynomial-1");
System.out.println("Enter the coefficients:");
quad=s.nextDouble();
linear=s.nextDouble();
constant=s.nextDouble();

Polynomial P1=new Polynomial();


P1.setValues(quad,linear,constant);

System.out.println("Polynomial-2");
System.out.println("Enter the coefficients:");
quad=s.nextDouble();
linear=s.nextDouble();
constant=s.nextDouble();

Polynomial P2=new Polynomial();


P2.setValues(quad,linear,constant);
System.out.println();
System.out.println("Polynomial-1");
P1.printSelf();
System.out.println();
System.out.println("Polynomial-2");
P2.printSelf();

Polynomial sum=P1.add(P2);
System.out.print("Sum:");
sum.printSelf();
}
}

OUTPUT:
-------------------------
Polynomial-1
Enter the coefficients:
5 2 3
Polynomial-2
Enter the coefficients:
6 3 8

Polynomial-1
X^2(5.0)+x(2.0)+3.0

Polynomial-2
X^2(6.0)+x(3.0)+8.0
Sum:X^2(11.0)+x(5.0)+11.0
Program No: 10
METHOD OVERLOADING
Problem:
Menu driven program to calculate the perimeter of rectangles and squares. Write class
Rectangle with overloaded setter methods to assign the side values of rectangle and square
methods.

Program:
import java.io.*;
import java.util.Scanner;
class Rectangle
{
double length,breadth;
void setSides(double a)
{
this.length=a;
this.breadth=a;
}
void setSides(double a,double b)
{
this.length=a;
this.breadth=b;
}
void calcPerimeter()
{
double peri;
peri=2*(length + breadth);
System.out.println("Perimeter: "+peri);
}
}
class record10
{
public static void main(String args[])
{
int choice;
double l,b;
Scanner s=new Scanner(System.in);
while(true)
{
System.out.println("1:Perimeter of Rectangle.
\n2:Perimter of Square. \n3.Enter to
exit.\n..................");
choice=s.nextInt();
switch(choice)
{
case 1:System.out.print("Enter the lenght and
breadth of Rectangle: ");
Rectangle rect=new Rectangle();
l=s.nextDouble();
b=s.nextDouble();
rect.setSides(l,b);
rect.calcPerimeter();
break;
case 2:System.out.println("Enter the side of
square: ");
Rectangle sqr=new Rectangle();
l=s.nextDouble();
sqr.setSides(l);
sqr.calcPerimeter();
break;
case 3: System.exit(0);
}
}

}
}

OUTPUT:
1:Perimeter of Rectangle.
2:Perimter of Square.
3.Enter to exit.
..................
1
Enter the lenght and breadth of Rectangle: 20 2
Perimeter: 44.0
1:Perimeter of Rectangle.
2:Perimter of Square.
3.Enter to exit.
..................
2
Enter the side of square:
10
Perimeter: 40.0
1:Perimeter of Rectangle.
2:Perimter of Square.
3.Enter to exit.
..................
3
Program No:11
THE CONSTRUCTOR
Problem:
Implement the scenario given in question 13 by replacing the setter methods with overloaded
constructors.

Program:
import java.util.Scanner;

class Student {
protected String name;
protected int[] marks;

// Constructor for students without an additional subject


public Student(String name, int mark1, int mark2, int
mark3, int mark4, int mark5) {
this.name = name;
this.marks = new int[]{mark1, mark2, mark3, mark4,
mark5};
}

// Constructor for students with an additional subject


public Student(String name, int mark1, int mark2, int
mark3, int mark4, int mark5, int mark6) {
this.name = name;
this.marks = new int[]{mark1, mark2, mark3, mark4,
mark5, mark6};
}

// Method to calculate total marks


public int calculateTotalMarks() {
int total = 0;
for (int mark : marks) {
total += mark;
}
return total;
}

// Method to calculate average marks


public double calculateAverageMarks() {
return calculateTotalMarks() / (double) marks.length;
}

// Method to compute grades


public String computeGrade() {
double average = calculateAverageMarks();
if (average >= 90) {
return "A+";
} else if (average >= 80) {
return "A";
} else if (average >= 70) {
return "B";
} else if (average >= 60) {
return "C";
} else if (average >= 50) {
return "D";
} else {
return "F";
}
}

// Display student information


public void displayInfo() {
System.out.println("Student Name: " + name);
System.out.println("Marks:");
for (int i = 0; i < marks.length; i++) {
System.out.println("Subject " + (i + 1) + ": " +
marks[i]);
}
System.out.println("Total Marks: " +
calculateTotalMarks());
System.out.println("Average Marks: " +
calculateAverageMarks());
System.out.println("Grade: " + computeGrade());
}
}

public class record11 {


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

// Input for students without additional subject


System.out.println("Enter details for student without
additional subject:");
System.out.print("Name: ");
String name1 = scanner.nextLine();
System.out.print("Enter marks for 5 subjects: ");
int mark1 = scanner.nextInt();
int mark2 = scanner.nextInt();
int mark3 = scanner.nextInt();
int mark4 = scanner.nextInt();
int mark5 = scanner.nextInt();

// Create object for student without additional


subject
Student student1 = new Student(name1, mark1, mark2,
mark3, mark4, mark5);

// Input for students with additional subject


System.out.println("\nEnter details for student with
additional subject:");
scanner.nextLine(); // Consume newline
System.out.print("Name: ");
String name2 = scanner.nextLine();
System.out.print("Enter marks for 6 subjects: ");
int mark6 = scanner.nextInt();

// Create object for student with additional subject


Student student2 = new Student(name2, mark1, mark2,
mark3, mark4, mark5, mark6);

// Display information for both students


System.out.println("\nStudent without additional
subject:");
student1.displayInfo();

System.out.println("\nStudent with additional


subject:");
student2.displayInfo();

scanner.close();
}
}

OUTPUT:
---------------------------------------------------------------
Enter details for student without additional subject:
Name: Aman
Enter marks for 5 subjects: 50
55
66
22
22

Enter details for student with additional subject:


Name: Patel
Enter marks for 6 subjects: 88

Student without additional subject:


Student Name: Aman
Marks:
Subject 1: 50
Subject 2: 55
Subject 3: 66
Subject 4: 22
Subject 5: 22
Total Marks: 215
Average Marks: 43.0
Grade: F

Student with additional subject:


Student Name: Patel
Marks:
Subject 1: 50
Subject 2: 55
Subject 3: 66
Subject 4: 22
Subject 5: 22
Subject 6: 88
Total Marks: 303
Average Marks: 50.5
Grade: D
Program No:12
INHERITANCE
Problem:
In an organization there are two types of employees. Normal employees and a manager who
is above the normal employees. Consider a scenario where the employees can access and
print their own personal data. Manager being an employee can also do the same. Additionally
the manager can print the details of any employee under him/her. Implement the scenario
using inheritance.
Program:
import java.io.*;
import java.util.Scanner;
class Employee
{
String name,empId;
void setEmpData(String a,String b)
{
this.name=a;
this.empId=b;
}
void printSelf()
{
System.out.println("\nName: "+ this.name);
System.out.println("Employee Id: "+this.empId);
}
}

class Manager extends Employee


{
void printEmpData(Employee obj)
{
System.out.println("Name: "+obj.name);
System.out.println("Employee Id: "+obj.empId);
}
}
public class record11
{
public static void main(String args[])
{
Employee emp=new Employee();
emp.setEmpData("Anu","emp01");

System.out.println("Employee Data(self)");
emp.printSelf();

Manager m=new Manager();


m.setEmpData("Raju","emp05");

System.out.println("\nManager Data(self)\n......");
m.printSelf();

System.out.println("\nEmployee Data(Manager)\n.....");
m.printEmpData(emp);
}

OUTPUT:
Employee Data(self)

Name: Anu
Employee Id: emp01

Manager Data(self)
......

Name: Raju
Employee Id: emp05

Employee Data(Manager)
.....
Name: Anu
Employee Id: emp01
Program No:13
METHOD OVERRIDING
Problem:
For a school final board examination, the students should take five subjects. And, if the
student is interested, he/she can opt an additional subject thereby making it a total of six
subjects. To compute the grades the scores of all the 5 will be considered for students without
an additional subject and for the students with an additional subject, the best five marks out
of six will be considered. Implement the scenario using inheritance. Assume any suitable
formula for computing the grades

Program:
import java.util.Scanner;

abstract class Student {


protected String name;
protected int[] marks = new int[6]; // Maximum 6 subjects

public Student(String name) {


this.name = name;
}

public abstract void inputMarks();

public char calculateGrade() {


int totalMarks = 0;
int bestFive = 0;

// Calculate total marks for all subjects


for (int mark : marks) {
totalMarks += mark;
}
// Find the best five marks (considering additional
subject if present)
for (int i = 0; i < 5; i++) {
int maxIndex = i;
for (int j = i + 1; j < marks.length; j++) {
if (marks[j] > marks[maxIndex]) {
maxIndex = j;
}
}
bestFive += marks[maxIndex];
}

// Calculate average based on best five marks


(considering additional subject)
double average = (double) bestFive / (marks.length > 5
? 5 : marks.length);

// Assign grade based on a sample formula (you can


customize this)
if (average >= 90) {
return 'A';
} else if (average >= 80) {
return 'B';
} else if (average >= 70) {
return 'C';
} else if (average >= 60) {
return 'D';
} else {
return 'F';
}
}
public void printResult() {
System.out.println("Name: " + name);
System.out.println("Grade: " + calculateGrade());
}
}

class RegularStudent extends Student {

public RegularStudent(String name) {


super(name);
}

@Override
public void inputMarks() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter marks for " + name + " (5
subjects):");
for (int i = 0; i < 5; i++) {
marks[i] = scanner.nextInt();
}
}
}

class ExtraSubjectStudent extends Student {

public ExtraSubjectStudent(String name) {


super(name);
}

@Override
public void inputMarks() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter marks for " + name + " (6
subjects):");
for (int i = 0; i < 6; i++) {
marks[i] = scanner.nextInt();
}
}
}

public class Main {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter name of student with 5


subjects: ");
Student regularStudent = new
RegularStudent(scanner.nextLine());
regularStudent.inputMarks();

System.out.print("\nEnter name of student with 6


subjects: ");
Student extraSubjectStudent = new
ExtraSubjectStudent(scanner.nextLine());
extraSubjectStudent.inputMarks();

System.out.println("\nResults:");
regularStudent.printResult();
extraSubjectStudent.printResult();
}
}
OUTPUT:
Enter name of student with 5 subjects: Aman
Enter marks for Aman (5 subjects):
55
66
45
55
15

Enter name of student with 6 subjects: Patel


Enter marks for Patel (6 subjects):
85
95
75
66
88
99

Results:
Name: Aman
Grade: F
Name: Patel
Grade: A
Program No:14

Abstract Classes
Problem:
In an organization, there are different classes of employees.
Consider the activities of reading the employee data (Name,
Employee Id & Basic Pay) and calculating the salary.

Take two types of employees; manager and assistant manager.

Manager
Basic pay : Read from user
DA(Dearness allowance)=50% of basic pay
HRA(House Rent Allowance)=10000 rupees
TA (Travel Allowance)= 5000
Salary=Basic pay+DA+TA+HRA

Assistant Manager
Basic pay : Read from user(input a value that is less than the
basic pay of manager)
DA(Dearness allowance)=40% of basic pay
HRA(House Rent Allowance)=7000 rupees
TA (Travel Allowance)= 3000
Salary=Basic pay+DA+TA+HRA

Implement the scenario using abstract classes as reading the


employee data needs the same implementation in both the
classes of employees and calculating the salary needs
different implementations in the two classes of employees.
(Abstract Classes)

Program:
import java.util.Scanner;

// Abstract class Employee


abstract class Employee {
protected String name;
protected int employeeId;
protected double basicPay;
// Constructor to read employee data
public Employee(String name, int employeeId, double
basicPay) {
this.name = name;
this.employeeId = employeeId;
this.basicPay = basicPay;
}

// Abstract method to calculate salary


public abstract double calculateSalary();
}

// Concrete class Manager extending Employee


class Manager extends Employee {
// Constants for allowances
private static final double DA_PERCENTAGE = 0.5;
private static final double HRA = 10000;
private static final double TA = 5000;

// Constructor for Manager


public Manager(String name, int employeeId, double
basicPay) {
super(name, employeeId, basicPay);
}

// Method to calculate salary for Manager


@Override
public double calculateSalary() {
double da = basicPay * DA_PERCENTAGE;
return basicPay + da + HRA + TA;
}
}
// Concrete class AssistantManager extending Employee
class AssistantManager extends Employee {
// Constants for allowances
private static final double DA_PERCENTAGE = 0.4;
private static final double HRA = 7000;
private static final double TA = 3000;

// Constructor for AssistantManager


public AssistantManager(String name, int employeeId,
double basicPay) {
super(name, employeeId, basicPay);
}

// Method to calculate salary for AssistantManager


@Override
public double calculateSalary() {
double da = basicPay * DA_PERCENTAGE;
return basicPay + da + HRA + TA;
}
}

public class record14 {


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

// Read manager details


System.out.println("Enter details for Manager:");
System.out.print("Name: ");
String managerName = scanner.nextLine();
System.out.print("Employee ID: ");
int managerId = scanner.nextInt();
System.out.print("Basic Pay: ");
double managerBasicPay = scanner.nextDouble();

// Create Manager object


Manager manager = new Manager(managerName, managerId,
managerBasicPay);

// Read assistant manager details


scanner.nextLine(); // Consume newline
System.out.println("\nEnter details for Assistant
Manager:");
System.out.print("Name: ");
String assistantManagerName = scanner.nextLine();
System.out.print("Employee ID: ");
int assistantManagerId = scanner.nextInt();
System.out.print("Basic Pay (less than Manager): ");
double assistantManagerBasicPay =
scanner.nextDouble();

// Create AssistantManager object


AssistantManager assistantManager = new
AssistantManager(assistantManagerName, assistantManagerId,
assistantManagerBasicPay);

// Display salaries
System.out.println("\nManager Salary:");
System.out.println("Salary: $" +
manager.calculateSalary());

System.out.println("\nAssistant Manager Salary:");


System.out.println("Salary: $" +
assistantManager.calculateSalary());
scanner.close();
}
}

OUTPUT:
-----------------------------------------------
Enter details for Manager:
Name: Manjesh
Employee ID: 01
Basic Pay: 500000

Enter details for Assistant Manager:


Name: Ajesh
Employee ID: 02
Basic Pay (less than Manager):450000

Manager Salary:
Salary: $765000.0

Assistant Manager Salary:


Salary: $80000.0
Program No:15
INTERFACES
Problem:
Program to calculate the area and perimeter of squares and circles satisfying the following
requirements.

• Define an interface with methods calcArea(double val) & calcPerimeter(double val).


• Create classes Square and Circle which implement these methods to find the area and
perimeter of the respective shapes.

Program:
// Define interface Shape
interface Shape {
double calcArea(double val);
double calcPerimeter(double val);
}

// Class Square implementing Shape interface


class Square implements Shape {
@Override
public double calcArea(double side) {
return side * side;
}

@Override
public double calcPerimeter(double side) {
return 4 * side;
}
}

// Class Circle implementing Shape interface


class Circle implements Shape {
// Constant for PI value
private static final double PI = 3.14159;

@Override
public double calcArea(double radius) {
return PI * radius * radius;
}

@Override
public double calcPerimeter(double radius) {
return 2 * PI * radius;
}
}

public class record15 {


public static void main(String[] args) {
Square square = new Square();
Circle circle = new Circle();

// Calculate area and perimeter of square


double squareSide = 5.0;
double squareArea = square.calcArea(squareSide);
double squarePerimeter =
square.calcPerimeter(squareSide);

// Calculate area and perimeter of circle


double circleRadius = 3.0;
double circleArea = circle.calcArea(circleRadius);
double circlePerimeter =
circle.calcPerimeter(circleRadius);
// Display results
System.out.println("Square - Area: " + squareArea + ",
Perimeter: " + squarePerimeter);
System.out.println("Circle - Area: " + circleArea + ",
Perimeter: " + circlePerimeter);
}
}

OUTPUT:
----------------------------------------------------
Square - Area: 25.0, Perimeter: 20.0
Circle - Area: 28.274309999999996, Perimeter:
18.849539999999998
Program No:16
GUI
Problem:
Program to create a GUI based application to calculate the sum of two real numbers. Show
the sum on a message box.

Program:
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
class GUI implements ActionListener
{
JFrame frame;
JTextField text1,text2;
GUI()
{
frame=new JFrame();
frame.setSize(250,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setTitle("My Application");

JLabel label=new JLabel("First Number:");


frame.setLayout(new FlowLayout());
text1=new JTextField(10);
frame.add(label);
frame.add(text1);

JLabel label2=new JLabel("Second Number:");


text2=new JTextField(10);
frame.add(label2);
frame.add(text2);

JButton button=new JButton("ADD");


button.addActionListener(this);
frame.add(button);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
float num1,num2;
String s;
s=text1.getText();
num1=Float.parseFloat(s);

s=text2.getText();
num2=Float.parseFloat(s);

JOptionPane.showMessageDialog(null,"SUM="+(num1+num2),"Result"
,JOptionPane.PLAIN_MESSAGE,null);
}
}
public class record17 {
public static void main(String args[])
{
new GUI();
}
}

OUTPUT:
Program No:17
EXCEPTION HANDLING
Problem:
Program to implement the scenario in which a user has to enter the percentage score of
undergraduate studies. Consider two cases where a user enters a negative value and a value
greater than 100. Write custom Java exception classes and handling routines to separately
handle both these cases.

Program:
// Custom exception for negative percentage score
class NegativePercentageException extends Exception {
public NegativePercentageException(String message) {
super(message);
}
}

// Custom exception for percentage score greater than 100


class InvalidPercentageException extends Exception {
public InvalidPercentageException(String message) {
super(message);
}
}

// Main class to handle user input and exceptions


public class record16 {
public static void main(String[] args) {
try {
// Get user input for percentage score
double percentage = getUserInput();

// Check for negative percentage


if (percentage < 0) {
throw new
NegativePercentageException("Percentage cannot be negative!");
}

// Check for percentage greater than 100


if (percentage > 100) {
throw new
InvalidPercentageException("Percentage cannot be greater than
100!");
}

// Display percentage
System.out.println("Entered percentage: " +
percentage + "%");
} catch (NegativePercentageException e) {
System.out.println("Error: " + e.getMessage());
} catch (InvalidPercentageException e) {
System.out.println("Error: " + e.getMessage());
}
}

// Method to get user input for percentage score


public static double getUserInput() {
java.util.Scanner scanner = new
java.util.Scanner(System.in);

System.out.print("Enter your percentage score: ");


double percentage = scanner.nextDouble();

scanner.close();

return percentage;
}
}

OUTPUT:
--------------------------------------------
Output 1
Enter your percentage score: 98
Entered percentage: 98.0%
Output 2
Enter your percentage score: -89

Error: Percentage cannot be negative!


Program No: 18
MULTITHREADING
Problem:
Program to create two threads where one thread prints odd numbers and the other even
numbers both from the same range.

Program:
class OddEvenPrinter {
private int max;
private boolean isOdd;
private Object lock = new Object();

public OddEvenPrinter(int max, boolean isOdd) {


this.max = max;
this.isOdd = isOdd;
}

public void printNumbers() {


int start = isOdd ? 1 : 2;
while (start <= max) {
synchronized (lock) {

System.out.println(Thread.currentThread().getName() + ": " +


start);
start += 2;
lock.notify(); // Notify the other thread that
the number has been printed
try {
if (start <= max) {
lock.wait(); // Wait for the other
thread to print its number
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

public class record18 {


public static void main(String[] args) {
OddEvenPrinter printer = new OddEvenPrinter(20, true);

Thread oddThread = new Thread(() -> {


printer.printNumbers();
}, "OddThread");

Thread evenThread = new Thread(() -> {


printer.printNumbers();
}, "EvenThread");

oddThread.start();
evenThread.start();
}
}

OUTPUT:
----------------------------
OddThread: 1
EvenThread: 1
OddThread: 3
EvenThread: 3
OddThread: 5
EvenThread: 5
OddThread: 7
EvenThread: 7
OddThread: 9
EvenThread: 9
OddThread: 11
EvenThread: 11
OddThread: 13
EvenThread: 13
OddThread: 15
EvenThread: 15
OddThread: 17
EvenThread: 17
OddThread: 19
EvenThread: 19
Program No:19
MUTUAL EXCLUSION BY THREADS
Problem:
Program to implement mutual exclusion of threads on accessing a shared object using
synchronized().

Program:

//Synchronization in multithreading.....

import java.io.*;
class CommonObj
{
//synchronized void printMessage(String thread)
void printMessage(String thread)
{
System.out.print("{");
System.out.print("Hi.. from "+thread);
System.out.println("}");
}
}
class UserThread extends Thread
{
String name;
CommonObj Object;
UserThread(String name,CommonObj ob)
{
this.name=name;
this.Object=ob;
}
public void run()
{
synchronized(Object) //Synchronized block
{
this.Object.printMessage(this.name);
}
}
}
class lab13_03__2
{
public static void main(String[] a )
{
CommonObj obj=new CommonObj();
UserThread t_1=new UserThread("First",obj);
UserThread t_2=new UserThread("Second",obj);
UserThread t_3=new UserThread("Third",obj);

t_1.start();
t_2.start();
t_3.start();
}
}

OUTPUT:
-------------------------
{Hi.. from First}
{Hi.. from Third}
{Hi.. from Second}

You might also like