0% found this document useful (0 votes)
64 views152 pages

Upasana+Abhishek Practical File

Uploaded by

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

Upasana+Abhishek Practical File

Uploaded by

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

EXPERIMENT 1

Objective: Write a program to print “Hello world”.


Program:
public class HelloWorld

public static void main(String[] args)

System.out.println("Hello, World!");

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 2
Objective: Write to find sum of n numbers.
Program:
import java.util.Scanner;

public class SumOfNNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int n = scanner.nextInt();

int sum = 0;

for (int i = 1; i <= n; i++) {

sum += i;

System.out.println("The sum of the first " + n + " numbers is: " + sum);

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 3

Objective: Write a program to find given number is palindrome or not.


Program:
import java.util.Scanner;

public class PalindromeChecker

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int originalNumber = number;

int reversedNumber = 0

while (number != 0)

int digit = number % 10;

reversedNumber = reversedNumber * 10 + digit;

number /= 10;

if (originalNumber == reversedNumber)

System.out.println(originalNumber + " is a palindrome.");

} else

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


{

System.out.println(originalNumber + " is not a palindrome.")

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 4

Objective: Write a program to take user input and make a calculator


by use of switch case.

Program:
import java.util.Scanner;

public class Calculator

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");

double num1 = scanner.nextDouble();

System.out.print("Enter the second number: ");

double num2 = scanner.nextDouble();

System.out.print("Enter an operator (+, -, *, /): ");

char operator = scanner.next().charAt(0);

double result;

switch (operator)

case '+':

result = num1 + num2

System.out.println("The result is: " + result);

break;

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


case '-':

result = num1 - num2;

System.out.println("The result is: " + result);

break;

case '*':

result = num1 * num2;

System.out.println("The result is: " + result);

break;

case '/':

if (num2 != 0) {

result = num1 / num2;

System.out.println("The result is: " + result);

else

System.out.println("Error! Division by zero is not allowed.");

break;

default:

System.out.println("Invalid operator! Please enter one of +, -, *, /.");

break;

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 5

Objective: Write a program to find all prime number upto given number.
Program:
import java.util.Scanner;

public class PrimeNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int n = scanner.nextInt();

for (int i = 2; i <= n; i++) {

if (isPrime(i))

System.out.print(i + " ");

public static boolean isPrime(int num)

if (num <= 1) {

return false;

for (int i = 2; i <= Math.sqrt(num); i++)

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


{

if (num % i == 0) {

return false;

return true;

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 6

Objective: Write a program to find given string is palindrome or not.

Program:
import java.util.Scanner;

public class PalindromeChecker

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

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

String original = scanner.nextLine();

String reversed = "";

for (int i = original.length() - 1; i >= 0; i--)

reversed += original.charAt(i);

if (original.equals(reversed))

System.out.println(original + " is a palindrome.");

else

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


{

System.out.println(original + " is not a palindrome.");

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 7

Objective: Write a program to find all uppercase letter in the given string.
Program:
import java.util.Scanner;

public class UppercaseLetters

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

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

String input = scanner.nextLine();

String uppercaseLetters = "";

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

char ch = input.charAt(i);

if (Character.isUpperCase(ch))

uppercaseLetters += ch;

System.out.println("Uppercase letters: " + uppercaseLetters);

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 8

Objective: Write a program to reverse a string word by word i.e input: java
world.

Program:
public class ReverseWords {

public static void main(String[] args) {

String input = "java world";

String output = reverseWords(input);

System.out.println(output);

public static String reverseWords(String sentence)

String[] words = sentence.split(" ")

StringBuilder reversedSentence = new StringBuilder();

for (int i = words.length - 1; i >= 0; i--) {

reversedSentence.append(words[i]);

if (i > 0) {

reversedSentence.append(" ");

return reversedSentence.toString();

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


}

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 9

Objective: Write a program to remove the space between the string i.e. input:
hello h r u?

Program:
public class RemoveSpaces

public static void main(String[] args)

String input = "hello h r u?";

String output = removeSpaces(input);

System.out.println(output);

public static String removeSpaces(String sentence)

return sentence.replace(" ", "");

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 10

Objective: Write a program to add Mr. in front of the string i.e.: input Uday
kapoor.

Program:
public class AddMr

public static void main(String[] args)

String input = "Uday Kapoor";

String output = addMrPrefix(input);

System.out.println(output);

public static String addMrPrefix(String name)

return "Mr. " + name;

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 11

Objective: write a program to show multilevel inheritance in java.


Program:
class Person {

String name;

int age;

public void displayPersonDetails() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

class Employee extends Person {

String employeeId;

String department;

public void displayEmployeeDetails() {

displayPersonDetails();

System.out.println("Employee ID: " + employeeId);

System.out.println("Department: " + department);

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


}

class Manager extends Employee {

int numberOfTeams;

public void displayManagerDetails() {

displayEmployeeDetails();

System.out.println("Number of Teams: " + numberOfTeams);

public class MultilevelInheritance {

public static void main(String[] args) {

Manager manager = new Manager();

manager.name = "Abhishek Kumar";

manager.age = 20;

manager.employeeId = "E0003";

manager.department = "Sales";

manager.numberOfTeams = 9;

manager.displayManagerDetails();

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003
EXPERIMENT 12
Objective: Write a program to show hierarchical inheritance in java.
Program:
class Person {

String name;

int age;

public void displayPersonDetails() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

class Student extends Person {

String studentId;

String course;

public void displayStudentDetails() {

displayPersonDetails();

System.out.println("Student ID: " + studentId);

System.out.println("Course: " + course);

class Teacher extends Person {

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


String employeeId;

String subject;

public void displayTeacherDetails() {

displayPersonDetails();

System.out.println("Employee ID: " + employeeId);

System.out.println("Subject: " + subject);

public class HierarchicalInheritance {

public static void main(String[] args) {

Student student = new Student();

student.name = "gillu";

student.age = 21;

student.studentId = "S123";

student.course = "Computer Science";

System.out.println("Student Details:");

student.displayStudentDetails();

System.out.println()

Teacher teacher = new Teacher();

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


teacher.name = "Mr. Smith";

teacher.age = 45;

teacher.employeeId = "T456";

teacher.subject = "Mathematics";

System.out.println("Teacher Details:");

teacher.displayTeacherDetails();

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 13

Objective: Write a program to show method overloading in java.


Program:
public class MethodOverloading {

public void display() {

System.out.println("Display method with no parameters");

public void display(int a) {

System.out.println("Display method with one integer parameter: " + a);

public void display(double a) {

System.out.println("Display method with one double parameter: " + a);

public void display(int a, String b) {

System.out.println("Display method with two parameters (int, String): " + a +


", " + b);

public void display(String a, int b) {

System.out.println("Display method with two parameters (String, int): " + a +


", " + b);

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


}

public static void main(String[] args) {

MethodOverloading obj = new MethodOverloading();

obj.display();

obj.display(10);

obj.display(5.5);

obj.display(20, "Hello");

and int)

obj.display("World", 30);

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 14

Objective: Write a program to show method overriding in java.


Program:
class Animal {

public void sound() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

public void sound() {

System.out.println("Dog barks");

class Cat extends Animal {

public void sound() {

System.out.println("Cat meows");

public class MethodOverriding {

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


public static void main(String[] args) {

Animal myAnimal = new Animal();

myAnimal.sound();

Animal myDog = new Dog();

myDog.sound();

Animal myCat = new Cat();

myCat.sound();

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 15

Objective: Write a program to show encapsulation in java.


Program:
public class EncapsulationExample {

private String name;

private int age;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public int getAge() {

return age;

public void setAge(int age) {

if (age > 0) {

this.age = age;

} else {

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


System.out.println("Please enter a valid age.");

public static void main(String[] args)

EncapsulationExample person = new EncapsulationExample();

person.setName("ABHISHEK KUMAR");

person.setAge(20);

System.out.println("Name: " + person.getName());

System.out.println("Age: " + person.getAge());

person.setAge(-5);

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 16

Objective: Write a program to show abstraction in java by use of abstract class.


Program:
abstract class Shape {

abstract void draw();

public void display() {

System.out.println("Displaying shape details");

class Circle extends Shape {

void draw() {

System.out.println("Drawing a Circle");

class Rectangle extends Shape {

void draw() {

System.out.println("Drawing a Rectangle");

public class AbstractionExample {

public static void main(String[] args) {

Shape circle = new Circle();

Shape rectangle = new Rectangle();

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


circle.draw();

circle.display();

rectangle.draw();

rectangle.display(); details

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 17

Objective: Write a program to show abstraction in java by use of interface.


Program:
interface Animal {

void sound();

default void sleep() {

System.out.println("Animal is sleeping");

class Dog implements Animal {

public void sound() {

System.out.println("Dog barks");

class Cat implements Animal {

public void sound() {

System.out.println("Cat meows");

public class AbstractionWithInterface {

public static void main(String[] args) {

Animal dog = new Dog();

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


Animal cat = new Cat();

dog.sound();

dog.sleep();

cat.sound();

cat.sleep();

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 18

Objective: Write a program to show try catch and finally block in java.
Program:
public class ExceptionHandlingExample

public static void main(String[] args)

try

int[] numbers = {1, 2, 3};

System.out.println("Accessing the fourth element: " + numbers[3]);

catch (ArrayIndexOutOfBoundsException e)

System.out.println("Exception caught: " + e);

finally

System.out.println("This is the finally block. It always executes.");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


System.out.println("Rest of the program continues...");

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 19

Objective: Write a program to make your own exception by use of throw


keyword.

Program:
class ThrowExcep

static void fun()

try

throw new NullPointerException("demo");

catch (NullPointerException e)

System.out.println("Caught inside fun().");

throw e;

public static void main(String args[])

try

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


{

fun();

catch (NullPointerException e) {

System.out.println("Caught in main.");

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 20

Objective: Write a program to make a thread by use of thread class.


Program:
class MyThread extends Thread {

private String threadName;

MyThread(String name) {

threadName = name;

public void run() {

for (int i = 1; i <= 5; i++) {

System.out.println(threadName + " - Count: " + i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(threadName + " interrupted.");

System.out.println(threadName + " exiting.");

public class ThreadDemo {

public static void main(String[] args) {

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


MyThread thread1 = new MyThread("Thread 1");

MyThread thread2 = new MyThread("Thread 2");

thread1.start();

thread2.start();

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 21

Objective: Write a program to make a thread by use of runnable interface.


Program:
public class RunnableDemo

public static void main(String[] args)

System.out.println("Main thread is- "

+ Thread.currentThread().getName());

Thread t1 = new Thread(new RunnableDemo().new RunnableImpl());

t1.start();

private class RunnableImpl implements Runnable

public void run()

System.out.println(Thread.currentThread().getName()

+ ", executing run() method!");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 22

Objective: Write a program to get priority of the main thread and change it to 8.
Program:
public class MainThreadPriorityDemo {

public static void main(String[] args) {

Thread mainThread = Thread.currentThread();

int initialPriority = mainThread.getPriority();

System.out.println("Initial priority of the main thread: " + initialPriority);

mainThread.setPriority(8);

int newPriority = mainThread.getPriority();

System.out.println("New priority of the main thread: " + newPriority);

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 23

Objective: Write a program to use synchronization in your thread by mutual


exclusion.

Program:
class Counter {

private int count = 0;

public synchronized void increment()

count++;

public int getCount()

return count;

class CounterThread extends Thread

private Counter counter;

private int incrementCount;

public CounterThread(Counter counter, int incrementCount)

this.counter = counter;

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


this.incrementCount = incrementCount;

public void run() {

for (int i = 0; i < incrementCount; i++)

counter.increment();

public class Main {

public static void main(String[] args) throws InterruptedException

Counter counter = new Counter();

int numThreads = 5;

int incrementCount = 1000;

CounterThread[] threads = new CounterThread[numThreads];

for (int i = 0; i < numThreads; i++)

threads[i] = new CounterThread(counter, incrementCount);

threads[i].start();

for (int i = 0; i < numThreads; i++)

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


threads[i].join();

System.out.println("Final count: " + counter.getCount());

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 24

Objective: Write a program to use synchronization in your thread by inter


process communication.

Program:
class SharedData {

private int data;

private boolean isDataAvailable = false;

while (isDataAvailable) {

try {

wait();

catch (InterruptedException e)

e.printStackTrace();

data = newData;

isDataAvailable = true;

System.out.println("Produced: " + data);

notify();

public synchronized int consume()

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


{

while (!isDataAvailable)

try

wait();

} catch (InterruptedException e)

e.printStackTrace();

System.out.println("Consumed: " + data);

isDataAvailable = false;

notify();

return data;

class ProducerThread extends Thread

private SharedData sharedData;

public ProducerThread(SharedData sharedData)

this.sharedData = sharedData;

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


public void run() {

for (int i = 1; i <= 5; i++)

sharedData.produce(i);

class ConsumerThread extends Thread {

private SharedData sharedData;

public ConsumerThread(SharedData sharedData) {

this.sharedData = sharedData;

public void run()

for (int i = 1; i <= 5; i++)

int consumedData = sharedData.consume();

public class Main

public static void main(String[] args)

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


SharedData sharedData = new SharedData();

ProducerThread producerThread = new ProducerThread(sharedData);

ConsumerThread consumerThread = new ConsumerThread(sharedData);

producerThread.start();

consumerThread.start();

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 25

Objective: Write a program for inputstream class and outputstream class and
copy the content of the file.

Program:
import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class FileCopyExample

public static void main(String[] args)

String inputFile = "input.txt";

String outputFile = "output.txt";

try (FileInputStream inputStream = new FileInputStream(inputFile);

FileOutputStream outputStream = new FileOutputStream(outputFile)) {

byte[] buffer = new byte[1024];

int bytesRead;

while ((bytesRead = inputStream.read(buffer)) != -1)

outputStream.write(buffer, 0, bytesRead);

System.out.println("File copied successfully.");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


catch (IOException e)

e.printStackTrace();

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 26

Objective: Write a program to make Arraylist and do some basic operations.


Program:
import java.util.ArrayList;

public class CustomArrayList {

private ArrayList<Integer> arrayList;

public CustomArrayList() {

this.arrayList = new ArrayList<>();

public void add(int element) {

arrayList.add(element);

System.out.println("Added " + element + " to the list.");

public void remove(int element) {

if (arrayList.contains(element)) {

arrayList.remove(Integer.valueOf(element));

System.out.println("Removed " + element + " from the list.");

} else {

System.out.println("Element " + element + " not found in the list.");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


}

public Integer get(int index) {

if (index >= 0 && index < arrayList.size()) {

return arrayList.get(index);

} else {

System.out.println("Index out of range.");

return null;

public int size() {

return arrayList.size();

public void iterate() {

for (int element : arrayList) {

System.out.println(element);

public static void main(String[] args) {

CustomArrayList customArrayList = new CustomArrayList();

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


// Adding elements

customArrayList.add(10);

customArrayList.add(20);

customArrayList.add(30);

// Accessing elements

Integer element = customArrayList.get(1);

if (element != null) {

System.out.println("Element at index 1: " + element);

// Removing an element

customArrayList.remove(20);

// Iterating over elements

System.out.println("Elements in the list:");

customArrayList.iterate();

// Getting the size of the list

System.out.println("Size of the list: " + customArrayList.size());

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


Program:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 27

Objective: Write a program to LinkedList and do some basic operations.


Program:
import java.io.*;

public class LinkedList {

Node head; // head of list

static class Node {

int data;

Node next;

Node(int d)

data = d;

next = null;

public static LinkedList insert(LinkedList list, int data)

Node new_node = new Node(data);

if (list.head == null) {

list.head = new_node;

else {

Node last = list.head;

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


while (last.next != null) {

last = last.next;

last.next = new_node;

return list;

public static void printList(LinkedList list)

Node currNode = list.head;

System.out.print("LinkedList: ");

while (currNode != null) {

System.out.print(currNode.data + " ");

currNode = currNode.next;

public static void main(String[] args)

/* Start with the empty list. */

LinkedList list = new LinkedList();

list = insert(list, 1);

list = insert(list, 2);

list = insert(list, 3);

list = insert(list, 4);

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


list = insert(list, 5);

list = insert(list, 6);

list = insert(list, 7);

list = insert(list, 8);

printList(list);

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 28

Objective: Write a program to make Stack and do some basic operation.


Program:
import java.util.Stack;

public class StackExample

public static void main(String[] args)

Stack<String> stack = new Stack<>();

stack.push("Apple");

stack.push("Banana");

stack.push("Cherry");

System.out.println("Stack: " + stack);

String poppedElement = stack.pop();

System.out.println("Popped element: " + poppedElement);

if (stack.isEmpty())

System.out.println("Stack is empty.");

else

System.out.println("Stack is not empty.");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


}

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 29

Objective: Write a program to make Queue and do some basic operations.


Program:
import java.util.LinkedList;

import java.util.Queue;

public class QueueExample

public static void main(String[] args)

Queue<Integer> queue = new LinkedList<>();

queue.add(170);

queue.add(620);

queue.add(390);

System.out.println("Queue: " + queue);

int removedElement = queue.remove();

System.out.println("Removed element: " + removedElement);

if (queue.isEmpty())

System.out.println("Queue is empty.");

else

System.out.println("Queue is not empty.");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


}

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 30

Objective: Write a program to make Dqueue and do some basic operations.


Program:
import java.util.ArrayDeque;

import java.util.Deque;

public class DequeExample

public static void main(String[] args)

Deque<String> deque = new ArrayDeque<>();

deque.addFirst("Frog");

deque.addLast("Bee");

System.out.println("Deque: " + deque);

String removedFromFront = deque.removeFirst();

String removedFromBack = deque.removeLast();

System.out.println("Removed from front: " + removedFromFront);

System.out.println("Removed from back: " + removedFromBack);

if (deque.isEmpty())

System.out.println("Deque is empty.");

else

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


System.out.println("Deque is not empty.");

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 31

Objective: Write a program to make Set and do some basic operation.


Program:
import java.util.HashSet;

import java.util.Set;

public class SetOperations

public static void main(String[] args)

Set<Integer> numbersSet = new HashSet<>();

numbersSet.add(5);

numbersSet.add(10);

numbersSet.add(15);

numbersSet.add(20);

System.out.println("Set: " + numbersSet);

numbersSet.remove(10);

if (numbersSet.contains(15))

System.out.println("Set contains 15.");

else

System.out.println("Set does not contain 15.");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


}

System.out.println("Updated Set: " + numbersSet);

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 32

Objective: Write a program to make HashSet and do some basic operation.


Program:
import java.util.HashSet;

import java.util.Set;

public class HashSetOperations

public static void main(String[] args)

Set<String> stringSet = new HashSet<>();

stringSet.add("Cat");

stringSet.add("Dog");

stringSet.add("Bird");

System.out.println("HashSet: " + stringSet);

stringSet.remove("Dog");

if (stringSet.contains("Cat"))

System.out.println("HashSet contains Cat.");

else

System.out.println("HashSet does not contain Cat.");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


System.out.println("Updated HashSet: " + stringSet);

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 33

Objective: Write a program to make SortedSet and do some basic operation.


Program:
import java.util.SortedSet;

import java.util.TreeSet;

public class SortedSetOperations

public static void main(String[] args)

SortedSet<Integer> numbersSortedSet = new TreeSet<>();

numbersSortedSet.add(30);

numbersSortedSet.add(10);

numbersSortedSet.add(50);

numbersSortedSet.add(20);

System.out.println("SortedSet: " + numbersSortedSet);

numbersSortedSet.remove(10);

if (numbersSortedSet.contains(30))

System.out.println("SortedSet contains 30.");

else

System.out.println("SortedSet does not contain 30.");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


}

System.out.println("Updated SortedSet: " + numbersSortedSet);

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 34

Objective: Write a program to make HashMap and do some basic operation.


Program:
import java.util.HashMap;

import java.util.Map;

public class HashMapOperations

public static void main(String[] args)

Map<String, Integer> ageMap = new HashMap<>();

ageMap.put("Alice", 25);

ageMap.put("Bob", 30);

ageMap.put("Charlie", 35);

System.out.println("HashMap: " + ageMap);

System.out.println("Bob's age is: " + ageMap.get("Bob"));

if (ageMap.containsKey("Alice"))

System.out.println("HashMap contains key 'Alice'.");

else

System.out.println("HashMap does not contain key 'Alice'.");

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


ageMap.remove("Charlie");

System.out.println("Updated HashMap: " + ageMap);

Output:

NAME: ABHISHEK KUMAR UNI. ROLL NO: 2201321520003


EXPERIMENT 1

Objective: Write a program to print “Hello world”.


Program:
public class HelloWorld

public static void main(String[] args)

System.out.println("Hello, World!");

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 2
Objective: Write to find sum of n numbers.
Program:
import java.util.Scanner;

public class SumOfNNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int n = scanner.nextInt();

int sum = 0;

for (int i = 1; i <= n; i++) {

sum += i;

System.out.println("The sum of the first " + n + " numbers is: " + sum);

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 3

Objective: Write a program to find given number is palindrome or not.


Program:
import java.util.Scanner;

public class PalindromeChecker

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int number = scanner.nextInt();

int originalNumber = number;

int reversedNumber = 0

while (number != 0)

int digit = number % 10;

reversedNumber = reversedNumber * 10 + digit;

number /= 10;

if (originalNumber == reversedNumber)

System.out.println(originalNumber + " is a palindrome.");

} else

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


{

System.out.println(originalNumber + " is not a palindrome.")

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 4

Objective: Write a program to take user input and make a calculator


by use of switch case.

Program:
import java.util.Scanner;

public class Calculator

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");

double num1 = scanner.nextDouble();

System.out.print("Enter the second number: ");

double num2 = scanner.nextDouble();

System.out.print("Enter an operator (+, -, *, /): ");

char operator = scanner.next().charAt(0);

double result;

switch (operator)

case '+':

result = num1 + num2

System.out.println("The result is: " + result);

break;

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


case '-':

result = num1 - num2;

System.out.println("The result is: " + result);

break;

case '*':

result = num1 * num2;

System.out.println("The result is: " + result);

break;

case '/':

if (num2 != 0) {

result = num1 / num2;

System.out.println("The result is: " + result);

else

System.out.println("Error! Division by zero is not allowed.");

break;

default:

System.out.println("Invalid operator! Please enter one of +, -, *, /.");

break;

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 5

Objective: Write a program to find all prime number upto given number.
Program:
import java.util.Scanner;

public class PrimeNumbers {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");

int n = scanner.nextInt();

for (int i = 2; i <= n; i++) {

if (isPrime(i))

System.out.print(i + " ");

public static boolean isPrime(int num)

if (num <= 1) {

return false;

for (int i = 2; i <= Math.sqrt(num); i++)

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


if (num % i == 0) {

return false;

return true;

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 6

Objective: Write a program to find given string is palindrome or not.

Program:
import java.util.Scanner;

public class PalindromeChecker

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

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

String original = scanner.nextLine();

String reversed = "";

for (int i = original.length() - 1; i >= 0; i--)

reversed += original.charAt(i);

if (original.equals(reversed))

System.out.println(original + " is a palindrome.");

else

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


System.out.println(original + " is not a palindrome.");

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 7

Objective: Write a program to find all uppercase letter in the given string.
Program:
import java.util.Scanner;

public class UppercaseLetters

public static void main(String[] args)

Scanner scanner = new Scanner(System.in);

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

String input = scanner.nextLine();

String uppercaseLetters = "";

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

char ch = input.charAt(i);

if (Character.isUpperCase(ch))

uppercaseLetters += ch;

System.out.println("Uppercase letters: " + uppercaseLetters);

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 8

Objective: Write a program to reverse a string word by word i.e input: java
world.

Program:
public class ReverseWords {

public static void main(String[] args) {

String input = "java world";

String output = reverseWords(input);

System.out.println(output);

public static String reverseWords(String sentence)

String[] words = sentence.split(" ")

StringBuilder reversedSentence = new StringBuilder();

for (int i = words.length - 1; i >= 0; i--) {

reversedSentence.append(words[i]);

if (i > 0) {

reversedSentence.append(" ");

return reversedSentence.toString();

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 9

Objective: Write a program to remove the space between the string i.e. input:
hello h r u?

Program:
public class RemoveSpaces

public static void main(String[] args)

String input = "hello h r u?";

String output = removeSpaces(input);

System.out.println(output);

public static String removeSpaces(String sentence)

return sentence.replace(" ", "");

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 10

Objective: Write a program to add Mr. in front of the string i.e.: input Uday
kapoor.

Program:
public class AddMr

public static void main(String[] args)

String input = "Uday Kapoor";

String output = addMrPrefix(input);

System.out.println(output);

public static String addMrPrefix(String name)

return "Mr. " + name;

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 11

Objective: write a program to show multilevel inheritance in java.


Program:
class Person {

String name;

int age;

public void displayPersonDetails() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

class Employee extends Person {

String employeeId;

String department;

public void displayEmployeeDetails() {

displayPersonDetails();

System.out.println("Employee ID: " + employeeId);

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


System.out.println("Department: " + department);

class Manager extends Employee {

int numberOfTeams;

public void displayManagerDetails() {

displayEmployeeDetails();

System.out.println("Number of Teams: " + numberOfTeams);

public class MultilevelInheritance {

public static void main(String[] args) {

Manager manager = new Manager();

manager.name = upasana singh";

manager.age = 21;

manager.employeeId = "E123";

manager.department = "Sales";

manager.numberOfTeams = 5;

manager.displayManagerDetails();

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 12
Objective: Write a program to show hierarchical inheritance in java.
Program:
class Person {

String name;

int age;

public void displayPersonDetails() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

class Student extends Person {

String studentId;

String course;

public void displayStudentDetails() {

displayPersonDetails();

System.out.println("Student ID: " + studentId);

System.out.println("Course: " + course);

class Teacher extends Person {

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


String employeeId;

String subject;

public void displayTeacherDetails() {

displayPersonDetails();

System.out.println("Employee ID: " + employeeId);

System.out.println("Subject: " + subject);

public class HierarchicalInheritance {

public static void main(String[] args) {

Student student = new Student();

student.name = "gillu";

student.age = 21;

student.studentId = "S123";

student.course = "Computer Science";

System.out.println("Student Details:");

student.displayStudentDetails();

System.out.println()

Teacher teacher = new Teacher();

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


teacher.name = "Mr. Smith";

teacher.age = 45;

teacher.employeeId = "T456";

teacher.subject = "Mathematics";

System.out.println("Teacher Details:");

teacher.displayTeacherDetails();

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 13

Objective: Write a program to show method overloading in java.


Program:
public class MethodOverloading {

public void display() {

System.out.println("Display method with no parameters");

public void display(int a) {

System.out.println("Display method with one integer parameter: " + a);

public void display(double a) {

System.out.println("Display method with one double parameter: " + a);

public void display(int a, String b) {

System.out.println("Display method with two parameters (int, String): " + a +


", " + b);

public void display(String a, int b) {

System.out.println("Display method with two parameters (String, int): " + a +


", " + b);

public static void main(String[] args) {

MethodOverloading obj = new MethodOverloading();

obj.display();
NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063
obj.display(10);

obj.display(5.5);

obj.display(20, "Hello");

and int)

obj.display("World", 30);

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 14

Objective: Write a program to show method overriding in java.


Program:
class Animal {

public void sound() {

System.out.println("Animal makes a sound");

class Dog extends Animal {

public void sound() {

System.out.println("Dog barks");

class Cat extends Animal {

public void sound() {

System.out.println("Cat meows");

public class MethodOverriding {

public static void main(String[] args) {

Animal myAnimal = new Animal();

myAnimal.sound();

Animal myDog = new Dog();

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


myDog.sound();

Animal myCat = new Cat();

myCat.sound();

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 15

Objective: Write a program to show encapsulation in java.


Program:
public class EncapsulationExample {

private String name;

private int age;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public int getAge() {

return age;

public void setAge(int age) {

if (age > 0) {

this.age = age;

} else {

System.out.println("Please enter a valid age.");

public static void main(String[] args)

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


{

EncapsulationExample person = new EncapsulationExample();

person.setName("upasana singh");

person.setAge(21);

System.out.println("Name: " + person.getName());

System.out.println("Age: " + person.getAge());

person.setAge(-5);

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 16
Objective: Write a program to show abstraction in java by use of abstract class.
Program:
abstract class Shape {

abstract void draw();

public void display() {

System.out.println("Displaying shape details");

class Circle extends Shape {

void draw() {

System.out.println("Drawing a Circle");

class Rectangle extends Shape {

void draw() {

System.out.println("Drawing a Rectangle");

public class AbstractionExample {

public static void main(String[] args) {

Shape circle = new Circle();

Shape rectangle = new Rectangle();

circle.draw();

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


circle.display();

rectangle.draw();

rectangle.display(); details

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 17

Objective: Write a program to show abstraction in java by use of interface.


Program:
interface Animal {

void sound();

default void sleep() {

System.out.println("Animal is sleeping");

class Dog implements Animal {

public void sound() {

System.out.println("Dog barks");

class Cat implements Animal {

public void sound() {

System.out.println("Cat meows");

public class AbstractionWithInterface {

public static void main(String[] args) {

Animal dog = new Dog();

Animal cat = new Cat();

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


dog.sound();

dog.sleep();

cat.sound();

cat.sleep();

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 18

Objective: Write a program to show try catch and finally block in java.
Program:
public class ExceptionHandlingExample

public static void main(String[] args)

try

int[] numbers = {1, 2, 3};

System.out.println("Accessing the fourth element: " + numbers[3]);

catch (ArrayIndexOutOfBoundsException e)

System.out.println("Exception caught: " + e);

finally

System.out.println("This is the finally block. It always executes.");

System.out.println("Rest of the program continues...");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


}

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 19

Objective: Write a program to make your own exception by use of throw


keyword.

Program:
class ThrowExcep

static void fun()

try

throw new NullPointerException("demo");

catch (NullPointerException e)

System.out.println("Caught inside fun().");

throw e;

public static void main(String args[])

try

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


fun();

catch (NullPointerException e) {

System.out.println("Caught in main.");

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 20

Objective: Write a program to make a thread by use of thread class.


Program:
class MyThread extends Thread {

private String threadName;

MyThread(String name) {

threadName = name;

public void run() {

for (int i = 1; i <= 5; i++) {

System.out.println(threadName + " - Count: " + i);

try {

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(threadName + " interrupted.");

System.out.println(threadName + " exiting.");

public class ThreadDemo {

public static void main(String[] args) {

MyThread thread1 = new MyThread("Thread 1");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


MyThread thread2 = new MyThread("Thread 2");

thread1.start();

thread2.start();

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 21

Objective: Write a program to make a thread by use of runnable interface.


Program:
public class RunnableDemo

public static void main(String[] args)

System.out.println("Main thread is- "

+ Thread.currentThread().getName());

Thread t1 = new Thread(new RunnableDemo().new RunnableImpl());

t1.start();

private class RunnableImpl implements Runnable

public void run()

System.out.println(Thread.currentThread().getName()

+ ", executing run() method!");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 22

Objective: Write a program to get priority of the main thread and change it to 8.
Program:
public class MainThreadPriorityDemo {

public static void main(String[] args) {

Thread mainThread = Thread.currentThread();

int initialPriority = mainThread.getPriority();

System.out.println("Initial priority of the main thread: " + initialPriority);

mainThread.setPriority(8);

int newPriority = mainThread.getPriority();

System.out.println("New priority of the main thread: " + newPriority);

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 23

Objective: Write a program to use synchronization in your thread by mutual


exclusion.

Program:
class Counter {

private int count = 0;

public synchronized void increment()

count++;

public int getCount()

return count;

class CounterThread extends Thread

private Counter counter;

private int incrementCount;

public CounterThread(Counter counter, int incrementCount)

this.counter = counter;

this.incrementCount = incrementCount;

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


}

public void run() {

for (int i = 0; i < incrementCount; i++)

counter.increment();

public class Main {

public static void main(String[] args) throws InterruptedException

Counter counter = new Counter();

int numThreads = 5;

int incrementCount = 1000;

CounterThread[] threads = new CounterThread[numThreads];

for (int i = 0; i < numThreads; i++)

threads[i] = new CounterThread(counter, incrementCount);

threads[i].start();

for (int i = 0; i < numThreads; i++)

threads[i].join();

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


}

System.out.println("Final count: " + counter.getCount());

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 24

Objective: Write a program to use synchronization in your thread by inter


process communication.

Program:
class SharedData {

private int data;

private boolean isDataAvailable = false;

while (isDataAvailable) {

try {

wait();

catch (InterruptedException e)

e.printStackTrace();

data = newData;

isDataAvailable = true;

System.out.println("Produced: " + data);

notify();

public synchronized int consume()

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


while (!isDataAvailable)

try

wait();

} catch (InterruptedException e)

e.printStackTrace();

System.out.println("Consumed: " + data);

isDataAvailable = false;

notify();

return data;

class ProducerThread extends Thread

private SharedData sharedData;

public ProducerThread(SharedData sharedData)

this.sharedData = sharedData;

public void run() {

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


for (int i = 1; i <= 5; i++)

sharedData.produce(i);

class ConsumerThread extends Thread {

private SharedData sharedData;

public ConsumerThread(SharedData sharedData) {

this.sharedData = sharedData;

public void run()

for (int i = 1; i <= 5; i++)

int consumedData = sharedData.consume();

public class Main

public static void main(String[] args)

SharedData sharedData = new SharedData();

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


ProducerThread producerThread = new ProducerThread(sharedData);

ConsumerThread consumerThread = new ConsumerThread(sharedData);

producerThread.start();

consumerThread.start();

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 25

Objective: Write a program for inputstream class and outputstream class and
copy the content of the file.

Program:
import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class FileCopyExample

public static void main(String[] args)

String inputFile = "input.txt";

String outputFile = "output.txt";

try (FileInputStream inputStream = new FileInputStream(inputFile);

FileOutputStream outputStream = new FileOutputStream(outputFile)) {

byte[] buffer = new byte[1024];

int bytesRead;

while ((bytesRead = inputStream.read(buffer)) != -1)

outputStream.write(buffer, 0, bytesRead);

System.out.println("File copied successfully.");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


catch (IOException e)

e.printStackTrace();

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 26

Objective: Write a program to make Arraylist and do some basic operations.


Program:
import java.util.ArrayList;

public class CustomArrayList {

private ArrayList<Integer> arrayList;

public CustomArrayList() {

this.arrayList = new ArrayList<>();

public void add(int element) {

arrayList.add(element);

System.out.println("Added " + element + " to the list.");

public void remove(int element) {

if (arrayList.contains(element)) {

arrayList.remove(Integer.valueOf(element));

System.out.println("Removed " + element + " from the list.");

} else {

System.out.println("Element " + element + " not found in the list.");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


}

public Integer get(int index) {

if (index >= 0 && index < arrayList.size()) {

return arrayList.get(index);

} else {

System.out.println("Index out of range.");

return null;

public int size() {

return arrayList.size();

public void iterate() {

for (int element : arrayList) {

System.out.println(element);

public static void main(String[] args) {

CustomArrayList customArrayList = new CustomArrayList();

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


// Adding elements

customArrayList.add(10);

customArrayList.add(20);

customArrayList.add(30);

// Accessing elements

Integer element = customArrayList.get(1);

if (element != null) {

System.out.println("Element at index 1: " + element);

// Removing an element

customArrayList.remove(20);

// Iterating over elements

System.out.println("Elements in the list:");

customArrayList.iterate();

// Getting the size of the list

System.out.println("Size of the list: " + customArrayList.size());

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


Program:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 27

Objective: Write a program to LinkedList and do some basic operations.


Program:
import java.io.*;

public class LinkedList {

Node head; // head of list

static class Node {

int data;

Node next;

Node(int d)

data = d;

next = null;

public static LinkedList insert(LinkedList list, int data)

Node new_node = new Node(data);

if (list.head == null) {

list.head = new_node;

else {

Node last = list.head;

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


while (last.next != null) {

last = last.next;

last.next = new_node;

return list;

public static void printList(LinkedList list)

Node currNode = list.head;

System.out.print("LinkedList: ");

while (currNode != null) {

System.out.print(currNode.data + " ");

currNode = currNode.next;

public static void main(String[] args)

/* Start with the empty list. */

LinkedList list = new LinkedList();

list = insert(list, 1);

list = insert(list, 2);

list = insert(list, 3);

list = insert(list, 4);

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


list = insert(list, 5);

list = insert(list, 6);

list = insert(list, 7);

list = insert(list, 8);

printList(list);

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 28

Objective: Write a program to make Stack and do some basic operation.


Program:
import java.util.Stack;

public class StackExample

public static void main(String[] args)

Stack<String> stack = new Stack<>();

stack.push("Apple");

stack.push("Banana");

stack.push("Cherry");

System.out.println("Stack: " + stack);

String poppedElement = stack.pop();

System.out.println("Popped element: " + poppedElement);

if (stack.isEmpty())

System.out.println("Stack is empty.");

else

System.out.println("Stack is not empty.");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


}

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 29

Objective: Write a program to make Queue and do some basic operations.


Program:
import java.util.LinkedList;

import java.util.Queue;

public class QueueExample

public static void main(String[] args)

Queue<Integer> queue = new LinkedList<>();

queue.add(170);

queue.add(620);

queue.add(390);

System.out.println("Queue: " + queue);

int removedElement = queue.remove();

System.out.println("Removed element: " + removedElement);

if (queue.isEmpty())

System.out.println("Queue is empty.");

else

System.out.println("Queue is not empty.");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


}

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 30

Objective: Write a program to make Dqueue and do some basic operations.


Program:
import java.util.ArrayDeque;

import java.util.Deque;

public class DequeExample

public static void main(String[] args)

Deque<String> deque = new ArrayDeque<>();

deque.addFirst("Frog");

deque.addLast("Bee");

System.out.println("Deque: " + deque);

String removedFromFront = deque.removeFirst();

String removedFromBack = deque.removeLast();

System.out.println("Removed from front: " + removedFromFront);

System.out.println("Removed from back: " + removedFromBack);

if (deque.isEmpty())

System.out.println("Deque is empty.");

else

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


System.out.println("Deque is not empty.");

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 31

Objective: Write a program to make Set and do some basic operation.


Program:
import java.util.HashSet;

import java.util.Set;

public class SetOperations

public static void main(String[] args)

Set<Integer> numbersSet = new HashSet<>();

numbersSet.add(5);

numbersSet.add(10);

numbersSet.add(15);

numbersSet.add(20);

System.out.println("Set: " + numbersSet);

numbersSet.remove(10);

if (numbersSet.contains(15))

System.out.println("Set contains 15.");

else

System.out.println("Set does not contain 15.");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


}

System.out.println("Updated Set: " + numbersSet);

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 32

Objective: Write a program to make HashSet and do some basic operation.


Program:
import java.util.HashSet;

import java.util.Set;

public class HashSetOperations

public static void main(String[] args)

Set<String> stringSet = new HashSet<>();

stringSet.add("Cat");

stringSet.add("Dog");

stringSet.add("Bird");

System.out.println("HashSet: " + stringSet);

stringSet.remove("Dog");

if (stringSet.contains("Cat"))

System.out.println("HashSet contains Cat.");

else

System.out.println("HashSet does not contain Cat.");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


System.out.println("Updated HashSet: " + stringSet);

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 33

Objective: Write a program to make SortedSet and do some basic operation.


Program:
import java.util.SortedSet;

import java.util.TreeSet;

public class SortedSetOperations

public static void main(String[] args)

SortedSet<Integer> numbersSortedSet = new TreeSet<>();

numbersSortedSet.add(30);

numbersSortedSet.add(10);

numbersSortedSet.add(50);

numbersSortedSet.add(20);

System.out.println("SortedSet: " + numbersSortedSet);

numbersSortedSet.remove(10);

if (numbersSortedSet.contains(30))

System.out.println("SortedSet contains 30.");

else

System.out.println("SortedSet does not contain 30.");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


}

System.out.println("Updated SortedSet: " + numbersSortedSet);

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 34

Objective: Write a program to make HashMap and do some basic operation.


Program:
import java.util.HashMap;

import java.util.Map;

public class HashMapOperations

public static void main(String[] args)

Map<String, Integer> ageMap = new HashMap<>();

ageMap.put("Alice", 25);

ageMap.put("Bob", 30);

ageMap.put("Charlie", 35);

System.out.println("HashMap: " + ageMap);

System.out.println("Bob's age is: " + ageMap.get("Bob"));

if (ageMap.containsKey("Alice"))

System.out.println("HashMap contains key 'Alice'.");

else

System.out.println("HashMap does not contain key 'Alice'.");

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


ageMap.remove("Charlie");

System.out.println("Updated HashMap: " + ageMap);

Output:

NAME: UPASANA KUMARI UNI. ROLL NO: 2201321520063


EXPERIMENT 3
EXPERIMENT 4

You might also like