You are on page 1of 136

ATSS’s

Institute of Industrial and Computer Management and Research,


Nigdi Pune
MCA Department
Academic Year: 2023-
24

Practical Journal
on
IT11L- Data Structure and
Algorithms (SEM-I)

Submitted By:

Name – Pratham Vikas Mekhale

Seat No - 6812

Roll No- 26

Date : 15/12/2023
Course Outcomes:

Student will be able to :


CO1: Demonstrate Collection framework (Apply)
CO2: Develop GUI using awt and swing (Apply)
CO3: Develop Web application using JSP and Servlet, JDBC (Apply)
CO4: Apply Data Structure to solve problems using JavaScript
(Apply)
ATSS’s

Institute of Industrial and Computer Management and Research, Nigdi Pune


MCA Department
INDEX
Student’s Name: Roll No.
Program Title Course Page Teacher’ Remarks
Sr Outcome No. s Sign
. with
No Date
Write a program to implement
1. Singly linked list with required CO4
member function(Create, insert, delete,
Display)
Write a program to implement
2. Doubly linked list with required CO4
member function(Create, insert, delete,
Display )
Write a program to implement STACK
3. CO4
using Array with PUSH, POP
operations
Write a program to implement Stack
4. CO4
using Linked List
Write a program of stack to Check
5. for balancedparentheses. CO4
Write a program to Reverse a
6. CO4
string usingstack
Write a program to
7. implementLinear Queue CO4
Write a program to Reverse stack
8. CO4
using queue
Write a program to implement
9. CO4
binary searchtree with its operations
Write a program
10. CO4
to
implementCircular
Queue
Write a Program to print Adjacency
11. Matrix and Adjacency List by reading CO4
Edges ofGraph
Write a Program to find the element an
12. array using Binary Search CO4
Write a Program to find the element
13. CO4
in an array using Linear Search
Write a Program to Print Pascal’s triangle
14. for n=5 CO4
Write a Program to implement GCD of
15. two numbers using Euclidean CO4
Algorithm
Write a program to implement tower of
16. Hanoi where number of disks=4 CO4
Write a program to
17. implement Fibonacci CO4
series till N
Write a program to implement Rain
18 terrace Problem CO4
Write a Program to implement
19 Graph traversal CO4
1.BFS 2.DFS

Write a program to implement sorting


20 using Divide and Conquer strategy CO4
1. Quick sort 2.Merge sort
Write a program to implement segment CO4
21 tree for sum queries
Q.1 Write a program to implement Singly linked list with required member function(Create, insert, delete,
Display)

Solution: Program
class Node
{
constructor(data){
this.data = data;
this.next = null;
}}
class LinkedListCreation {
constructor() {
this.head = null;
}
create(data) {
var nn = new Node(data);
if (this.head == null) {
this.head = nn; }
else{
let cur = this .head;
while(cur.next != null) {
cur = cur.next; }
cur.next = nn;
}}
insertAtFirst(data)
{
let nnF = new Node(data);
nnF.next = this.head;
this.head = nnF;
}
insertAtLast(data) {
let nnL = new Node(data);
let cur = this.head;
while(cur.next != null) {
cur = cur.next; }
cur.next = nnL;
}

insertAtPos(data,pos) {
let nnp = new Node(data);
let temp = this.head;
for (let i = 1; i < pos-1 && temp.next != null;i++) {
temp = temp.next; }
nnp.next = temp.next;
temp.next = nnp;
}
DeleteFromFirst() {
if(this.head.next==null) {
this.head = null; }
else{
this.head = this.head.next;
}}
DeleteFromPos(pos)
{
let p = this.head;
for(let i = 1; i<pos && p != null; i++)
{
var q = p;
p=p.next;
}
q.next = p.next;
}

DeleteFromLast()
{
let cur = this.head;
while(cur.next != null)
{
var p = cur;
cur=cur.next;
}
p.next = null;

DisplayList()
{
let cur = this .head;
while(cur!= null)
{
console.log(cur.data);
cur = cur.next;
}
}

var ll = new LinkedListCreation();


ll.create(111);
ll.create(222);
ll.create(333);
ll.create(444);
ll.create(555);
ll.create(666);
ll.insertAtFirst(110);
ll.insertAtPos(400,5);
ll.insertAtLast(777);
ll.DeleteFromFirst();
ll.DeleteFromPos(3);
ll.DeleteFromLast();
ll.DisplayList();

Output:
Screen Shot

Creating linked list, Inserting element at first , last and Position and Display.

After inserrtion and deleting element from first, last, and Position.-
Q2. Write a program to implement Doubly linked list with required member function(Create, insert, delete,
Display )

class Node {

constructor(data) {

this.data = data;

this.next = null;

this.prev = null;

}}
class DoublyLinkedList {

constructor()
{
this.head = null;
this.tail = null;
}

create(data) {
const newNode = new Node(data);

if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {

newNode.prev = this.tail;

this.tail.next = newNode;

this.tail = newNode;

}}

InsertAtFirst(data) {

let nf =new Node(data);

nf.next = this.head;

if (this.head) {
this.head.prev = nf;
}
this.head = nf;
}

InsertAtLast(data) {
let nl = new Node(data)
this.tail.next = nl;
Data Structure and Algorithms
nl.prev = this.tail;
this.tail = nl;
}

InsertAtPos(pos, data) {
const newNode = new Node(data);

if (pos === 0) {
newNode.next = this.head;
if (this.head) {
this.head.prev = newNode;
}
this.head = newNode;
} else {
let current = this.head;
let count = 0;

while (current && count < pos - 1) {


current = current.next;
count++;

if (!current) {

console.log("Position not found");

return;
}

newNode.next = current.next;
newNode.prev = current;

if (current.next) {
current.next.prev = newNode;
}
current.next = newNode;
}
}

DeleteFromFrist() {
if (this.head) {
this.head = this.head.next;
if (this.head) {
this.head.prev = null;
}
}
}

DeleteFromLast() {
if (this.tail) {
this.tail = this.tail.prev;
Data Structure and Algorithms
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
}
}

DeleteFromPos(pos) {
let current = this.head;
let count = 1;

while (current && count < pos) {


current = current.next; count+
+;
}

if (!current) {
console.log("Position not found");
return;
}

if (current.prev) {
current.prev.next =
current.next;
} else {
this.head = current.next;
}

if (current.next) {
current.next.prev = current.prev;
} else {
this.tail = current.prev;
}
}

Display() {
let current = this.head;
while (current != null) {
console.log(current.data);
current = current.next;
}}}
const list = new DoublyLinkedList();
list.create(41);
list.create(42);
list.create(43);
list.create(44);
list.create(45);
console.log("Elements in list are:");
list.Display();
console.log("The element after inserted new element at
first:");
list.InsertAtFirst(40);
list.Display();
console.log("The element after inserted new element at last:");
list.InsertAtLast(46);
Data Structure and Algorithms
list.Display();
console.log("The element after inserted new element at given
position:");
list.InsertAtPos(2, 55);
list.Display();
console.log("The element after deleted element from first:");
list.DeleteFromFrist();
list.Display();
console.log("The element after deleted element from last:");
list.DeleteFromLast();
list.Display();
console.log("The element after deleted element from given
position:");
list.DeleteFromPos(2);
list.Display();

Output -
Screenshot-
Q3. Write a program to implement STACK using Array with PUSH, POP operations

Program-

class STKA{
constructor(sz)
{
this.data=[];
this.top=-1;
this.size=sz;
}

push(val)
{
if(this.top==this.size-1)
{
console.log("Stack is full");
}
else{
this.top++;
this.data[this.top]=val;
return
}
}
pop()
{
if(this.top==-1)
{
console.log("Stack is empty");
}
else{
let t = this.data[this.top];
this.top--;
console.log(t);
}
}
display()
{
for(let i = this.top; i>=0; i--)
{
console.log(this.data[i]+" ");

}
}
}
var mystka = new STKA(5);
mystka.push(10);
mystka.push(20);
mystka.push(30);
mystka.push(40);
mystka.push(50);
console.log(".....................");
mystka.display();
console.log(".....................");
console.log("Popped element is :");
mystka.pop();
console.log(".....................");
mystka.display();

Output-

Screenshot-
Q4. Write a program to implement Stack using Linked List.

Program

class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}

class Stackk {
constructor() {
this.top = null;

push(data) {
const newNode = new Node(data);
newNode.next = this.top;
this.top = newNode;

pop() {

if(this.top == null)
{
console.log("Stack is empty");
}
else{
console.log("popped element is:",this.top.data);
this.top = this.top.next;

}
}

display() {
if(this.top == null)
{
console.log("Stack is empty !");
}
else{
let current = this.top;
while (current !== null) {
console.log(current.data);
current = current.next;
}
}
}
}
const stk = new Stackk();

stk.push(1000);
stk.push(2000);
stk.push(3000);
stk.push(4000);
console.log("Stack elements:");
stk.display();
stk.pop();
console.log("Now elements in stack are:");
stk.display();

Output-
Screenshots-
Q5 Write a program of stack to Check for balanced parentheses.

Program-

function areBracketsBalanced(expr)
{ let stack = [];

for(let i = 0; i < expr.length; i++)


{ let x = expr[i];

if (x == '(' || x == '[' || x == '{')


{ stack.push(x);
continue; }

if (stack.length == 0)
return false;

let check;
switch (x){
case ')':
check = stack.pop();
if (check == '{' || check == '[')
return false;
break;

case '}':
check = stack.pop();
if (check == '(' || check == '[')
return false;
break;

case ']':
check = stack.pop();
if (check == '(' || check == '{')
return false;
break;
}}

return (stack.length == 0); }

let expr = "([{}])";

if (areBracketsBalanced(expr))
console.log("Balanced ");
else
console.log("Not Balanced ");

Output
Q6. Write a program to Reverse a string using stack

Program
class newNode {
constructor(data) {
this.data = data
this.next = null
}}
class S {
constructor() {
this.top = null
}
push(ele) {
var node = new newNode(ele)
node.next = this.top
this.top = node
}
pop() {
var temp = this.top
var char = temp.data
this.top = this.top.next
temp = null
return char
}
reverseString(str) {
var i = 0
var reversestr = ""
while (i != str.length) {
this.push(str.charAt(i))
i++
}
var temp = this.top
while (temp != null) {
var char
char = this.pop()
reversestr += char
temp = this.top
}
return reversestr
}
display() {
var temp = this.top
while (temp != null) {
console.log(temp.data)
temp = temp.next
} }}
const s = new S();
const string = "Pratha"
const reverse = s.reverseString(string)
console.log(`The String provided - ${string}\nString in reverse format -${reverse}`)

output:-
Q7. Write a program to implement Linear Queue

Program-
class LinearQueue {
constructor(size) {
this.queue = [];
this.size = size;
this.front = -1;
this.rear = -1;
}

isEmpty() {
return this.front === -1;
}

isFull() {
return this.rear === this.size - 1;
}

enqueue(element) {
if (this.isFull()) {
console.log("Queue is full. Cannot enqueue.");
return;
}

if (this.isEmpty()) {
this.front = 0;
}

this.rear++;
this.queue[this.rear] = element;
console.log(`${element} enqueued to the queue.`);
}

dequeue() {
if (this.isEmpty()) {
console.log("Queue is empty. Cannot dequeue.");
return;
}

const removedElement = this.queue[this.front];


if (this.front === this.rear) {
this.front = -1;
this.rear = -1;
} else {
this.front++;
}

console.log(`${removedElement} dequeued from the


queue.`);
return removedElement;
}

display() {
if (this.isEmpty()) {
Data Structure and Algorithms
console.log("Queue is empty.");
} else {
console.log("Elements in the queue:",
this.queue.slice(this.front, this.rear + 1));
}
}
}

const queue = new LinearQueue(5);


queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
queue.display();
queue.dequeue();
queue.display();
queue.enqueue(4);
queue.enqueue(5);
queue.display();
queue.enqueue(6);

Output-

Data Structure and Algorithms


Q8. Write a program to reverse the string using stack.

Program-

class Stack {
constructor() {
this.items = [];
}

// Push element onto the stack


push(element) {
this.items.push(element);
}

// Pop element from the stack


pop() {
if (this.isEmpty()) {
return null;
}
return this.items.pop();
}

// Check if the stack is empty


isEmpty() {
return this.items.length === 0;
}

// Get the size of the stack


size() {
return this.items.length;
}

// Peek at the top element of the stack


peek() {
if (this.isEmpty()) {
return null;
}
return this.items[this.items.length - 1];
}
}

function reverseString(inputString) {
const stack = new Stack();

// Push each character onto the stack


for (let char of inputString) {
stack.push(char);
}

let reversedString = '';

// Pop each character from the stack to reverse the string


while (!stack.isEmpty()) {
reversedString += stack.pop();
}
return reversedString;
}

// Example usage
const originalString = 'PRATHAM';
const reversedString = reverseString(originalString);

console.log(`Original String: ${originalString}`);


console.log(`Reversed String: ${reversedString}`);

Output-

Data Structure and Algorithms


Q9. Write a program to implement binary search tree with its
operations.

class Node {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}

class BinarySearchTree {
constructor() {
this.root = null;
}

insert(key) {
this.root = this._insert(this.root, key);
}

_insert(root, key) {
if (root === null) {
return new Node(key);
}

if (key < root.key) {


root.left = this._insert(root.left, key);
} else if (key > root.key) {
root.right = this._insert(root.right, key);
}

return root;
}

delete(key) {
this.root = this._delete(this.root, key);
}

_delete(root, key) {
if (root === null) {
return root;
}

if (key < root.key) {


root.left = this._delete(root.left, key);
} else if (key > root.key) {
root.right = this._delete(root.right, key);
} else {
// Node with only one child or no child
if (root.left === null) {
return root.right;
} else if (root.right === null)
{ return root.left;
}
Data Structure and Algorithms
root.key = this._minValueNode(root.right).key;

root.right = this._delete(root.right, root.key);


}

return root;
}

_minValueNode(node) {
let current = node;
while (current.left !== null) {
current = current.left;
}
return current;
}

// Search for a key in the BST


search(key) {
return this._search(this.root, key);
}

_search(root, key) {
if (root === null || root.key === key) {
return root;
}

if (key < root.key) {


return this._search(root.left, key);
} else {
return this._search(root.right, key);
}
}

inorder() {
const result = [];
this._inorderRec(this.root, result);
return result;
}

_inorderRec(node, result) {
if (node !== null) {
this._inorderRec(node.left, result);
result.push(node.key);
this._inorderRec(node.right, result);
}
}
}

const bst = new ;


BinarySearchTree(); bst.insert(50); bst.ins
bst.insert(30) ert(40)
; ;
bst.insert(70)
;
bst.insert(20)
Data Structure and Algorithms
bst.insert(60);
bst.insert(80);

console.log("Inorder traversal:", bst.inorder());

bst.delete(20);
console.log("Inorder traversal after deleting 20:", bst.inorder());

const searchResult = bst.search(30);


console.log("Search result for key 30:", searchResult);

Data Structure and Algorithms


Q10. Write a program to implement Circular Queue.

Program-

class Queue {
constructor() {
this.rear = -1;
this.front = -1;
this.size = 5;
this.arr = new Array();
}
enQueue(value) {
if (this.front == 0 && this.rear == this.size - 1)
{
console.log("Queue is Full");
return;
}
else if (this.front == -1) {
this.front = this.rear = 0;
this.arr[this.rear] = value;
}
else if (this.rear == this.size - 1 && this.front != 0) {
this.rear = 0;
this.arr[this.rear] = value;
}
else {
this.rear++;
this.arr[this.rear] = value;
}
}
deQueue() {
if (this.front == -1) {
console.log("Queue is Empty");
}
let data = this.arr[this.front];
this.arr[this.front] = -1;
if (this.front == this.rear) {
this.front = -1;
this.rear = -1;
}
else if (this.front == this.size - 1)
this.front = 0;
else
this.front++;
// console.log("Data: ",data);
return data;
}
displayQueue() {
if (this.front == -1) {
console.log("Queue is Empty");
return;
}
Data Structure and Algorithms
console.log("\nElements in Circular Queue are: ");
if (this.rear >= this.front) {
for (let i = this.front; i <= this.rear; i++)
console.log(this.arr[i]);
}
else {
for (let i = this.front; i < this.size; i++)
console.log(this.arr[i]);
for (let i = 0; i <= this.rear; i++)
console.log(this.arr[i]);
}
}
}

let q = new Queue;

q.enQueue(14);
q.enQueue(22);
q.enQueue(13);
q.enQueue(-6);

q.displayQueue();

console.log("Deleted value = ", q.deQueue());


console.log("Deleted value = ", q.deQueue());
q.displayQueue();
q.enQueue(9);
q.enQueue(20);
q.enQueue(5);
q.displayQueue();
q.enQueue(20);
Output-

Screenshot-
Q11 Write a Program to print Adjacency Matrix and Adjacency List by reading Edges of Graph.

Program-

function createGraph(edges) {
const adjacencyMatrix = [];
const adjacencyList = {};

function addEdge(start, end) {


if (!adjacencyMatrix[start]) {
adjacencyMatrix[start] = [];
}
adjacencyMatrix[start][end] = 1;

if (!adjacencyList[start]) {
adjacencyList[start] = [];
}
adjacencyList[start].push(end);
}

edges.forEach(edge => {
const [start, end] = edge;
addEdge(start, end);
});

return { adjacencyMatrix, adjacencyList };


}

const edges = [[0, 1], [0, 2], [1, 2], [2, 0], [2, 3]];
const { adjacencyMatrix, adjacencyList } = createGraph(edges);

console.log("Adjacency Matrix:");
adjacencyMatrix.forEach(row => console.log(row.join(" ")));

console.log("\nAdjacency List:");
for (const vertex in adjacencyList) {
console.log(`${vertex} -> ${adjacencyList[vertex].join(", ")}`); }
Output-
Q12. Write a Program to find the element in an array using Binary Search.

Program-

function binarySearch(arr, target) {


let left = 0;
let right = arr.length - 1;

while (left <= right) {


const mid = Math.floor((left + right) / 2);

if (arr[mid] === target) {


return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}

return -1;
}

const sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];


const targetElement = 7;

const result = binarySearch(sortedArray, targetElement);

if (result !== -1) {


console.log(`Element ${targetElement} found at index ${result}.`);
} else {
console.log(`Element ${targetElement} not found in the array.`);
}

Output-
Q13 Write a Program to find the element in an array using Linear Search

Program-

function LinearSearch(arra, k)
{
for ( let i=0; i < arra.length;i++)
{
if(arra[i]==k)
{
return i;
}
}
return -1
}
var a = [80,45,70,35,40,50];
i = LinearSearch(a, 35);
if(i==-1)
{
console.log("Element is not found");
}
else
{
console.log("Element is present at position:",i+1);
}

Output -
Q14. Write a Program to Print Pascal’s triangle for n=5

Program-

function PascalTriangle(numRows)
{
if (numRows===0) return []

if(numRows===1) return [[1]]


let result=[];
for(let row=1 ; row <= numRows; row++)
{
let ar=[];
for(let col=0; col<row; col++)
{
if(col===0 || col === row -1)
{
ar.push(1);

}
else{
ar.push((result[row-2][col-1]+result[row -2][col]))
}
}
result.push(ar);

}
return result;

}
let n = 5;
console.log(PascalTriangle(n));

Output-
Q15. Write a Program to implement GCD of two numbers using Euclidean Algorithm

Program

function GCD(a,b)
{
if(a == 0)
{
return b;
}
else{
return GCD(b % a, a);
}
}
var a = 270 , b = 192;
console.log("GCD of "+ a + " and " + b +" = ", GCD(a, b));

Output
Q16 . Write a program to implement tower of Hanoi where number of disks=4.

Program

function TowerOfHanoi(num, first, mid, last)


{
if(num == 1)
{
console.log("Move disk 1 from Rod "+ first + "to rod"+ last);
return;
}
TowerOfHanoi(num-1, first, last, mid);
console.log("Move disk"+ num +" from Rod" +first+ " to Rod "+ mid);
TowerOfHanoi(num-1,last, mid, first);
}
var num = 4;
TowerOfHanoi(num, 'first', 'last', 'mid');

Output-
Q17. Write a program to implement Fibonacci series till N.

Program

const num = parseInt(prompt('Enter the number:'));


let n1 = 0, n2 = 1, next;

console.log('Fibonnacci Series:');

for(let i = 1; i <= num; i++)


{
console.log(n1)
; next = n1 +
n2; n1 = n2 ;
n2 = next;
}

Output-
Q18. Write a program to implement Rain terrace Problem

Program-

function maxWater(ary, n)
{
var res = 0;
for(var i = 1; i < n -1; i++)
{
var left = ary[i];
for (var j = 0; j < i; j++)
{
left = Math.max(left, ary[j])
}
var right = ary[i];
for(j = i+1; j < n; j++)
{
right = Math.max(right, ary[j])
}
res += Math.min(left, right) - ary[i];
}
return res;
}
var ary = [0,1,0,2,1,0,1,3,2,1,];
n = ary.length;
console.log(maxWater(ary,n));

Output-
Q19. Write a Program to implement Graph traversal 1.BFS 2.DFS

BFS-

class graph {
constructor() {
this.vertices = [];
this.adjacencyList = new Map();
}

addVertex(vertex) {
this.vertices.push(vertex);
this.adjacencyList.set(vertex, []);
}

addEdge(vertex1, vertex2) {
this.adjacencyList.get(vertex1).push(vertex2);
this.adjacencyList.get(vertex2).push(vertex1);
}

bfs(startingVertex) {
const visited = new Set();
const queue = [];

visited.add(startingVertex);
queue.push(startingVertex);

while (queue.length !== 0) {


const currentVertex = queue.shift();
console.log(currentVertex);

const neighbors = this.adjacencyList.get(currentVertex);

for (const neighbor of neighbors) {


if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
}
}

const gph = new graph();

gph.addVertex('A');
gph.addVertex('B');
gph.addVertex('C');
gph.addVertex('D');
gph.addVertex('E');

gph.addEdge('A', 'B');
gph.addEdge('A', 'C');
gph.addEdge('B', 'D');
Data Structure and Algorithms
gph.addEdge('C', 'E');

console.log('BFS Traversal:');
gph.bfs('A');

Output-

DFS-

class Graph {
constructor() {
this.adjacencyList = new Map();
}

addVertex(vertex) {
if (!this.adjacencyList.has(vertex)) {
this.adjacencyList.set(vertex, []);
}
}

addEdge(vertex1, vertex2) {
this.adjacencyList.get(vertex1).push(vertex2);
this.adjacencyList.get(vertex2).push(vertex1);
}

dfs(startingVertex, visited = new Set()) {


console.log(startingVertex);
visited.add(startingVertex);

for (const neighbor of this.adjacencyList.get(startingVertex)) {


if (!visited.has(neighbor)) {
this.dfs(neighbor, visited);
}
}
}
}
const graph = new Graph();

graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');
graph.addVertex('D');
graph.addVertex('E');

graph.addEdge('A', 'B');
graph.addEdge('B', 'C');
graph.addEdge('C', 'D');
graph.addEdge('D', 'E');

console.log("DFS Traversal:");
graph.dfs('A');

Output-
Q20. Write a program to implement sorting using Divide and Conquer strategy 1. Quick sort 2. Merge sort

Program

Quick Sort:

function partition(a, low, high)


{
var pivot, t, i, j;
pivot = a[high];
j = low;
for(var i = low; i < high; i++)
{
if (pivot >= a[i])
{
t = a[i];
a[i] = a[j];
a[j] = t;
j = j + 1;
}
}
a[high] = a[j];
a[j] = pivot;
return j;

a[high] = a[j];
a[j] = pivot;
return j;
}

function quicksort(a, low, high)


{
if(low < high)
{
var j = partition(a, low, high);
quicksort(a, low, j - 1);
quicksort(a, j + 1, high);
}
}
var a = [10, 89, -7, 29, -1];
var n = a.length;
var low = 0;
var high = n - 1;
console.log("Unsorted array is:")
for(var i = 0; i < n; i ++)
{
console.log(a[i]);
}
quicksort(a, low, high);
console.log("After sorting :");
for(var i = 0; i < n; i ++)
{
console.log(a[i]);
} Data Structure and Algorithms
Output-

Merge Sort-

function merge(arr, l, m, r)
{
var n1 = m - l + 1;
var n2 = r - m;

var L = new Array(n1);


var R = new Array(n2);

for (var i = 0; i < n1; i++)


L[i] = arr[l + i];
for (var j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

var i =

0; var j

= 0; var

k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
} k+
+;
}

while (i < n1) {


arr[k] = L[i]; i+
+;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

function mergeSort(arr,l, r){


if(l>=r){
return;
}
var m =l+ parseInt((r-l)/2);
mergeSort(arr,l,m);
mergeSort(arr,m+1,r);
merge(arr,l,m,r);
}

function printArray( A, size)


{
for (var i = 0; i < size; i++)
console.log( A[i] + " ");
}

var arr = [ 12, 11, 13, 5, 6, 7 ];


var arr_size = arr.length;

console.log( "Given array is ");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

console.log( "Sorted array is ");


printArray(arr, arr_size);
Output-
Q21. Write a program to implement segment tree for sum queries

Program-

class SegmentTree {
constructor(nums) {
this.n = nums.length;
this.tree = new Array(2 * this.n).fill(0);

this.buildTree(nums, 0, 0, this.n - 1);


}

buildTree(nums, treeIndex, left, right) {


if (left === right) {
this.tree[treeIndex] = nums[left];
} else {
const mid = Math.floor((left + right) / 2);
const leftChild = 2 * treeIndex + 1;
const rightChild = 2 * treeIndex + 2;

this.buildTree(nums, leftChild, left, mid);


this.buildTree(nums, rightChild, mid + 1, right);

this.tree[treeIndex] = this.tree[leftChild] + this.tree[rightChild];


}
}

update(index, value) {
this.updateHelper(0, 0, this.n - 1, index, value);
}

updateHelper(treeIndex, left, right, index, value) {


if (left === right) {
this.tree[treeIndex] = value;
} else {
const mid = Math.floor((left + right) / 2);
const leftChild = 2 * treeIndex + 1;
const rightChild = 2 * treeIndex + 2;

if (index <= mid) {


this.updateHelper(leftChild, left, mid, index, value);
} else {
this.updateHelper(rightChild, mid + 1, right, index, value);
}

this.tree[treeIndex] = this.tree[leftChild] + this.tree[rightChild];


}
}
query(left, right) {
return this.queryHelper(0, 0, this.n - 1, left, right);
}

queryHelper(treeIndex, segmentLeft, segmentRight, queryLeft, queryRight) {


if (queryLeft > segmentRight || queryRight < segmentLeft) {
return 0; // No overlap
}

if (queryLeft <= segmentLeft && queryRight >= segmentRight) {


return this.tree[treeIndex]; // Complete overlap
}

const mid = Math.floor((segmentLeft + segmentRight) / 2);


const leftChild = 2 * treeIndex + 1;
const rightChild = 2 * treeIndex + 2;

const leftSum = this.queryHelper(leftChild, segmentLeft, mid, queryLeft, queryRight);


const rightSum = this.queryHelper(rightChild, mid + 1, segmentRight, queryLeft, queryRight);

return leftSum + rightSum;


}
}

const nums = [1, 3, 5, 7, 9, 11];


const segmentTree = new SegmentTree(nums);

console.log(segmentTree.query(1, 4)); // Output: 25 (3 + 5 + 7 + 9)


segmentTree.update(2, 6);
console.log(segmentTree.query(1, 4)); // Output: 27 (3 + 6 + 7 + 9)

output-
Audyogik Tantra Shikshan Sansth’s

INSTITUTE OF INDUSTRIAL & COMPUTER


MANAGEMENT AND RESEARCH
[ IICMR]
Plot HS-2 Sector 27-A, Near Sant Tukaram Garden, Pradhikaran, Nigdi, Pune -44.
Phone : 020-27657648 , 27650011 e-mail: info@iicmr.org

Ref.iicmr/MCA/Lab.let/ /2023 Date :

Certificate
This is to certify that Mr./Ms. PRATHAM VIKAS MEKHALE

is bonafide student of IICMR, studying in Master of Computer Application(MCA) Program (Batch 2023-2025).

He/She has successfully completed IT 11L Practical of Semester 1 (A.Y. 2023-2024).

Seat no 6812

Practical Coordinator HOD Director

Examiner 1. Examiner 2.

Date:
ATSS’s

INSTITUTE OF INDUSTRIAL AND COMPUTER MANAGEMENT AND RESEARCH NIGDI, PUNE


MCA Department

INDEX

Name: PRATHAM VIKAS MEKHALE Roll No. : _26

Teacher's
Sr. Course Page
Name of the Practical Sign with Remarks
No. Outcome No.
Date
Hybrid Inheritance - Class student should hold the
rollno,class test should hold marks scored in two
different subjects(m1,m2,m3), interface sports should
1 hold marks in sports and class Result should calculate CO1 5
the total marks. The program must print the rollno,
marks scored in individual subject marks, marks scored
in sports and the total marks.

Design an interface Advanced Arithmetic which


contains a method signature int divisor_sum(int n).
You need to write a class called MyCalculator which
2 implements the interface. divisor_sum(int n) function CO1 8
takes an integer as input and return the sum of all its
divisors. Divisors of 6 are 1, 2, 3 and 6, so divisor_sum
should return 12. (0<n<100)

Design an interface Shape which contain method


3 input() and area() to calculate area of circle, CO1 10
square and
rectangle
Write an application which will throw
4 OverwtProductException if Product weight is above CO1 12
60kg. (Use User defined exception)
For a given 2D square matrix of size N*N, the task is to
5 CO1 14
find the sum of elements in the Principal diagonals
Declare the integer array with 10 numbers. Generate 2
6 new arrays Prime and NonPrime with prime and non- CO1 16
prime numbers from main array.
Program to count occurrence of given number in an
7 CO1 18
integer array of size 10
8 Program to reverse string without using inbuilt methods. CO1 19

9 Program to remove duplicate characters from String CO1 20

Program to toggle case each character of every word of


10 CO1 21
string
Write a program to demonstrate Arrays class any 10
11 CO1 23
methods with examples (hint: Java.util.Arrays).
Write java program to generate 10 terms of Fibonacci
12 CO1 25
series using threads
Create a menu driven program for Bank
13 account(acc_no, Name, amt) (Hint: use vector) 1. Add CO1 26
2. Search 3. Delete 4. Display
Write a program to store employee in TreeSet and
14 CO1 29
employees should be in sorted order of their age.

Write a program to write and read file by character


15 CO1 31
Stream. Also count number of lines in the file.
Write a Menu Driven Program for Blood Donor
application for following task a. Insert blood donor
details into database. b. Display blood group-wise
details of donors c. Update the address of a specific
16 donor. d. Delete the record of donors whose age is CO3 33
below 18.
Blood_Donor(Adhar,Name,Address,DOB,Gender,Blo
odGroup)
Design GUI for Student Registration (Student ID,
Name, Address, Gender, DOB, Course (C, C++, Java,
17 Python, Data Science, Hadoop, PowerBI, AWS etc.) It CO2 37
should be in dropdown combo). Add the details in
database. (Use events for radio button, combobox )

Write a servlet to check username & password passed


from html page. If it is “Scott” & “tiger”, display
18 welcome message else show the same html page again. CO3 40
[With res.sendRedirect
(“http://localhost:8080/login.html”)]
Write a servlet to add a Cookie to clients machine that
19 CO3 42
stores username, current date & time. Display the same
Q1. Hybrid Inheritance - Class student should hold the rollno,class test should hold marks scored in two different
subjects(m1,m2,m3), interface sports should hold marks in sports and class Result should calculate the total marks.
The program must print the rollno, marks scored in individual subject marks, marks scored in sports and the total
marks

PROGRAM-

interface Sports {
int getSportsMarks();
}
class Student { int
rollno;

public Student(int rollno)


{ this.rollno = rollno;
}
}
class Test extends Student { int m1,
m2, m3;

public Test(int rollno, int m1, int m2, int m3) { super(rollno);
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
}
public void displayTestMarks() {
System.out.println("Test Marks: " + m1 + ", " + m2 + ", " + m3);
}
}
class Result extends Test implements Sports { int sportsMarks;

public Result(int rollno, int m1, int m2, int m3, int sportsMarks) { super(rollno, m1, m2,
m3);
this.sportsMarks = sportsMarks;
}
@Override
public int getSportsMarks() { return
sportsMarks;
}
public void displayResult() { System.out.println("Roll No: "
+ rollno); displayTestMarks();
System.out.println("Sports Marks: " + sportsMarks); int totalMarks =
m1 + m2 + m3 + sportsMarks; System.out.println("Total Marks: " +
totalMarks);
}
}
public class HybridInheritance {
public static void main(String[] args) {
Result resultInstance = new Result(26, 90, 85, 95, 75); resultInstance.displayResult();
}
}
OUTPUT-
Q2. Design an interface AdvancedArithmetic which contains a method signature int divisor_sum(int n). You need
to write a class called MyCalculator which implements the interface. divisor_sum(int n) function takes an integer
as input and return the sum of all its divisors. Divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12.
(0<n<100).

PROGRAM-

interface AdvancedArithmetic { int


divisor_sum(int n);
}

class MyCalculator implements AdvancedArithmetic { @Override


public int divisor_sum(int n) { if (n <= 0
|| n >= 100) {
throw new IllegalArgumentException("Input must be in the range 0 < n < 100"); }

int sum = 0;
for (int i = 1; i <= n; i++) { if (n % i
== 0) {
sum += i;
} }
return sum;
}}
public class AdvancedArithmeticDivSum { public static void
main(String[] args) {
MyCalculator myCalculator = new MyCalculator(); int result =
myCalculator.divisor_sum(6); System.out.println("Divisor Sum: " +
result);
}
}

OUTPUT-

Q3. Design an interface Shape which contain method input() and area() to calculate area of cirlce,square and
rectangle.

PROGRAM-

import java.util.Scanner; interface Shape


{
void input();
double area();
}
class Circle implements Shape { double
radius;
public void input() {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the
radius of the circle: "); radius = scanner.nextDouble();
}
public double area() {
return Math.PI * radius * radius;
}
}
class Square implements Shape { double side;
public void input() {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the side
length of the square: "); side = scanner.nextDouble();
}
public double area() { return side
* side;
}
}
class Rectangle implements Shape { double length,
width;
public void input() {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the
length of the rectangle: "); length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: "); width =
scanner.nextDouble();
}
public double area() { return
length * width;
}
}
public class CRS {
public static void main(String[] args) { Shape circle
= new Circle(); circle.input();
System.out.println("Area of Circle: " + circle.area()); Shape square = new
Square();
square.input();
System.out.println("Area of Square: " + square.area()); Shape rectangle = new
Rectangle();
rectangle.input();
System.out.println("Area of Rectangle: " + rectangle.area());
}
}

OUTPUT-
Q4. Write an application which will throw OverwtProductException if Product weight is above 60kg. (Use User
defined exception).

PROGRAM-

class OverweightProductException extends Exception { public


OverweightProductException(String message) {
super(message);
}
}
class Product {
private String name; private
double weight;

public Product(String name, double weight) { this.name =


name;
this.weight = weight;
}
public void checkWeight() throws OverweightProductException { if (weight > 60) {
throw new OverweightProductException("Product weight exceeds 60 kg: " + weight + " kg");
} else {
System.out.println("Product weight is within the acceptable range.");
}
}
}
public class ProductApplication {
public static void main(String[] args) { try {
Product overweightProduct = new Product("HeavyProduct", 70);

overweightProduct.checkWeight();
} catch (OverweightProductException e) { System.out.println("Exception: " +
e.getMessage());
}
}
}

OUTPUT-
Q5. For a given 2D square matrix of size N*N, the task is to find the sum of elements in the Principal diagonals.

PROGRAM-

import java.util.Scanner;
public class PrincipalDiagonalSum { public static
void main(String[] args) {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the size of the
square matrix (N): "); int N = scanner.nextInt();
int[][] matrix = new int[N][N]; System.out.println("Enter the elements of
the matrix:"); for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) { matrix[i][j] =
scanner.nextInt();
}
}
int principalDiagonalSum = calculatePrincipalDiagonalSum(matrix, N); System.out.println("Sum of elements in the
principal diagonal: " + principalDiagonalSum);
scanner.close();
}
private static int calculatePrincipalDiagonalSum(int[][] matrix, int N) { int sum = 0;
for (int i = 0; i < N; i++) { sum +=
matrix[i][i];
}
return sum;
}
}
OUTPUT-
Q6. Declare the integer array with 10 numbers. Generate 2 new arrays Prime and NonPrime with prime and non-
prime numbers from main array.

PROGRAM-

public class PrimeAndNonPrimeArrays { public static void


main(String[] args) { int[] originalArray =
{1,2,3,4,5,6,7,8,9,10};
int[] primeArray = generatePrimeArray(originalArray);
int[] nonPrimeArray = generateNonPrimeArray(originalArray);
System.out.println("Original Array: " + java.util.Arrays.toString(originalArray));
System.out.println("Prime Numbers: " + java.util.Arrays.toString(primeArray));
System.out.println("Non-Prime Numbers: " +
java.util.Arrays.toString(nonPrimeArray));
}
private static int[] generatePrimeArray(int[] array) { int primeCount =
countPrimes(array);
int[] primeArray = new int[primeCount]; int index =
0;
for (int num : array) { if
(isPrime(num)) {
primeArray[index] = num; index++;
}
}
return primeArray;
}
private static int[] generateNonPrimeArray(int[] array) { int
nonPrimeCount = array.length - countPrimes(array); int[] nonPrimeArray
= new int[nonPrimeCount];
int index = 0;
for (int num : array) { if (!
isPrime(num)) {
nonPrimeArray[index] = num; index++;
}
}
return nonPrimeArray;
}
private static int countPrimes(int[] array) { int count = 0;
for (int num : array) { if
(isPrime(num)) { count++;
}
}
return count;
}
private static boolean isPrime(int num) { if (num <=
1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i
== 0) {
return false;
}}
return true;
} }

OUTPUT
Q7 Program to count occurance of given number in an integer array of size 10.

PROGRAM-
import java.util.Scanner;
public class NumberOccurrenceInArray { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in); int[] array = new int[10];
System.out.println("Enter 10 numbers:"); for (int i = 0; i <
array.length; i++) { array[i] = scanner.nextInt(); }
System.out.print("Enter the number to count its occurrences: "); int numberToCount =
scanner.nextInt();
int occurrenceCount = countOccurrences(array, numberToCount); System.out.println("Number of occurrences of " +
numberToCount + ": " + occurrenceCount);
scanner.close(); }
private static int countOccurrences(int[] array, int number) { int count = 0;
for (int i = 0; i < array.length; i++) { if (array[i] ==
number) {
count++; } return
count; }} OUTPUT-
Q8.Program to reverse string without using inbuilt methods.

PROGRAM-
import java.util.Scanner; public class
ReverseString {
public static void main(String[] args) { Scanner scanner = new
Scanner(System.in); System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
String reversedString = reverseString(inputString); System.out.println("Reversed String: " +
reversedString); scanner.close();
}
private static String reverseString(String input) { char[] charArray =
input.toCharArray();
int start = 0;
int end = charArray.length - 1; while (start <
end) {
char temp = charArray[start]; charArray[start] =
charArray[end]; charArray[end] = temp;
start++;
end--; }
return new String(charArray); }}
OUTPUT-
Q9. Program to remove duplicate characters from String

PROGRAM-
import java.util.Scanner;
public class RemoveDuplicatesFromString { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in); System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
String resultString = removeDuplicates(inputString); System.out.println("String after removing
duplicates: " + resultString); scanner.close(); }
private static String removeDuplicates(String input) { char[] charArray =
input.toCharArray();
int length = charArray.length; for (int i = 0;
i < length; i++) {
for (int j = i + 1; j < length; j++) { if
(charArray[i] == charArray[j]) { charArray[j]
= '\0'; }}}
int newIndex = 0;
for (int i = 0; i < length; i++) { if
(charArray[i] != '\0') {
charArray[newIndex++] = charArray[i];}} return new
String(charArray, 0, newIndex); }} OUTPUT-
Q10. Program to toggle case each charatcer of every word of string.

PROGRAM-

import java.util.Scanner;

public class ToggleCaseInWords { public static void


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

System.out.print("Enter a string: "); String inputString


= scanner.nextLine();

String result = toggleCaseInWords(inputString); System.out.println("String with toggled case in

each word: " + result);

scanner.close();
}
private static String toggleCaseInWords(String input) { StringBuilder result = new
StringBuilder();

String[] words = input.split("\\s"); for (String

word : words) {
result.append(toggleCase(word)).append(" ");
}
return result.toString().trim();
}
private static String toggleCase(String word) { char[] characters =
word.toCharArray();

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


if (Character.isUpperCase(characters[i])) {
characters[i] = Character.toLowerCase(characters[i]);
} else if (Character.isLowerCase(characters[i])) {
characters[i] = Character.toUpperCase(characters[i]);
}
}

return new String(characters);


}
}

OUTPUT-
Q11. Write a program to demonstrate Arrays class any 10 methods with examples (hint: Java.util.Arrays).

PROGRAM -

import java.util.Arrays;
public class ArraysMethod10 {
public static void main(String[] args) { int[] array1 = {9,
10, 8, 5, 1, 2, 3, 6, 8, 11};
int[] array2 = {9, 10, 8, 5, 1, 2, 3, 6, 8, 11};
// 1. Sorting array Arrays.sort(array1);
System.out.println("1. Sorted array: " + Arrays.toString(array1));
// 2. Binary search int
searchKey = 4;
int index = Arrays.binarySearch(array1, searchKey); System.out.println("2. Index of " +
searchKey + ": " + index);
// 3. Comparing arrays
boolean areEqual = Arrays.equals(array1, array2); System.out.println("3. Arrays are equal: "
+ areEqual);
// 4. Filling array
int[] filledArray = new int[5];
Arrays.fill(filledArray, 42);
System.out.println("4. Filled array: " + Arrays.toString(filledArray));
// 5. Copying arrays
int[] copiedArray = Arrays.copyOf(array1, array1.length); System.out.println("5. Copied array: " +
Arrays.toString(copiedArray));
// 6. Copying a range of elements
int[] rangeCopiedArray = Arrays.copyOfRange(array1, 2, 7); System.out.println("6. Copied
range array: " + Arrays.toString(rangeCopiedArray));
// 7. Converting array to a string
String arrayAsString = Arrays.toString(array1); System.out.println("7. Array as string: " +
arrayAsString);
// 8. Finding the minimum value
int minValue = Arrays.stream(array1).min().orElse(0); System.out.println("8. Minimum
value: " + minValue);
// 9. Finding the maximum value
int maxValue = Arrays.stream(array1).max().orElse(0); System.out.println("9. Maximum
value: " + maxValue);
// 10. Checking if array contains a specific value
boolean containsValue = Arrays.asList(array1).contains(6); System.out.println("10. Array
contains value 6: " + containsValue);
}
}

OUTPUT-
Q12. Write java program to generate 10 terms of Fibonacci series using threads.

PROGRAM-
class FibonacciThread extends Thread { private int n;
public FibonacciThread(int n) { this.n = n;
}
public void run() { int a =
0, b = 1, c;
System.out.print("Fibonacci Series for " + n + " terms: "); for (int i = 1; i <= n;
++i) {
System.out.print(a + " "); c = a +
b;
a = b;
b = c;
}
System.out.println();
})
public class FibonacciSeriesWithThreads { public static void
main(String[] args) {
FibonacciThread thread1 = new FibonacciThread(10); FibonacciThread
thread2 = new FibonacciThread(10); thread1.start();
thread2.start();
}
}

OUTPUT-
Q13. Create a menu driven program for Bank account(acc_no, Name, amt) (Hint: use vector) 1. Add 2. Search 3.
Delete 4. Display

PROGRAM-

import java.util.Scanner; import


java.util.Vector; class
BankAccount {
int acc_no; String
name; double amt;
public BankAccount(int acc_no, String name, double amt) { this.acc_no = acc_no;
this.name = name; this.amt = amt;
}
public String toString() {
return "Account Number: " + acc_no + ", Name: " + name + ", Amount: "
+ amt;
}
}
public class BankManagementSystem { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in);
Vector<BankAccount> accounts = new Vector<>(); int choice;
do { System.out.println("Menu:");
System.out.println("1. Add");
System.out.println("2. Search");
System.out.println("3. Delete");
System.out.println("4. Display");
System.out.println("5. Exit");
System.out.print("Enter your choice: "); choice =
scanner.nextInt();
switch (choice) { case 1:
System.out.print("Enter Account Number: ");
int acc_no = scanner.nextInt();
System.out.print("Enter Name: "); String name =
scanner.next(); System.out.print("Enter Amount: ");
double amt = scanner.nextDouble();
accounts.add(new BankAccount(acc_no, name, amt));
System.out.println("Account added successfully."); break;
case 2:
System.out.print("Enter Account Number to search: "); int searchAccNo =
scanner.nextInt();
boolean found = false;
for (BankAccount account : accounts) { if
(account.acc_no == searchAccNo) {
System.out.println("Account found: " + account); found = true;
break;
}
}
if (!found) {
System.out.println("Account not found.");
}
break;
case 3:
System.out.print("Enter Account Number to delete: "); int deleteAccNo =
scanner.nextInt();
for (BankAccount account : accounts) { if
(account.acc_no == deleteAccNo) {
accounts.remove(account);
System.out.println("Account deleted successfully."); break;
}
}
break;
case 4:
System.out.println("List of Accounts:"); for
(BankAccount account : accounts) {
System.out.println(account);
}
break;
case 5:
System.out.println("Exiting the program."); break;
default:
System.out.println("Invalid choice. Please enter a valid option."); break;
}
} while (choice != 5); scanner.close();
}
}

OUTPUT-
Q14. Write a program to store employee in TreeSet and employees should be in sorted order of their age.

PROGRAM-

import java.util.*;

class Employee implements Comparable<Employee> { private String name;


private int age;

public Employee(String name, int age) { this.name = name;


this.age = age;
}
public String getName() { return
name;
}

public int getAge() { return


age;
}

@Override
public int compareTo(Employee other) { return
Integer.compare(this.age, other.age);
}
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age + '}';
}
}
public class EmployeeTreeSetExample { public static
void main(String[] args) {
TreeSet<Employee> employeeSet = new TreeSet<>();
employeeSet.add(new Employee("Pratham", 21));
employeeSet.add(new Employee("Dnayesh", 22));
employeeSet.add(new Employee("Tanvi", 22));
employeeSet.add(new Employee("Prashun", 22));

System.out.println("Employees sorted by age:"); for (Employee


employee : employeeSet) {
System.out.println(employee);
}
}
}

OUTPUT-
Q15.Write a program to write and read file by character Stream. Also count number of lines in the file.

PROGRAM-

import java.io.BufferedReader; import


java.io.BufferedWriter; import
java.io.FileReader; import
java.io.FileWriter; import
java.io.IOException; public class
FILEPROGRAM {
public static void main(String[] args) {
writeToFile("sample.txt", "Hello, this is a sample type file.\nJava.\nPHP 3."); readAndCountLines("sample.txt");
}
private static void writeToFile(String fileName, String content) { try (BufferedWriter
writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(content); System.out.println("File writing
successful.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
private static void readAndCountLines(String fileName) { try
(BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
int lineCount = 0; String
line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
lineCount++;
}
System.out.println("Number of lines in the file: " + lineCount);
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
OUTPUT-
Q16. Write a Menu Driven Program for Blood Donor application for following task
a. Insert blood donor details into database. b. Display blood group-wise details of donors c. Update the address of
a specific donor. d. Delete the record of donors whose age is below 18.
Blood_Donor(Adhar,Name,Address,DOB,Gender,BloodGroup).

PROGRAM-

import java.util.ArrayList; import


java.util.Iterator; import
java.util.Scanner; class BloodDonor
{ String adhar;
String name;
String address;
String dob;
String gender;
String bloodGroup;
public BloodDonor(String adhar, String name, String address, String dob, String gender, String
bloodGroup) {
this.adhar = adhar; this.name =
name; this.address = address;
this.dob = dob; this.gender =
gender;
this.bloodGroup = bloodGroup;
}
public String toString() {
return "Adhar: " + adhar + ", Name: " + name + ", Address: " + address + ", DOB: " + dob + ",
Gender: " + gender + ", Blood Group: " + bloodGroup;
}
}
public class BloodDonorApplication { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in);
ArrayList<BloodDonor> donorList = new ArrayList<>(); int choice;
do { System.out.println("Menu:");
System.out.println("a. Insert blood donor details"); System.out.println("b. Display blood group-
wise details of donors"); System.out.println("c. Update the address of a specific donor");
System.out.println("d. Delete the record of donors whose age is below 18");
System.out.println("e. Exit"); System.out.print("Enter
your choice: "); choice = scanner.next().charAt(0);
switch (choice) {
case 'a':
System.out.print("Enter Adhar: "); String adhar =
scanner.next(); System.out.print("Enter Name: ");
String name = scanner.next();
System.out.print("Enter Address: "); String address =
scanner.next(); System.out.print("Enter DOB: ");
String dob = scanner.next(); System.out.print("Enter
Gender: "); String gender = scanner.next();
System.out.print("Enter Blood Group: "); String
bloodGroup = scanner.next();
donorList.add(new BloodDonor(adhar, name, address, dob, gender, bloodGroup));
System.out.println("Blood donor details added successfully."); break;
case 'b':
System.out.print("Enter Blood Group to display details: "); String
groupToDisplay = scanner.next(); Iterator<BloodDonor> iterator =
donorList.iterator(); while (iterator.hasNext()) {
BloodDonor donor = iterator.next();
if (donor.bloodGroup.equalsIgnoreCase(groupToDisplay))
{
System.out.println(donor);
}
}
break; case
'c':
System.out.print("Enter Adhar of the donor to update address: ");
String adharToUpdate = scanner.next(); for
(BloodDonor donor : donorList) {
if (donor.adhar.equals(adharToUpdate))
{ System.out.print("Enter new address: "); String
newAddress = scanner.next(); donor.address =
newAddress;
System.out.println("Address updated successfully."); break;
}
}
break; case
'd':
Iterator<BloodDonor> deleteIterator = donorList.iterator(); while
(deleteIterator.hasNext()) {
BloodDonor donor = deleteIterator.next();
// Assuming DOB format is YYYY-MM-DD and the year is at index 0-3
int year = Integer.parseInt(donor.dob.substring(0, 4)); if (2023 - year <
18) {
deleteIterator.remove(); System.out.println("Donor below 18
removed: " + donor);
}
}
break; case
'e':
System.out.println("Exiting the program."); break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
break;
}
} while (choice != 'e'); scanner.close();
}
}

OUTPUT-
Q17. Design GUI for Student Registration (Student ID, Name, Address, Gender, DOB, Course (C,C++,Java,
Python, Data Science, Hadoop, PowerBI, AWS. It should be in dropdown combo). Add the details in database.
(Use events for radio button, combobox )

PROGRAM-

import java.awt.event.ActionEvent; import


java.awt.event.ActionListener; import
javax.swing.ButtonGroup; import
javax.swing.JButton;
import javax.swing.JComboBox; import
javax.swing.JFrame; import
javax.swing.JLabel; import
javax.swing.JPanel; import
javax.swing.JRadioButton; import
javax.swing.JTextField;
public class StudentRegistrationGUI { public static
void main(String[] args) {
JFrame frame = new JFrame("Student Registration"); frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new
JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) { panel.setLayout(null);
JLabel nameLabel = new JLabel("Name:");
nameLabel.setBounds(10, 20, 80, 25); panel.add(nameLabel);
JTextField nameText = new JTextField(20);
nameText.setBounds(100, 20, 165, 25); panel.add(nameText);
JLabel idLabel = new JLabel("Student ID:");
idLabel.setBounds(10, 50, 80, 25); panel.add(idLabel);
JTextField idText = new JTextField(20); idText.setBounds(100,
50, 165, 25); panel.add(idText);
JLabel addressLabel = new JLabel("Address:");
addressLabel.setBounds(10, 80, 80, 25);
panel.add(addressLabel);
JTextField addressText = new JTextField(20);
addressText.setBounds(100, 80, 165, 25);
panel.add(addressText);
JLabel genderLabel = new JLabel("Gender:");
genderLabel.setBounds(10, 110, 80, 25); panel.add(genderLabel);
JRadioButton maleRadio = new JRadioButton("Male"); JRadioButton femaleRadio = new
JRadioButton("Female"); maleRadio.setBounds(100, 110, 80, 25);
femaleRadio.setBounds(180, 110, 80, 25); ButtonGroup genderGroup =
new ButtonGroup(); genderGroup.add(maleRadio);
genderGroup.add(femaleRadio); panel.add(maleRadio);
panel.add(femaleRadio);
JLabel dobLabel = new JLabel("DOB:");
dobLabel.setBounds(10, 140, 80, 25); panel.add(dobLabel);
JTextField dobText = new JTextField(20);
dobText.setBounds(100, 140, 165, 25); panel.add(dobText);
JLabel courseLabel = new JLabel("Course:");
courseLabel.setBounds(10, 170, 80, 25); panel.add(courseLabel);
String[] courses = {"C", "C++", "Java", "Python", "Data Science", "Hadoop", "PowerBI",
"AWS"};
JComboBox<String> courseCombo = new JComboBox<>(courses);
courseCombo.setBounds(100, 170, 165, 25); panel.add(courseCombo);
JButton submitButton = new JButton("Submit"); submitButton.setBounds(10,
200, 80, 25); panel.add(submitButton); submitButton.addActionListener(new
ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { String name =
nameText.getText();
String id = idText.getText();
String address = addressText.getText();
String gender = maleRadio.isSelected() ? "Male" : "Female"; String dob =
dobText.getText();
String course = (String) courseCombo.getSelectedItem();
// Add database logic here or print the details for testing
System.out.println("Name: " + name); System.out.println("Student ID: " + id);
System.out.println("Address: " + address); System.out.println("Gender: " +
gender); System.out.println("DOB: " + dob); System.out.println("Course: " +
course);
}
});
}
}
OUTPUT-
Q18. Write a servlet to check username & password passed from html page. If it is “Scott” & “tiger”, display
welcome message else show the same html page again. [With res.sendRedirect (http://localhost:8080/login.html)]

PROGRAM-

login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html> loginServlet
import java.io.IOException; import
java.io.PrintWriter;
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet { private static
final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username"); String password =
request.getParameter("password");
if ("Scott".equals(username) && "tiger".equals(password)) { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>"); out.println("<h2>Welcome,
Scott!</h2>"); out.println("</body></html>");
} else { response.sendRedirect("http://localhost:8080/login.html");
}
}
}

OUTPUT-
Q19. Write a servlet to add a Cookie to clients machine that stores username, current date & time. Display the same.

PROGRAM-

OUTPUT-
Audyogik Tantra Shikshan Sansth’s

INSTITUTE OF INDUSTRIAL & COMPUTER


MANAGEMENT AND RESEARCH
[ IICMR]
Plot HS-2 Sector 27-A, Near Sant Tukaram Garden, Pradhikaran, Nigdi, Pune -44.
Phone : 020-27657648 , 27650011 e-mail: info@iicmr.org

Ref.iicmr/MCA/Lab.let/ /2023 Date :

Certificate
This is to certify that Mr./Ms. PRATHAM VIKAS MEKHALE

is bonafide student of IICMR, studying in Master of Computer Application(MCA) Program (Batch 2023-2025).

He/She has successfully completed IT 11L Practical of Semester 1 (A.Y. 2023-2024).

Seat no 6812

Practical Coordinator HOD Director

Examiner 1. Examiner 2.

Date:
ATSS’s

INSTITUTE OF INDUSTRIAL AND COMPUTER MANAGEMENT AND RESEARCH NIGDI, PUNE


MCA Department

INDEX

Name: PRATHAM VIKAS MEKHALE Roll No. : _26

Teacher's
Sr. Course Page
Name of the Practical Sign with Remarks
No. Outcome No.
Date
Hybrid Inheritance - Class student should hold the
rollno,class test should hold marks scored in two
different subjects(m1,m2,m3), interface sports should
1 hold marks in sports and class Result should calculate CO1 5
the total marks. The program must print the rollno,
marks scored in individual subject marks, marks scored
in sports and the total marks.

Design an interface Advanced Arithmetic which


contains a method signature int divisor_sum(int n).
You need to write a class called MyCalculator which
2 implements the interface. divisor_sum(int n) function CO1 8
takes an integer as input and return the sum of all its
divisors. Divisors of 6 are 1, 2, 3 and 6, so divisor_sum
should return 12. (0<n<100)

Design an interface Shape which contain method


3 input() and area() to calculate area of circle, CO1 10
square and
rectangle
Write an application which will throw
4 OverwtProductException if Product weight is above CO1 12
60kg. (Use User defined exception)
For a given 2D square matrix of size N*N, the task is to
5 CO1 14
find the sum of elements in the Principal diagonals
Declare the integer array with 10 numbers. Generate 2
6 new arrays Prime and NonPrime with prime and non- CO1 16
prime numbers from main array.
Program to count occurrence of given number in an
7 CO1 18
integer array of size 10
8 Program to reverse string without using inbuilt methods. CO1 19

9 Program to remove duplicate characters from String CO1 20

Program to toggle case each character of every word of


10 CO1 21
string
Write a program to demonstrate Arrays class any 10
11 CO1 23
methods with examples (hint: Java.util.Arrays).
Write java program to generate 10 terms of Fibonacci
12 CO1 25
series using threads
Create a menu driven program for Bank
13 account(acc_no, Name, amt) (Hint: use vector) 1. Add CO1 26
2. Search 3. Delete 4. Display
Write a program to store employee in TreeSet and
14 CO1 29
employees should be in sorted order of their age.

Write a program to write and read file by character


15 CO1 31
Stream. Also count number of lines in the file.
Write a Menu Driven Program for Blood Donor
application for following task a. Insert blood donor
details into database. b. Display blood group-wise
details of donors c. Update the address of a specific
16 donor. d. Delete the record of donors whose age is CO3 33
below 18.
Blood_Donor(Adhar,Name,Address,DOB,Gender,Blo
odGroup)
Design GUI for Student Registration (Student ID,
Name, Address, Gender, DOB, Course (C, C++, Java,
17 Python, Data Science, Hadoop, PowerBI, AWS etc.) It CO2 37
should be in dropdown combo). Add the details in
database. (Use events for radio button, combobox )

Write a servlet to check username & password passed


from html page. If it is “Scott” & “tiger”, display
18 welcome message else show the same html page again. CO3 40
[With res.sendRedirect
(“http://localhost:8080/login.html”)]
Write a servlet to add a Cookie to clients machine that
19 CO3 42
stores username, current date & time. Display the same
Q1. Hybrid Inheritance - Class student should hold the rollno,class test should hold marks scored in two different
subjects(m1,m2,m3), interface sports should hold marks in sports and class Result should calculate the total marks.
The program must print the rollno, marks scored in individual subject marks, marks scored in sports and the total
marks

PROGRAM-

interface Sports {
int getSportsMarks();
}
class Student { int
rollno;

public Student(int rollno)


{ this.rollno = rollno;
}
}
class Test extends Student { int m1,
m2, m3;

public Test(int rollno, int m1, int m2, int m3) { super(rollno);
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
}
public void displayTestMarks() {
System.out.println("Test Marks: " + m1 + ", " + m2 + ", " + m3);
}
}
class Result extends Test implements Sports { int sportsMarks;

public Result(int rollno, int m1, int m2, int m3, int sportsMarks) { super(rollno, m1, m2,
m3);
this.sportsMarks = sportsMarks;
}
@Override
public int getSportsMarks() { return
sportsMarks;
}
public void displayResult() { System.out.println("Roll No: "
+ rollno); displayTestMarks();
System.out.println("Sports Marks: " + sportsMarks); int totalMarks =
m1 + m2 + m3 + sportsMarks; System.out.println("Total Marks: " +
totalMarks);
}
}
public class HybridInheritance {
public static void main(String[] args) {
Result resultInstance = new Result(26, 90, 85, 95, 75); resultInstance.displayResult();
}
}
OUTPUT-
Q2. Design an interface AdvancedArithmetic which contains a method signature int divisor_sum(int n). You need
to write a class called MyCalculator which implements the interface. divisor_sum(int n) function takes an integer
as input and return the sum of all its divisors. Divisors of 6 are 1, 2, 3 and 6, so divisor_sum should return 12.
(0<n<100).

PROGRAM-

interface AdvancedArithmetic { int


divisor_sum(int n);
}

class MyCalculator implements AdvancedArithmetic { @Override


public int divisor_sum(int n) { if (n <= 0
|| n >= 100) {
throw new IllegalArgumentException("Input must be in the range 0 < n < 100"); }

int sum = 0;
for (int i = 1; i <= n; i++) { if (n % i
== 0) {
sum += i;
} }
return sum;
}}
public class AdvancedArithmeticDivSum { public static void
main(String[] args) {
MyCalculator myCalculator = new MyCalculator(); int result =
myCalculator.divisor_sum(6); System.out.println("Divisor Sum: " +
result);
}
}

OUTPUT-

Q3. Design an interface Shape which contain method input() and area() to calculate area of cirlce,square and
rectangle.

PROGRAM-

import java.util.Scanner; interface Shape


{
void input();
double area();
}
class Circle implements Shape { double
radius;
public void input() {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the
radius of the circle: "); radius = scanner.nextDouble();
}
public double area() {
return Math.PI * radius * radius;
}
}
class Square implements Shape { double side;
public void input() {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the side
length of the square: "); side = scanner.nextDouble();
}
public double area() { return side
* side;
}
}
class Rectangle implements Shape { double length,
width;
public void input() {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the
length of the rectangle: "); length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: "); width =
scanner.nextDouble();
}
public double area() { return
length * width;
}
}
public class CRS {
public static void main(String[] args) { Shape circle
= new Circle(); circle.input();
System.out.println("Area of Circle: " + circle.area()); Shape square = new
Square();
square.input();
System.out.println("Area of Square: " + square.area()); Shape rectangle = new
Rectangle();
rectangle.input();
System.out.println("Area of Rectangle: " + rectangle.area());
}
}

OUTPUT-
Q4. Write an application which will throw OverwtProductException if Product weight is above 60kg. (Use User
defined exception).

PROGRAM-

class OverweightProductException extends Exception { public


OverweightProductException(String message) {
super(message);
}
}
class Product {
private String name; private
double weight;

public Product(String name, double weight) { this.name =


name;
this.weight = weight;
}
public void checkWeight() throws OverweightProductException { if (weight > 60) {
throw new OverweightProductException("Product weight exceeds 60 kg: " + weight + " kg");
} else {
System.out.println("Product weight is within the acceptable range.");
}
}
}
public class ProductApplication {
public static void main(String[] args) { try {
Product overweightProduct = new Product("HeavyProduct", 70);

overweightProduct.checkWeight();
} catch (OverweightProductException e) { System.out.println("Exception: " +
e.getMessage());
}
}
}

OUTPUT-
Q5. For a given 2D square matrix of size N*N, the task is to find the sum of elements in the Principal diagonals.

PROGRAM-

import java.util.Scanner;
public class PrincipalDiagonalSum { public static
void main(String[] args) {
Scanner scanner = new Scanner(System.in); System.out.print("Enter the size of the
square matrix (N): "); int N = scanner.nextInt();
int[][] matrix = new int[N][N]; System.out.println("Enter the elements of
the matrix:"); for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) { matrix[i][j] =
scanner.nextInt();
}
}
int principalDiagonalSum = calculatePrincipalDiagonalSum(matrix, N); System.out.println("Sum of elements in the
principal diagonal: " + principalDiagonalSum);
scanner.close();
}
private static int calculatePrincipalDiagonalSum(int[][] matrix, int N) { int sum = 0;
for (int i = 0; i < N; i++) { sum +=
matrix[i][i];
}
return sum;
}
}
OUTPUT-
Q6. Declare the integer array with 10 numbers. Generate 2 new arrays Prime and NonPrime with prime and non-
prime numbers from main array.

PROGRAM-

public class PrimeAndNonPrimeArrays { public static void


main(String[] args) { int[] originalArray =
{1,2,3,4,5,6,7,8,9,10};
int[] primeArray = generatePrimeArray(originalArray);
int[] nonPrimeArray = generateNonPrimeArray(originalArray);
System.out.println("Original Array: " + java.util.Arrays.toString(originalArray));
System.out.println("Prime Numbers: " + java.util.Arrays.toString(primeArray));
System.out.println("Non-Prime Numbers: " +
java.util.Arrays.toString(nonPrimeArray));
}
private static int[] generatePrimeArray(int[] array) { int primeCount =
countPrimes(array);
int[] primeArray = new int[primeCount]; int index =
0;
for (int num : array) { if
(isPrime(num)) {
primeArray[index] = num; index++;
}
}
return primeArray;
}
private static int[] generateNonPrimeArray(int[] array) { int
nonPrimeCount = array.length - countPrimes(array); int[] nonPrimeArray
= new int[nonPrimeCount];
int index = 0;
for (int num : array) { if (!
isPrime(num)) {
nonPrimeArray[index] = num; index++;
}
}
return nonPrimeArray;
}
private static int countPrimes(int[] array) { int count = 0;
for (int num : array) { if
(isPrime(num)) { count++;
}
}
return count;
}
private static boolean isPrime(int num) { if (num <=
1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i
== 0) {
return false;
}}
return true;
} }

OUTPUT
Q7 Program to count occurance of given number in an integer array of size 10.

PROGRAM-
import java.util.Scanner;
public class NumberOccurrenceInArray { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in); int[] array = new int[10];
System.out.println("Enter 10 numbers:"); for (int i = 0; i <
array.length; i++) { array[i] = scanner.nextInt(); }
System.out.print("Enter the number to count its occurrences: "); int numberToCount =
scanner.nextInt();
int occurrenceCount = countOccurrences(array, numberToCount); System.out.println("Number of occurrences of " +
numberToCount + ": " + occurrenceCount);
scanner.close(); }
private static int countOccurrences(int[] array, int number) { int count = 0;
for (int i = 0; i < array.length; i++) { if (array[i] ==
number) {
count++; } return
count; }} OUTPUT-
Q8.Program to reverse string without using inbuilt methods.

PROGRAM-
import java.util.Scanner; public class
ReverseString {
public static void main(String[] args) { Scanner scanner = new
Scanner(System.in); System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
String reversedString = reverseString(inputString); System.out.println("Reversed String: " +
reversedString); scanner.close();
}
private static String reverseString(String input) { char[] charArray =
input.toCharArray();
int start = 0;
int end = charArray.length - 1; while (start <
end) {
char temp = charArray[start]; charArray[start] =
charArray[end]; charArray[end] = temp;
start++;
end--; }
return new String(charArray); }}
OUTPUT-
Q9. Program to remove duplicate characters from String

PROGRAM-
import java.util.Scanner;
public class RemoveDuplicatesFromString { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in); System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
String resultString = removeDuplicates(inputString); System.out.println("String after removing
duplicates: " + resultString); scanner.close(); }
private static String removeDuplicates(String input) { char[] charArray =
input.toCharArray();
int length = charArray.length; for (int i = 0;
i < length; i++) {
for (int j = i + 1; j < length; j++) { if
(charArray[i] == charArray[j]) { charArray[j]
= '\0'; }}}
int newIndex = 0;
for (int i = 0; i < length; i++) { if
(charArray[i] != '\0') {
charArray[newIndex++] = charArray[i];}} return new
String(charArray, 0, newIndex); }} OUTPUT-
Q10. Program to toggle case each charatcer of every word of string.

PROGRAM-

import java.util.Scanner;

public class ToggleCaseInWords { public static void


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

System.out.print("Enter a string: "); String inputString


= scanner.nextLine();

String result = toggleCaseInWords(inputString); System.out.println("String with toggled case in

each word: " + result);

scanner.close();
}
private static String toggleCaseInWords(String input) { StringBuilder result = new
StringBuilder();

String[] words = input.split("\\s"); for (String

word : words) {
result.append(toggleCase(word)).append(" ");
}
return result.toString().trim();
}
private static String toggleCase(String word) { char[] characters =
word.toCharArray();

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


if (Character.isUpperCase(characters[i])) {
characters[i] = Character.toLowerCase(characters[i]);
} else if (Character.isLowerCase(characters[i])) {
characters[i] = Character.toUpperCase(characters[i]);
}
}

return new String(characters);


}
}

OUTPUT-
Q11. Write a program to demonstrate Arrays class any 10 methods with examples (hint: Java.util.Arrays).

PROGRAM -

import java.util.Arrays;
public class ArraysMethod10 {
public static void main(String[] args) { int[] array1 = {9,
10, 8, 5, 1, 2, 3, 6, 8, 11};
int[] array2 = {9, 10, 8, 5, 1, 2, 3, 6, 8, 11};
// 1. Sorting array Arrays.sort(array1);
System.out.println("1. Sorted array: " + Arrays.toString(array1));
// 2. Binary search int
searchKey = 4;
int index = Arrays.binarySearch(array1, searchKey); System.out.println("2. Index of " +
searchKey + ": " + index);
// 3. Comparing arrays
boolean areEqual = Arrays.equals(array1, array2); System.out.println("3. Arrays are equal: "
+ areEqual);
// 4. Filling array
int[] filledArray = new int[5];
Arrays.fill(filledArray, 42);
System.out.println("4. Filled array: " + Arrays.toString(filledArray));
// 5. Copying arrays
int[] copiedArray = Arrays.copyOf(array1, array1.length); System.out.println("5. Copied array: " +
Arrays.toString(copiedArray));
// 6. Copying a range of elements
int[] rangeCopiedArray = Arrays.copyOfRange(array1, 2, 7); System.out.println("6. Copied
range array: " + Arrays.toString(rangeCopiedArray));
// 7. Converting array to a string
String arrayAsString = Arrays.toString(array1); System.out.println("7. Array as string: " +
arrayAsString);
// 8. Finding the minimum value
int minValue = Arrays.stream(array1).min().orElse(0); System.out.println("8. Minimum
value: " + minValue);
// 9. Finding the maximum value
int maxValue = Arrays.stream(array1).max().orElse(0); System.out.println("9. Maximum
value: " + maxValue);
// 10. Checking if array contains a specific value
boolean containsValue = Arrays.asList(array1).contains(6); System.out.println("10. Array
contains value 6: " + containsValue);
}
}

OUTPUT-
Q12. Write java program to generate 10 terms of Fibonacci series using threads.

PROGRAM-
class FibonacciThread extends Thread { private int n;
public FibonacciThread(int n) { this.n = n;
}
public void run() { int a =
0, b = 1, c;
System.out.print("Fibonacci Series for " + n + " terms: "); for (int i = 1; i <= n;
++i) {
System.out.print(a + " "); c = a +
b;
a = b;
b = c;
}
System.out.println();
})
public class FibonacciSeriesWithThreads { public static void
main(String[] args) {
FibonacciThread thread1 = new FibonacciThread(10); FibonacciThread
thread2 = new FibonacciThread(10); thread1.start();
thread2.start();
}
}

OUTPUT-
Q13. Create a menu driven program for Bank account(acc_no, Name, amt) (Hint: use vector) 1. Add 2. Search 3.
Delete 4. Display

PROGRAM-

import java.util.Scanner; import


java.util.Vector; class
BankAccount {
int acc_no; String
name; double amt;
public BankAccount(int acc_no, String name, double amt) { this.acc_no = acc_no;
this.name = name; this.amt = amt;
}
public String toString() {
return "Account Number: " + acc_no + ", Name: " + name + ", Amount: "
+ amt;
}
}
public class BankManagementSystem { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in);
Vector<BankAccount> accounts = new Vector<>(); int choice;
do { System.out.println("Menu:");
System.out.println("1. Add");
System.out.println("2. Search");
System.out.println("3. Delete");
System.out.println("4. Display");
System.out.println("5. Exit");
System.out.print("Enter your choice: "); choice =
scanner.nextInt();
switch (choice) { case 1:
System.out.print("Enter Account Number: ");
int acc_no = scanner.nextInt();
System.out.print("Enter Name: "); String name =
scanner.next(); System.out.print("Enter Amount: ");
double amt = scanner.nextDouble();
accounts.add(new BankAccount(acc_no, name, amt));
System.out.println("Account added successfully."); break;
case 2:
System.out.print("Enter Account Number to search: "); int searchAccNo =
scanner.nextInt();
boolean found = false;
for (BankAccount account : accounts) { if
(account.acc_no == searchAccNo) {
System.out.println("Account found: " + account); found = true;
break;
}
}
if (!found) {
System.out.println("Account not found.");
}
break;
case 3:
System.out.print("Enter Account Number to delete: "); int deleteAccNo =
scanner.nextInt();
for (BankAccount account : accounts) { if
(account.acc_no == deleteAccNo) {
accounts.remove(account);
System.out.println("Account deleted successfully."); break;
}
}
break;
case 4:
System.out.println("List of Accounts:"); for
(BankAccount account : accounts) {
System.out.println(account);
}
break;
case 5:
System.out.println("Exiting the program."); break;
default:
System.out.println("Invalid choice. Please enter a valid option."); break;
}
} while (choice != 5); scanner.close();
}
}

OUTPUT-
Q14. Write a program to store employee in TreeSet and employees should be in sorted order of their age.

PROGRAM-

import java.util.*;

class Employee implements Comparable<Employee> { private String name;


private int age;

public Employee(String name, int age) { this.name = name;


this.age = age;
}
public String getName() { return
name;
}

public int getAge() { return


age;
}

@Override
public int compareTo(Employee other) { return
Integer.compare(this.age, other.age);
}
@Override
public String toString() {
return "Employee{name='" + name + "', age=" + age + '}';
}
}
public class EmployeeTreeSetExample { public static
void main(String[] args) {
TreeSet<Employee> employeeSet = new TreeSet<>();
employeeSet.add(new Employee("Pratham", 21));
employeeSet.add(new Employee("Dnayesh", 22));
employeeSet.add(new Employee("Tanvi", 22));
employeeSet.add(new Employee("Prashun", 22));

System.out.println("Employees sorted by age:"); for (Employee


employee : employeeSet) {
System.out.println(employee);
}
}
}

OUTPUT-
Q15.Write a program to write and read file by character Stream. Also count number of lines in the file.

PROGRAM-

import java.io.BufferedReader; import


java.io.BufferedWriter; import
java.io.FileReader; import
java.io.FileWriter; import
java.io.IOException; public class
FILEPROGRAM {
public static void main(String[] args) {
writeToFile("sample.txt", "Hello, this is a sample type file.\nJava.\nPHP 3."); readAndCountLines("sample.txt");
}
private static void writeToFile(String fileName, String content) { try (BufferedWriter
writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(content); System.out.println("File writing
successful.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
private static void readAndCountLines(String fileName) { try
(BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
int lineCount = 0; String
line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
lineCount++;
}
System.out.println("Number of lines in the file: " + lineCount);
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
OUTPUT-
Q16. Write a Menu Driven Program for Blood Donor application for following task
a. Insert blood donor details into database. b. Display blood group-wise details of donors c. Update the address of
a specific donor. d. Delete the record of donors whose age is below 18.
Blood_Donor(Adhar,Name,Address,DOB,Gender,BloodGroup).

PROGRAM-

import java.util.ArrayList; import


java.util.Iterator; import
java.util.Scanner; class BloodDonor
{ String adhar;
String name;
String address;
String dob;
String gender;
String bloodGroup;
public BloodDonor(String adhar, String name, String address, String dob, String gender, String
bloodGroup) {
this.adhar = adhar; this.name =
name; this.address = address;
this.dob = dob; this.gender =
gender;
this.bloodGroup = bloodGroup;
}
public String toString() {
return "Adhar: " + adhar + ", Name: " + name + ", Address: " + address + ", DOB: " + dob + ",
Gender: " + gender + ", Blood Group: " + bloodGroup;
}
}
public class BloodDonorApplication { public static void
main(String[] args) { Scanner scanner = new
Scanner(System.in);
ArrayList<BloodDonor> donorList = new ArrayList<>(); int choice;
do { System.out.println("Menu:");
System.out.println("a. Insert blood donor details"); System.out.println("b. Display blood group-
wise details of donors"); System.out.println("c. Update the address of a specific donor");
System.out.println("d. Delete the record of donors whose age is below 18");
System.out.println("e. Exit"); System.out.print("Enter
your choice: "); choice = scanner.next().charAt(0);
switch (choice) {
case 'a':
System.out.print("Enter Adhar: "); String adhar =
scanner.next(); System.out.print("Enter Name: ");
String name = scanner.next();
System.out.print("Enter Address: "); String address =
scanner.next(); System.out.print("Enter DOB: ");
String dob = scanner.next(); System.out.print("Enter
Gender: "); String gender = scanner.next();
System.out.print("Enter Blood Group: "); String
bloodGroup = scanner.next();
donorList.add(new BloodDonor(adhar, name, address, dob, gender, bloodGroup));
System.out.println("Blood donor details added successfully."); break;
case 'b':
System.out.print("Enter Blood Group to display details: "); String
groupToDisplay = scanner.next(); Iterator<BloodDonor> iterator =
donorList.iterator(); while (iterator.hasNext()) {
BloodDonor donor = iterator.next();
if (donor.bloodGroup.equalsIgnoreCase(groupToDisplay))
{
System.out.println(donor);
}
}
break; case
'c':
System.out.print("Enter Adhar of the donor to update address: ");
String adharToUpdate = scanner.next(); for
(BloodDonor donor : donorList) {
if (donor.adhar.equals(adharToUpdate))
{ System.out.print("Enter new address: "); String
newAddress = scanner.next(); donor.address =
newAddress;
System.out.println("Address updated successfully."); break;
}
}
break; case
'd':
Iterator<BloodDonor> deleteIterator = donorList.iterator(); while
(deleteIterator.hasNext()) {
BloodDonor donor = deleteIterator.next();
// Assuming DOB format is YYYY-MM-DD and the year is at index 0-3
int year = Integer.parseInt(donor.dob.substring(0, 4)); if (2023 - year <
18) {
deleteIterator.remove(); System.out.println("Donor below 18
removed: " + donor);
}
}
break; case
'e':
System.out.println("Exiting the program."); break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
break;
}
} while (choice != 'e'); scanner.close();
}
}

OUTPUT-
Q17. Design GUI for Student Registration (Student ID, Name, Address, Gender, DOB, Course (C,C++,Java,
Python, Data Science, Hadoop, PowerBI, AWS. It should be in dropdown combo). Add the details in database.
(Use events for radio button, combobox )

PROGRAM-

import java.awt.event.ActionEvent; import


java.awt.event.ActionListener; import
javax.swing.ButtonGroup; import
javax.swing.JButton;
import javax.swing.JComboBox; import
javax.swing.JFrame; import
javax.swing.JLabel; import
javax.swing.JPanel; import
javax.swing.JRadioButton; import
javax.swing.JTextField;
public class StudentRegistrationGUI { public static
void main(String[] args) {
JFrame frame = new JFrame("Student Registration"); frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new
JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) { panel.setLayout(null);
JLabel nameLabel = new JLabel("Name:");
nameLabel.setBounds(10, 20, 80, 25); panel.add(nameLabel);
JTextField nameText = new JTextField(20);
nameText.setBounds(100, 20, 165, 25); panel.add(nameText);
JLabel idLabel = new JLabel("Student ID:");
idLabel.setBounds(10, 50, 80, 25); panel.add(idLabel);
JTextField idText = new JTextField(20); idText.setBounds(100,
50, 165, 25); panel.add(idText);
JLabel addressLabel = new JLabel("Address:");
addressLabel.setBounds(10, 80, 80, 25);
panel.add(addressLabel);
JTextField addressText = new JTextField(20);
addressText.setBounds(100, 80, 165, 25);
panel.add(addressText);
JLabel genderLabel = new JLabel("Gender:");
genderLabel.setBounds(10, 110, 80, 25); panel.add(genderLabel);
JRadioButton maleRadio = new JRadioButton("Male"); JRadioButton femaleRadio = new
JRadioButton("Female"); maleRadio.setBounds(100, 110, 80, 25);
femaleRadio.setBounds(180, 110, 80, 25); ButtonGroup genderGroup =
new ButtonGroup(); genderGroup.add(maleRadio);
genderGroup.add(femaleRadio); panel.add(maleRadio);
panel.add(femaleRadio);
JLabel dobLabel = new JLabel("DOB:");
dobLabel.setBounds(10, 140, 80, 25); panel.add(dobLabel);
JTextField dobText = new JTextField(20);
dobText.setBounds(100, 140, 165, 25); panel.add(dobText);
JLabel courseLabel = new JLabel("Course:");
courseLabel.setBounds(10, 170, 80, 25); panel.add(courseLabel);
String[] courses = {"C", "C++", "Java", "Python", "Data Science", "Hadoop", "PowerBI",
"AWS"};
JComboBox<String> courseCombo = new JComboBox<>(courses);
courseCombo.setBounds(100, 170, 165, 25); panel.add(courseCombo);
JButton submitButton = new JButton("Submit"); submitButton.setBounds(10,
200, 80, 25); panel.add(submitButton); submitButton.addActionListener(new
ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { String name =
nameText.getText();
String id = idText.getText();
String address = addressText.getText();
String gender = maleRadio.isSelected() ? "Male" : "Female"; String dob =
dobText.getText();
String course = (String) courseCombo.getSelectedItem();
// Add database logic here or print the details for testing
System.out.println("Name: " + name); System.out.println("Student ID: " + id);
System.out.println("Address: " + address); System.out.println("Gender: " +
gender); System.out.println("DOB: " + dob); System.out.println("Course: " +
course);
}
});
}
}
OUTPUT-
Q18. Write a servlet to check username & password passed from html page. If it is “Scott” & “tiger”, display
welcome message else show the same html page again. [With res.sendRedirect (http://localhost:8080/login.html)]

PROGRAM-

login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html> loginServlet
import java.io.IOException; import
java.io.PrintWriter;
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet { private static
final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username"); String password =
request.getParameter("password");
if ("Scott".equals(username) && "tiger".equals(password)) { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>"); out.println("<h2>Welcome,
Scott!</h2>"); out.println("</body></html>");
} else { response.sendRedirect("http://localhost:8080/login.html");
}
}
}

OUTPUT-
Q19. Write a servlet to add a Cookie to clients machine that stores username, current date & time. Display the same.

PROGRAM-

import java.io.IOException;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String username = "JohnDoe"; // Replace this with your actual username retrieval logic

// Get current date and time

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String currentDateAndTime = dateFormat.format(new Date());

// Create a cookie with the username and current date & time

Cookie userCookie = new Cookie("userDetails", username + " at " + currentDateAndTime);


userCookie.setMaxAge(24 * 60 * 60); response.addCookie(userCookie);

out.println("<html><body>");

out.println("<h2>Cookie Set Successfully</h2>");

out.println("<p>Username: " + username + "</p>");

out.println("<p>Current Date & Time: " + currentDateAndTime + "</p>");

out.println("</body></html>");

out.close();

}
OUTPUT-

You might also like