Java Programming Lab Manual (3)
Java Programming Lab Manual (3)
AN AUTONOMOUS INSTITUTION
NAME :
REGISTER NUMBER :
BRANCH :
YEAR / SEM :
COURSE :
1
2
K S R INSTITUTE FOR ENGINEERING AND TECHNOLOGY
AN AUTONOMOUS INSTITUTION
CERTIFICATE
………………………………………………………………………………………………Branch
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
MISSION
7
8
K S R INSTITUTE FOR ENGINEERING AND TECHNOLOGY
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.
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.
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
4.Develop an application using interface by accessing super class constructors and methods
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.
Program:
// Java Program to Illustrate Arithmetic Operators
importjava.util.*;
// Class 1
classA {
// 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
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:
Algorithm:
Step1: start
Step2:int numbers
Step3:sum=0,
Step5:end.
Program:
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?
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
Step5:end.
IF STATEMENT
Sample Output:
x + y is greater than 20
23
24
IF-ELSE STATEMENT
Sample Output:
x + y is greater than 20
IF-ELSE-IF LADDER
25
26
Sample Output:
Delhi
NESTED-IF
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?
4. Define Nested-if.
MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20
Program 30
Pre-lab questions 10
Post-lab questions 10
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;
}
// if stack is empty
// no element to pop
if (isEmpty()) {
System.out.println("STACK EMPTY");
33
34
// terminates the program
System.exit(1);
}
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();
Program 30
Pre-lab questions 10
Post-lab questions 10
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
Queue() {
front = -1;
rear = -1;
}
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);
}
}
// 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);
}
}
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);
}
}
q.display();
47
48
}
}
MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20
Program 30
Pre-lab questions 10
Post-lab questions 10
Total 100
Result:
Thus the above program was executed and verified successfully.
49
50
EX.NO:3.A
INHERITANCE USING JAVA
DATE:
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.
// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;
51
52
// the Bicycle class has three methods
public void applyBrake(int decrement)
{
speed -= decrement;
}
// derived class
class MountainBike extends Bicycle {
53
Sample Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
54
super(gear, speed);
seatHeight = startHeight;
}
// driver class
public class Test {
public static void main(String args[])
{
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
Total 100
Result:
Thus the above program was executed and verified successfully.
57
58
EX.NO:3.B
POLYMORPHISM USING JAVA
DATE:
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");
}
}
Vehicle myCar = new Car(); // Car object polymorphically assigned to Vehicle reference
Vehicle myBike = new Bike(); // Bike object polymorphically assigned to Vehicle
reference
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
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:
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
}
}
MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20
Program 30
Pre-lab questions 10
Post-lab questions 10
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;
69
70
String type = in.nextLine();
if (type.compareToIgnoreCase("F") == 0) {
FullTimeEmployee employee = new FullTimeEmployee(name);
System.out.println(employee);
} else if(type.compareToIgnoreCase("P") == 0) {
PartTimeEmployee employee = new PartTimeEmployee(name);
System.out.println(employee);
} else {
System.out.println("Error: Ivalid Employee Type!");
}
}
}
71
72
public void setName(String name) {
this.name = name;
}
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;
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
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.
Step5:Use the "throw" keyword to throw an instance of the custom exception when the error
condition occurs.
Program:
79
Sample Output:
ERROR!
Error: Invalid salary: 120000.0
80
// Example of using the custom exception
class Employee {
private String name;
private double salary;
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
Total 100
Result:
Thus the above program was executed and verified successfully.
83
84
EX.NO:7.A IMPLEMENT TO MULTI-THREADING
COMMUNICATION
DATE:
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
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().
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() .
91
92
Program:
class Chat {
boolean flag = false;
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 class TestThread {
95
Sample Output:
Hi
Hi
Great!
96
public static void main(String[] args) {
Chat m = new Chat();
new T1(m);
new T2(m);
}
MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20
Program 30
Pre-lab questions 10
Post-lab questions 10
Total 100
Result:
97
98
EX.NO:8.A
DEVELOP AN APPLICATION TO PERFORM CREATE
FILE OPERATION IN JAVA
DATE:
Aim:
Algorithm:
Step2:To create a new file, we can use the createNewFile() method. It returns
Program:
class Main {
public static void main(String[] args) {
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
Total 100
Result:
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.
Program:
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
Total 100
Result:
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.
Program:
class Main {
public static void main(String[] args) {
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());
}
}
// variable of T type
private T 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
Total 100
Result:
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.
Step5: The ArrayList class allows us to create resizable arrays. The class implements
the List interface (which is a subinterface of the Collection interface).
Program:
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");
MARKS ALLOCATION
Marks Marks
Details
Allotted Awarded
Aim & Algorithm 20
Program 30
Pre-lab questions 10
Post-lab questions 10
Total 100
Result:
117