[go: up one dir, main page]

0% found this document useful (0 votes)
2 views117 pages

Java Programming Lab Manual (3)

The document outlines the structure and curriculum of the Java Programming Laboratory course at K S R Institute for Engineering and Technology, detailing the vision, mission, program outcomes, and specific experiments to be conducted. It includes a certificate template for students, a list of experiments, and sample Java programs demonstrating various programming concepts. The document emphasizes the development of technical skills and ethical values in Information Technology education.

Uploaded by

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

Java Programming Lab Manual (3)

The document outlines the structure and curriculum of the Java Programming Laboratory course at K S R Institute for Engineering and Technology, detailing the vision, mission, program outcomes, and specific experiments to be conducted. It includes a certificate template for students, a list of experiments, and sample Java programs demonstrating various programming concepts. The document emphasizes the development of technical skills and ethical values in Information Technology education.

Uploaded by

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

K S R INSTITUTE FOR ENGINEERING AND TECHNOLOGY

AN AUTONOMOUS INSTITUTION

TIRUCHENGODE – 637 215

Approved by AICTE,New Delhi


Affiliated to Anna University,
Chennai

Accredited by NBA & NAAC with A+ Grade


DEPARTMENT OF INFORMATION TECHNOLOGY

23CS1341-JAVA PROGRAMMING LABORATORY

NAME :

REGISTER NUMBER :

BRANCH :

YEAR / SEM :

COURSE :

1
2
K S R INSTITUTE FOR ENGINEERING AND TECHNOLOGY

AN AUTONOMOUS INSTITUTION

TIRUCHENGODE – 637 215

CERTIFICATE

Register No. …………………………………………………………….

Certified that this is a bonafide record of work done by

Selvan/Selvi …………………………………………….. of the ................................. Semester

………………………………………………………………………………………………Branch

during the year 2024-25 in the .............................................................................................. Laboratory.

Staff in-charge Head of the Department

Submitted for the Practical Examination on …………………….

Internal Examiner External Examiner

3
4
CONTENTS
Exp. Faculty
Date Name of the Experiment Page No. Marks
No. Signature

5
CONTENTS
Exp. Faculty
Date Name of the Experiment Page No. Marks
No. Signature

6
VISION & MISSION OF THE INSTITUTE

VISION

 To become a globally recognized Institution in Engineering education, Research and


Entrepreneurship.

MISSION

 Accomplish quality education through improved teaching learning process.


 Enrich technical skills with state of the art laboratories and facilities.
 Enhance research and entrepreneurship activities to meet the industrial and societal
needs.

PROGRAM OUTCOMES (POs)


PO1 Engineering Knowledge PO7 Environment and sustainability
PO2 Problem Analysis PO8 Ethics
PO3 Design/development of solutions PO9 Individual and team work
PO4 Conduct investigations of PO10
Communication
complex problems
PO5 Modern tool usage PO11 Project management and finance
PO6 The Engineer and society PO12 Life-long learning

7
8
K S R INSTITUTE FOR ENGINEERING AND TECHNOLOGY

(An Autonomous Institution) TIRUCHENGODE


DEPARTMENT OF INFORMATION TECHNOLOGY
Vision

To produce competent Information Technology Professionals and Entrepreneurs with ethical values
to meet the global challenges.

Mission
Impart quality education with ethical values in Information Technology through
DM1
improved teaching learning process.
Provide an ambient learning environment using state of the art laboratories and
DM2
facilities.

Encourage research and entrepreneurship activities to meet the dynamic needs of


DM3
Information Technology industry and society.

Program Educational Objectives (PEOs)


PEO Key Words Description
Graduates will be successful professionals in career
PEO 1 by applying the knowledge of mathematics, science
Core Competency
and engineering with appropriate techniques and
modern tools.

Graduates will exhibit soft skills, professional and


PEO 2 Professionalism ethical values and thrust for continuous learning to
maintain professionalism in the IT industries.

Graduates will engage in higher studies and outshine


PEO 3 Higher Studies and
as entrepreneurs through life-long learning which
Entrepreneurship
leads to societal benefits.

9
Program Outcomes (POs)
Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals and an engineering specialization to the IT enabled solution of complex
engineering problems.
Problem Analysis: Identify, analyze and provide solutions to the problems reaching
PO2
substantiated IT enabled conclusions.
Design/Development of Solutions: Design solutions for complex engineering
PO3 problems and design system components or processes that meet the desired needs
within realistic constraints.
Conduct Investigations of complex problems: Use research-based knowledge and research
PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
Modern Tool Usage: Create, select and apply appropriate techniques, resources and
PO5 modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
Environment and Sustainability: Understand the impact of the professional
PO7 engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities
PO8
and norms of engineering practice.
Individual and Team Work: Function effectively as an individual, and as a member or leader
PO9
in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on engineering activities with the
PO10
engineering community and with society.
Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
PO11
member and leader in a team, to manage projects and in multidisciplinary
environments.
Life Long Learning: Recognize the need for, and have the preparation and ability to
PO12 engage in independent and life-long learning in the broadest context of technological
change.

Program Specific Outcomes (PSOs)

Work as Software Engineers for providing solutions to real world


PSO1 Programming Skill
problems using programming languages and open-source software.

Ability to use the web designing skill to establish new solutions for
PSO2 Web Designing Skill
the societal needs.

10
23CS1341-JAVA PROGRAMMING LABORATORY

LIST OF EXPRIMENTS

1.a) Write a simple java program using operators

1.b) Compute sum and average of array elements

1.c) Write a simple java program using a conditional statement

2.a) Develop stack data structures using object and classes

2.b) Develop queue data structures using object and classes

3.a) Write the concepts of inheritance using java program

3.b) Write the concepts polymorphism using java program

4.Develop an application using interface by accessing super class constructors and methods

5.Develop an employee payroll application using java packages

6.Implement exception handling and creation of user defined exception

7.a) Implement program to multi-threading communication in java program

7.b) Implement program to interthread communication in java program

8.a) Develop an application to perform create file operation in java

8.b) Develop an application to perform delete file operation in java

9. Develop an application to demonstrate the features of generic class and interfaces

10.Implement the concepts of collections frameworks

TOTAL : 30 PERIODS

11
12
EX.NO: 1.A
SIMPLE JAVA PROGRAM USING OPERATORS
DATE:

Aim:
To write a simple java program using operators.

Algorithm:
Step1: start the program.

Step2:initialize the variables a and b.

Step3:compute for the sum,sum=a+b.

Step4:compute for the difference,diff=a-b.

Step5:compute for the product,product=a*b.

Step6:compute for the quotient,quotient=a/b.

Step7:end of the program.

Program:
// Java Program to Illustrate Arithmetic Operators

importjava.util.*;

// Class 1
classA {

// Main driver method


publicstaticvoidmain(String args[])
{

inta = 10, b = 4, res;

// printing a and b
System.out.println("a is "+ a + " and b is "+ b);

res = a + b; // addition
System.out.println("a+b is "+ res);

res = a - b; // subtraction
System.out.println("a-b is "+ res);

13
Sample Output:
a is 10 and b is 4
a+b is 14
a-b is 6
a*b is 40
a/b is 2
a%b is 2

14
res = a * b; // multiplication
System.out.println("a*b is "+ res);

res = a / b; // division

System.out.println("a/b is "+ res);

res = a % b; // modulus
System.out.println("a%b is "+ res);
}
}

15
16
PRE LAB QUESTIONS
1.What are the 4 types of arithmetic operators in java?
2.What is the use of addition operator?
3. Define division.
4. Define variables.
5. What is modulus operators in java?

Result:
Thus the above program was executed and verified successfully.

17
18
EX.NO: 1.B
COMPUTE SUM AND AVERAGE OF ARRAY ELEMENTS
DATE:

Aim:

To compute sum and average of array elements.

Algorithm:

Step1: start

Step2:int numbers

Step3:sum=0,

Step4: average = ((double)sum / (double)arrayLength).

Step5:end.

Program:

//Compute Sum and Average of Array Elements

class Main {
public static void main(String[] args) {
int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
int sum = 0;
Double average;
for (int number: numbers) {
sum += number;
}
int arrayLength = numbers.length;
average = ((double)sum / (double)arrayLength);
System.out.println("Sum = " + sum);
System.out.println("Average = " + average);
}
}

19
Sample Output:
Sum = 36
Average = 3.6

20
PRE LAB QUESTIONS
1. What is an array?

2. How do you find the sum and average of elements in an array?


3. What is the formula for sum and average?
4. How to declare an array in java?
5. List out the types of an array.

Result:
Thus the above program was executed and verified successfully.

21
22
EX.NO: 1.C
PROGRAM USING CONDITIONAL STATEMENTS
DATE:

Aim:
To write a simple java program using a conditional statements.

Algorithm:

Step1: start

Step2: int numbers

Step3: read the values

Step4: put the condition and print the output

Step5:end.

IF STATEMENT

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

Sample Output:

x + y is greater than 20

23
24
IF-ELSE STATEMENT

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}

Sample Output:

x + y is greater than 20

IF-ELSE-IF LADDER

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}

25
26
Sample Output:
Delhi

NESTED-IF

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";

if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}

Sample Output:
Delhi

27
28
PRE LAB QUESTIONS
1. What is the syntax for an if statement in Java?

2. How do you write an if-else statement in Java?

3. Provide an example of a nested if-else statement?

4. Define Nested-if.

5. What is conditional statement?

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:
Thus the above program was executed and verified successfully.

29
30
EX.NO: 2.A
DEVELOP STACK DATA STRUCTURES USING OBJECT AND
DATE: CLASSES

Aim:
To develop stack data structures using object and classes.

Algorithm:
Step1:Start
Step2:Create anew stack object called stack using the default constructor.
Step3:Push a four integers on to the stack using the push() method.
Step4:Then pop the elements from the stack is using the pop()method inside a while loop.
Step5:The code creates a stack of integers and pushes 4 integers onto the stack in the order 1
to 4.
Step6:Pop elements from the stack one by one using the pop method(),which removes and
returns the top element of the stack.
Step7:The stack follows a last-in-first-out(LIFO)order,the elements are popped in the reverse
order of insertion,resulting in the out shown above.
Step8:Stop

Program:
Stack implementation in Java
class Stack {
// store elements of stack
private int arr[];
// represent top of stack
private int top;
// total capacity of the stack
private int capacity;

31
32
// Creating a stack
Stack(int size) {
// initialize the array
// initialize the stack variables
arr = new int[size];
capacity = size;
top = -1;
}

// push elements to the top of stack


public void push(int x) {
if (isFull()) {
System.out.println("Stack OverFlow");

// terminates the program


System.exit(1);
}

// insert element on top of stack


System.out.println("Inserting " + x);
arr[++top] = x;
}

// pop elements from top of stack


public int pop() {

// if stack is empty
// no element to pop
if (isEmpty()) {
System.out.println("STACK EMPTY");

33
34
// terminates the program
System.exit(1);
}

// pop element from top of stack


return arr[top--];
}

// return size of the stack


public int getSize() {
return 1;
}

// check if the stack is empty


public Boolean isEmpty() {
return top == -1;
}

// check if the stack is full


public Boolean isFull() {
return top == capacity - 1;
}
public void printStack() {
for (int i = 0; i<= top; i++) {
System.out.print(arr[i] + ", ");
}
}

public static void main(String[] args) {


Stack stack = new Stack(5);

35
Sample Output:
Inserting 1
Inserting 2
Inserting 3
Stack: 1, 2, 3,
After popping out
1, 2,

36
stack.push(1);
stack.push(2);
stack.push(3);

System.out.print("Stack: ");
stack.printStack();

// remove element from stack


stack.pop();
System.out.println("\nAfter popping out");
stack.printStack();
}
}
PRE LAB QUESTIONS
1. What is a stack data structure?
2. What is an a push?
3. What is an a pop?
4. Write the syntax of insert an element.
5. Define stack applications.
MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100
Result:
Thus the above program was executed and verified successfully.

37
38
EX.NO: 2. B
DEVELOP QUEUE DATA STRUCTURES USING OBJECT
AND CLASSES
DATE:

Aim:
To develop queue data structures using object and classes.

Algorithm:
Step1:start
Step2:initialize the variables in main class.
int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;
Step3: check if the queue is full,check if the queue is empty.
Step4:.insert elements to the queue, mark front denote first element of queue.
Step5:insert element at the rear,delete element from the queue.
Step6:if queue is empty,remove element from the front of queue.
Step7:.if the queue has only one element mark next element as the front.display element of
the queue.
Step8:display the front of the queue,display the front of the queue and display the rear of the
queue.
Step9:create an object of Queue class try to delete element from the queue,currently queue is
empty so deletion is not possible.
Step10:insert elements to the queue,6th element can't be added to queue because queue is full
removes element entered first i.e. 1.Now we have just 4 elements.
Step11:end of the program.

39
40
Queue implementation in Java

public class Queue {


int SIZE = 5;
int items[] = new int[SIZE];
int front, rear;

Queue() {
front = -1;
rear = -1;
}

// check if the queue is full


booleanisFull() {
if (front == 0 && rear == SIZE - 1) {
return true;
}
return false;
}

// check if the queue is empty


booleanisEmpty() {
if (front == -1)
return true;
else
return false;
}

// insert elements to the queue


void enQueue(int element) {

41
42
// if queue is full
if (isFull()) {
System.out.println("Queue is full");
}
else {
if (front == -1) {
// mark front denote first element of queue
front = 0;
}

rear++;
// insert element at the rear
items[rear] = element;
System.out.println("Insert " + element);
}
}

// delete element from the queue


int deQueue() {
int element;

// if queue is empty
if (isEmpty()) {
System.out.println("Queue is empty");
return (-1);
}
else {
// remove element from the front of queue
element = items[front];

43
44
// if the queue has only one element
if (front >= rear) {
front = -1;
rear = -1;
}
else {
// mark next element as the front
front++;
}
System.out.println( element + " Deleted");
return (element);
}
}

// display element of the queue


void display() {
int i;
if (isEmpty()) {
System.out.println("Empty Queue");
}
else {
// display the front of the queue
System.out.println("\nFront index-> " + front);

// display element of the queue


System.out.println("Items -> ");
for (i = front; i<= rear; i++)
System.out.print(items[i] + " ");

// display the rear of the queue

45
Sample Output:
Queue is empty
Insert 1
Insert 2
Insert 3
Insert 4
Insert 5
Queue is full

Front index-> 0
Items ->
12 3 4 5
Rear index-> 4
1 Deleted

Front index-> 1
Items ->
2 3 4 5
Rear index-> 4

46
System.out.println("\nRear index-> " + rear);
}
}

public static void main(String[] args) {

// create an object of Queue class


Queue q = new Queue();

// try to delete element from the queue


// currently queue is empty
// so deletion is not possible
q.deQueue();

// insert elements to the queue


for(int i = 1; i< 6; i ++) {
q.enQueue(i);
}

// 6th element can't be added to queue because queue is full


q.enQueue(6);

q.display();

// deQueue removes element entered first i.e. 1


q.deQueue();

// Now we have just 4 elements


q.display();

47
48
}
}

PRE LAB QUESTIONS


1. What is an queue?

2. How to insert an elements to the queue?

3. How to delete element from the queue?

4. Define circular queue.

5. List the application of queue.

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:
Thus the above program was executed and verified successfully.

49
50
EX.NO:3.A
INHERITANCE USING JAVA
DATE:

Aim: To write the concepts of inheritance using java program.

Algorithm:
Step1: start
Step2: initialize the variables in main class.
Step3: field and method of the parent classinherit from Bicycle.
Step4: new method in subclassitcreate an object of the subclass.
Step5: access field of superclass in call method of superclass with using object of subclass.
Step6:stop the program.

// Java program to illustrate the


// concept of inheritance

// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}

51
52
// the Bicycle class has three methods
public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return ("No of gears are " + gear + "\n"
+ "speed of bicycle is " + speed);
}
}

// derived class
class MountainBike extends Bicycle {

// the MountainBike subclass adds one more field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int gear, int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor

53
Sample Output:
No of gears are 3
speed of bicycle is 100
seat height is 25

54
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method


public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method


// of Bicycle to print more info
@Override public String toString()
{
return (super.toString() + "\nseat height is "
+ seatHeight);
}
}

// driver class
public class Test {
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


System.out.println(mb.toString());
}
}

55
56
PRE LAB QUESTIONS
1. What is inheritance in Java?
2. Explain method overriding in Java?
3. Demonstrate how inheritance is declared using the extends keyword?
4. Give an example where you override a method?
5.List out the applications of inheritance.

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:
Thus the above program was executed and verified successfully.

57
58
EX.NO:3.B
POLYMORPHISM USING JAVA
DATE:

Aim: To write the concepts polymorphism using java program.

Algorithm:
Step1: start
Step2: initialize the Superclass Vehicle.
Step3: Subclass Car inheriting from Vehicle.
Step4: Subclass Bike inheriting from Vehicle.
Step5: Car object polymorphically assigned to Vehicle reference.
Step6: Bike object polymorphically assigned to Vehicle.
Step7: end of the program.

Program

// Superclass Vehicle
class Vehicle {
public void start() {
System.out.println("Vehicle starts");
}
}
// Subclass Car inheriting from Vehicle
class Car extends Vehicle {
@Override
public void start() {
System.out.println("Car starts with a key");
}
}

59
Sample Output:
Car starts with a key
Bike starts with a kick

60
// Subclass Bike inheriting from Vehicle
class Bike extends Vehicle {
@Override
public void start() {
System.out.println("Bike starts with a kick");
}
}

// Main class demonstrating dynamic polymorphism


public class DynamicPolymorphismExample {
public static void main(String[] args) {

Vehicle myCar = new Car(); // Car object polymorphically assigned to Vehicle reference
Vehicle myBike = new Bike(); // Bike object polymorphically assigned to Vehicle
reference

myCar.start(); // Outputs: Car starts with a key


myBike.start(); // Outputs: Bike starts with a kick
}
}

61
62
PRE LAB QUESTIONS
1. Explain the difference between compile-time (static) and runtime (dynamic)
polymorphism.
2. Define polymorphism in the context of Java?
3. What is method overriding? How does it relate to polymorphism?
4.Write the advantages of polymorphism.
5. What is error?

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:
Thus the above program was executed and verified successfully.

63
64
EX.NO:4 DEVELOP AN APPLICATION USING INTERFACE BY
ACCESSING SUPER CLASS CONSTRUCTORS AND
DATE: METHODS

Aim:
To develop an application using interface by accessing super class constructors and
methods.

Algorithm:
Step1: start
Step2: create a Superclass (parent)and Subclass (child).
Step3:Call the superclass method,Create a object.
Step4:Call the method on the object.
Step5: end of the program.

Program:

class Animal { // Superclass (parent)


public void animalSound() {
System.out.println("The animal makes a sound");
}
}

class Dog extends Animal { // Subclass (child)


public void animalSound() {
super.animalSound(); // Call the superclass method
System.out.println("The dog says: bow wow");
}
}

public class Main {

65
Sample Output:
The animal makes a sound
The dog says: bow wow

66
public static void main(String[] args) {
Animal myDog = new Dog(); // Create a Dog object
myDog.animalSound(); // Call the method on the Dog object
}
}

PRE LAB QUESTIONS


1. Explain what an interface is in Java and how it differs from a class?
2. Describe the key features of interfaces?
3. Give an example demonstrating how a subclass constructor can invoke a superclass
constructor using super().
4. Define constructor.
5. How to declare super class in interface?

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:
Thus the above program was executed and verified successfully.

67
68
EX.NO:5
DEVELOP AN EMPLOYEE PAYROLL APPLICATION
DATE: USING JAVA PACKAGES

Aim:
To develop an employee payroll application using java program.
Algorithm
Step1:Start the program.
Step2: Create a base class namely Employee.
Step3: Create a sub classes namely, Programmer, Assistant professor, Associate professor and
Professor and inherit all these sub class from base class Employee by following the
hierarchical inheritance concept.
Step4: Write down the salary calculation for each sub class by following the policy given
below,
 Add Basic Pay (BP) as the member of all the inherited classes with 97% of BP
as DA,
 10 % of BP as HRA,
 12% of BP as PF, 0.1% of BP for staff club fund.

Step5: Display the pay slips for the employee with their Gross and Net salary.
Step6: stop the program.

Program:
import java.util.Scanner;

public class RunEmployee {


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

System.out.print("Enter Employee Name: ");


String name = in.nextLine();

System.out.println("\nEmployeeTypes:\n F - Full Time\n P - Part Time");


System.out.print("Enter Employee Type:");

69
70
String type = in.nextLine();
if (type.compareToIgnoreCase("F") == 0) {
FullTimeEmployee employee = new FullTimeEmployee(name);

System.out.print("\nEnter Monthly Salary: ");


employee.setMonthlySalary(in.nextDouble());

System.out.println(employee);
} else if(type.compareToIgnoreCase("P") == 0) {
PartTimeEmployee employee = new PartTimeEmployee(name);

System.out.print("\nEnter Rate Per Hour: ");


double rate = in.nextDouble();

System.out.print("\nEnter Number of Hours Worked: ");


employee.setWage(rate, in.nextInt());

System.out.println(employee);
} else {
System.out.println("Error: Ivalid Employee Type!");
}
}
}

abstract class Employee {


private String name;

public Employee(String name) {


setName(name);
}

71
72
public void setName(String name) {
this.name = name;
}

public String getName() {


return name;
}
}

final class FullTimeEmployee extends Employee {


private double monthlySalary;

public FullTimeEmployee(String name) {


super(name);
}

public void setMonthlySalary(double salary) {


monthlySalary = salary;
}

public double getMonthlySalary() {


return monthlySalary;
}

public String toString() {


return "\nEmployee Name: " + getName() + "\nMonthly Salary: " + monthlySalary;
}
}

final class PartTimeEmployee extends Employee {

73
Sample Output:
Enter Employee Name: Ravi
Employee Types:
F - Full Time
P - Part Time
Enter Employee Type:F
Enter Monthly Salary: 12000
Employee Name: kavi
Monthly Salary: 12000.0

74
private double ratePerHour;
private int hoursWorked;
private double wage;

public PartTimeEmployee(String name) {


super(name);
}

public void setWage(double rate, int hours) {


ratePerHour = rate;
hoursWorked = hours;
wage = ratePerHour * hoursWorked;
}

public double getWage() {


return wage;
}

public String toString() {


return "\nEmployee Name: " + getName() + "\nWage: " + wage;
}
}

75
76
PRE LAB QUESTIONS
1. Explain how you would manage a collection of Employee objects in your Java
application.
2. Provide examples of methods to add, remove, and search for employees in your
collection.
3. Describe how you would calculate the monthly payroll for employees based on their
salary.
4. Define Packages
5. How to create a packages in java?

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:
Thus the above program was executed and verified successfully.

77
78
EX.NO:6
IMPLEMENT EXCEPTION HANDLING AND CREATION OF
DATE: USER DEFINED EXCEPTION

Aim:
To implement exception handling and creation of user defined exception.

Algorithm:
Step1: start the program.
Step2:Create a custom exception class that extends the base exception class
(java.lang.Exception).

Step3:Define the constructor for the custom exception class. The constructor can accept
parameters to provide more information about the error.

Step4:Override the to String() method to provide a custom error message.

Step5:Use the "throw" keyword to throw an instance of the custom exception when the error
condition occurs.

Step6:Use a "try-catch" block to catch the exception and handle it appropriately.

Step7: end of the program.

Program:

User Defined exception in java for Validating Login Credentials

// Custom exception class


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

79
Sample Output:
ERROR!
Error: Invalid salary: 120000.0

80
// Example of using the custom exception
class Employee {
private String name;
private double salary;

public void setSalary(double salary) throws SalaryOutOfBoundsException {


if (salary < 0 || salary > 100000) {
throw new SalaryOutOfBoundsException("Invalid salary: " + salary);
}
this.salary = salary;
}
}

// Main class demonstrating custom exception usage


public class CustomExceptionExample {
public static void main(String[] args) {
Employee emp = new Employee();
try {
emp.setSalary(120000); // Throws SalaryOutOfBoundsException
} catch (SalaryOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

81
82
PRE LAB QUESTIONS
1. Explain what exceptions are in Java and why they are used?
2. Explain the order in which catch blocks are evaluated when an exception occurs.
3. Describe why and when you would create a user-defined exception in Java.
4. What is exception?
5. List out the types of exception?

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:
Thus the above program was executed and verified successfully.

83
84
EX.NO:7.A IMPLEMENT TO MULTI-THREADING
COMMUNICATION
DATE:

Aim:To implement a program multithreading in java.

Algorithm:
Step1:start
Step2: create a class that extends the java.lang.Thread class
Step3:This class overrides the run() method available in the Thread class.
Step4:A thread begins its life inside run() method.
Step5: We create an object of our new class and call start() method to start the
execution of a thread.
Step7:Start() invokes the run() method on the Thread object.
Step8:end of the program.

Program:
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception

85
Sample Output:
Thread 11 is running
Thread 13 is running
Thread 15 is running
Thread 12 is running
Thread 17 is running
Thread 16 is running
Thread 10 is running
Thread 14 is running

86
System.out.println("Exception is caught");
}
}
}

// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i< n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}

87
88
PRE LAB QUESTIONS
1. Provide examples using the Thread class and implementing the Runnable interface.
2. Describe different ways to create threads in Java.
3. Explain the advantages of using multithreading in a Java application.
4. List the types of states in thread cycle.
5. What is thread?

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:
Thus the above program was executed and verified successfully.

89
90
EX.NO: 7.B
IMPLEMENT TO INTERTHREAD COMMUNICATION
DATE:

Aim:
To implement program to interthread communication in java program.

Algorithm:
Step1: start the program.
Step2: Causes the current thread to wait until another thread invokes the notify().

Step3:Wakes up a single thread that is waiting on this object's monitor.

Step4: Wakes up all the threads that called wait( ) on the same object.

Step5:Second, it puts the csgo thread in a waiting state until all other threads are
finished. It can regain control of a Game object by using notify() or notifyAll() on the same
object, if some other function wakes it up.

Step6: As a result, as soon as the wait() function is invoked, the control transfers to
valorant thread and prints -"Waiting for return key csgo paused valorant running." to show
that the csgo thread is in a waiting state while the valorant thread is active.

Step7: To begin with, unlike wait(), it does not release the lock on shared resources,
therefore it's best to use notify just at the end of your method to get the desired outcome.

Step8:As you may have noticed, control does not instantly pass to the csgo thread
even after notify(). The reason for this is that after notify(), we called Thread.sleep() .

Step9: end of the program.

91
92
Program:

class Chat {
boolean flag = false;

public synchronized void Question(String msg) {


if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg);
flag = true;
notify();
}

public synchronized void Answer(String msg) {


if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

System.out.println(msg);
flag = false;
notify();
}

93
94
class T1 implements Runnable {
Chat m;
String[] s1 = { "Hi", "How are you ?", "I am also doing fine!" };

public T1(Chat m1) {


this.m = m1;
new Thread(this, "Question").start();
}

public void run() {


for (int i = 0; i< s1.length; i++) {
m.Question(s1[i]);
}
}
}

class T2 implements Runnable {


Chat m;
String[] s2 = { "Hi", "I am good, what about you?", "Great!" };

public T2(Chat m2) {


this.m = m2;
new Thread(this, "Answer").start();
}

public void run() {


for (int i = 0; i< s2.length; i++) {
m.Answer(s2[i]);
}

}
public class TestThread {

95
Sample Output:

Hi

Hi

How are you ?

I am good, what about you?

I am also doing fine!

Great!

96
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);
}

PRE LAB QUESTIONS

1. What is inter-thread communication in Java?


2. Why is inter-thread communication important in multithreaded programming?
3. Explain the wait(), notify(), and notifyAll() methods in Java.
4. Draw the thread life cycle model
5. How to control it idle stage?

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:

Thus the above program was executed and verified successfully.

97
98
EX.NO:8.A
DEVELOP AN APPLICATION TO PERFORM CREATE
FILE OPERATION IN JAVA
DATE:

Aim:

To develop an application to perform create file operation in java.

Algorithm:

Step1: start the program.

Step2:To create a new file, we can use the createNewFile() method. It returns

Step3:true if a new file is created.

Step4:false if the file already exists in the specified location.

Step5: end of the program.

Program:

// importing the File class


import java.io.File;

class Main {
public static void main(String[] args) {

// create a file object for the current location


File file = new File("newFile.txt");

try {

99
Sample Output:
Code Execution Successful

100
// trying to create a file based on the object
boolean value = file.createNewFile();
if (value) {
System.out.println("The new file is created.");
}
else {
System.out.println("The file already exists.");
}
}
catch(Exception e) {
e.getStackTrace();
}
}
}

101
102
PRE LAB QUESTIONS
1. Define File
2. List out the file operations in java.
3. How to delete a file in packages?
4. What is command line arguments?
5. Define append file.

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:

Thus the above program was executed and verified successfully.

103
104
EX.NO:8.B
DEVELOP AN APPLICATION TO PERFORM DELETE
DATE: FILE OPERATION

Aim:
To develop an application to perform delete file operation in java.
Algorithm:
Step1:start the program.

Step2: We can use the delete() method of the File class to delete the specified file or
directory. It returns.

Step3:true if the file is deleted.


Step4:false if the file does not exist.

Step5:end of the program.

Program:

Java delete files


import java.io.File;
class Main {
public static void main(String[] args) {

// creates a file object


File file = new File("file.txt");

// deletes the file


boolean value = file.delete();
if(value) {
System.out.println("The File is deleted.");
}
else {
System.out.println("The File is not deleted.");
}}}

105
Sample Output:
The File is not deleted.

106
PRE LAB QUESTIONS
1. Explain how you would create a new text file in Java.
2. Why is error handling important when creating files in Java?
3. Describe how you would handle exceptions like IOException during file creation.
4. How would you delete a non-empty directory and its contents in Java?
5. Define IOException.

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:

Thus the above program was executed and verified successfully.

107
108
EX.NO: 9 DEVELOP APPLICATION TO DEMENSTRATE THE
FEAUTURES OF GENERIC CLASS AND INTERFACES
DATE:

Aim:
We can create a class that can be used with any type of data. Such a class is known as
Generics Class.

Algorithm:
Step1: start the program.

Step2: we have created a generic class named GenericsClass. This class can be used
to work with any type of data.

Step3: T used inside the angle bracket <> indicates the type parameter. Inside
the Main class, we have created two objects of GenericsClass.

Step4: intObj - Here, the type parameter T is replaced by Integer. Now,


the GenericsClass works with integer data.

Step5: s tringObj - Here, the type parameter T is replaced by String. Now,


the GenericsClass works with string data.
Step6: end of the program.

Program:

class Main {
public static void main(String[] args) {

// initialize generic class


// with Integer data
GenericsClass<Integer>intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());

109
Sample Output:
Generic Class returns: 5
Generic Class returns: Java Programming

110
// initialize generic class
// with String data
GenericsClass<String>stringObj = new GenericsClass<>("Java Programming");
System.out.println("Generic Class returns: " + stringObj.getData());
}
}

// create a generics class


class GenericsClass<T> {

// variable of T type
private T data;

public GenericsClass(T data) {


this.data = data;
}

// method that return T type variable


public T getData() {
return this.data;
}
}

111
112
PRE LAB QUESTIONS
1. Explain what generics are in Java and why they are used.
2. Discuss the advantages of using generics in terms of type safety and code reusability.
3. Describe how you would define a generic method within a generic class.
4. Describe how generics can be applied to interfaces in Java.
5. What is generic?

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:

Thus the above program was executed and verified successfully.

113
114
EX.NO: 10
COLLECTIONS FRAMEWORKS
DATE:

Aim:
To implement the concepts of collection frameworks.

Algorithm:
Step1: start the program.

Step2: If we want our data to be unique, then we can use the Set interface provided
by the collections framework .

Step3: To store data in key/value pairs, we can use the Map interface.

Step4: The ArrayList class provides the functionality of resizable arrays.

Step5: The ArrayList class allows us to create resizable arrays. The class implements
the List interface (which is a subinterface of the Collection interface).

Step6: end of the program.

Program:

// The Collections framework is defined in the java.util package


import java.util.ArrayList;

class Main {
public static void main(String[] args){
ArrayList<String> animals = new ArrayList<>();

115
Sample Output:
ArrayList: [Dog, Cat, Horse]

116
// Add elements
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");

System.out.println("ArrayList: " + animals);


}
}

PRE LAB QUESTIONS


1. Explain what the Java Collections Framework is and its main objectives.
2. Discuss the advantages of using collections over arrays in Java.
3. Explain the purpose and key characteristics of each interface.
4. Give an example of adding elements in java.
5. What is framework?

MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20

Program 30

Pre-lab questions 10

Post-lab questions 10

Execution & Results 30

Total 100

Result:

Thus the above program was executed and verified successfully.

117

You might also like