Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

EXPERIMENT-1

AIM: Create a java program to implement stack and queue concept.

SOFTWARE USED : Apache NetBeans IDE 15

THEORY :-

STACK : A stack is a linear data structure that follows the LIFO (Last–In, First–Out) principle.
That means the objects can be inserted or removed only at one end of it, also called a top.

The stack supports the following operations:

 push inserts an item at the top of the stack (i.e., above its current top element).
 pop removes the object at the top of the stack and returns that object from the function.
The stack size will be decremented by one.

 isEmpty tests if the stack is empty or not.


 isFull tests if the stack is full or not.
 peek returns the object at the top of the stack without removing it from the stack or
modifying the stack in any way.
 size returns the total number of elements present in the stack.

QUEUE :A queue is a linear data structure that follows the FIFO (First–In, First–Out) principle.
That means the object inserted first will be the first one out, followed by the object inserted next.

The queue supports the following core operations:

1. Enqueue: Inserts an item at the rear of the queue.


2. Dequeue: Removes the object from the front of the queue and returns it, thereby
decrementing queue size by one.
3. Peek: Returns the object at the front of the queue without removing it.
4. IsEmpty: Tests if the queue is empty or not.
5. Size: Returns the total number of elements present in the queue.

Dhriti 02213302720 Page 1


CODE :-

i. STACK IMPLEMENTATION

public class S1 {
private intarr[];
privateint top;
privateint capacity;

// Constructor to initialize the stack


S1(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}

// Utility function to add an element `x` to the stack


public void push(int x)
{
if (isFull())
{
System.out.println("Overflow\nProgram Terminated\n");
System.exit(-1);
}
System.out.println("Inserting " + x);
arr[++top] = x;
}

// Utility function to pop a top element from the stack


public intpop()
{
// check for stack underflow
if (isEmpty())
{
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
}
System.out.println("Removing " + peek());
// decrease stack size by 1 and (optionally) return the popped element
return arr[top--];
}

// Utility function to return the top element of the stack


public intpeek()
{
if (!isEmpty()) {

Dhriti 02213302720 Page 2


return arr[top];
}
else {
System.exit(-1);
}

return -1;
}

// Utility function to return the size of the stack


public intsize() {
return top + 1;
}
// Utility function to check if the stack is empty or not
public booleanisEmpty() {
return top == -1; // or return size() == 0;
}
// Utility function to check if the stack is full or not
public booleanisFull() {
return top == capacity - 1; // or return size() == capacity;
}

public static void main (String[] args)


{
S1 stack = new S1(3);

stack.push(1); // inserting 1 in the stack


stack.push(2); // inserting 2 in the stack

stack.pop(); // removing the top element (2)


stack.pop(); // removing the top element (1)

stack.push(3); // inserting 3 in the stack

System.out.println("The top element is " + stack.peek());


System.out.println("The stack size is " + stack.size());
// check if the stack is empty
if (stack.isEmpty()) {
System.out.println("The stack is empty");
}
else {
System.out.println("The stack is not empty");
}
}
}

Dhriti 02213302720 Page 3


OUTPUT :-

Dhriti 02213302720 Page 4


ii. QUEUE IMPLEMENTATION
public class Queue {
// A class to represent a queue
private int[] arr; // array to store queue elements
private intfront; // front points to the front element in the queue
private intrear; // rear points to the last element in the queue
private intcapacity; // maximum capacity of the queue
private intcount; // current size of the queue
// Constructor to initialize a queue
Queue(int size)
{
arr = new int[size];
capacity = size;
front = 0;
rear = -1;
count = 0;
}
// Utility function to dequeue the front element
public intdequeue()
{
// check for queue underflow
if (isEmpty())
{
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
}
int x = arr[front];
System.out.println("Removing " + x);
front = (front + 1) % capacity;
count--;
return x;
}
// Utility function to add an item to the queue
public void enqueue(int item)
{
// check for queue overflow
if (isFull())
{
System.out.println("Overflow\nProgram Terminated");
System.exit(-1);
}
System.out.println("Inserting " + item);
rear = (rear + 1) % capacity;
arr[rear] = item;
count++;
}

Dhriti 02213302720 Page 5


// Utility function to return the front element of the queue
public intpeek()
{
if (isEmpty())
{
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
}
return arr[front];
}
// Utility function to return the size of the queue
public intsize() {
return count;
}
// Utility function to check if the queue is empty or not
public booleanisEmpty() {
return (size() == 0);
}
// Utility function to check if the queue is full or not
public booleanisFull() {
return (size() == capacity);
}
public static void main (String[] args)
{
// create a queue of capacity 5
Queue q = new Queue(5);

q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
System.out.println("The front element is " + q.peek());
q.dequeue();
System.out.println("The front element is " + q.peek());
System.out.println("The queue size is " + q.size());

q.dequeue();
q.dequeue();

if (q.isEmpty()) {
System.out.println("The queue is empty");
}
else {
System.out.println("The queue is not empty");
}
}
}
OUTPUT :-
Dhriti 02213302720 Page 6
EXPERIMENT-2

Dhriti 02213302720 Page 7


AIM: Write a program in java to implement Method Overloading (Compile time Polymorphism)

SOFTWARE USED : Apache NetBeans IDE 15

THEORY :-

Compile-time Polymorphism
Compile-time polymorphism is also known as static polymorphism or early binding. Compile-
time polymorphism is a polymorphism that is resolved during the compilation process.
Overloading of methods is called through the reference variable of a class. Compile-time
polymorphism is achieved by method overloading and operator overloading.

1. Method overloading
We can have one or more methods with the same name that are solely distinguishable by
argument numbers, type, or order.
Method Overloading occurs when a class has many methods with the same name but different
parameters. Two or more methods may have the same name if they have other numbers of
parameters, different data types, or different numbers of parameters and different data types.  
Example: 
void sum() { ... }
void sum(int num1 ) { ... }
void sum(float num1) { ... }
void sum(int num1 , float num2 ) { ... }
(a). Method overloading by changing the number of parameters  
 In this type, Method overloading is done by overloading methods in the function call with a
varied number of parameters
 Example:
show( char a )
show( char a ,char b )
(b). Method overloading by changing Datatype of parameter
In this type, Method overloading is done by overloading methods in the function call with
different types of parameters
Example:
show( float a float b)
show( int a, int b )
(c). By changing the sequence of parameters  
In this type, overloading is dependent on the sequence of the parameters  
Example:
show( int a, float b )
show( float a, int b )
Here in this example, The parameters int and float are used in the first declaration. The
parameters are int and float in the second declaration, but their order in the parameter list is
different.

CODE :-

Dhriti 02213302720 Page 8


class Overload//Java program to implement method overloading in java

{
void demo (int a) // First Method
{
System.out.println ("a: " + a);
}

void demo (int a, int b) // Second Method


{
System.out.println ("a and b: " + a + "," + b);
}

double demo(double a) // Third Method


{
System.out.println("double a: " + a); return a*a;
}
}

class MethodOverloading
{
public static void main (String args[]) // main function
{
Overload O1 = new Overload(); double result;

O1 .demo(10);

O1 .demo(10, 20);
result = O1 .demo(5.5);

System.out.println("O/P : " + result);


}
}

OUTPUT :-

Dhriti 02213302720 Page 9


EXPERIMENT-3
AIM: Develop an analog clock using applet.

Dhriti 02213302720 Page 10


SOFTWARE USED : Apache NetBeans IDE 15

THEORY :-

Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

CODE :-

import java.applet.Applet;
import java.awt.*;

Dhriti 02213302720 Page 11


import java.util.*;
@SuppressWarnings("deprecation")
public class analog1 extends Applet {
@Override
public void init()
{
// Applet window size & color
this.setSize(new Dimension(800, 400));
setBackground(new Color(50, 50, 50));
new Thread() {
@Override
public void run()
{
while (true) {
repaint();
delayAnimation();
}
}
}.start();
}
// Animating the applet
private void delayAnimation()
{
try {
// Animation delay is 1000 milliseconds
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
// Paint the applet
@Override
public void paint(Graphics g)
{
// Get the system time
Calendar time = Calendar.getInstance();

int hour = time.get(Calendar.HOUR_OF_DAY);


int minute = time.get(Calendar.MINUTE);
int second = time.get(Calendar.SECOND);
Dhriti 02213302720 Page 12
// 12 hour format
if (hour > 12) {
hour -= 12;
}
// Draw clock body center at (400, 200)
g.setColor(Color.white);
g.fillOval(300, 100, 200, 200);
// Labeling
g.setColor(Color.black);
g.drawString("12", 390, 120);
g.drawString("9", 310, 200);
g.drawString("6", 400, 290);
g.drawString("3", 480, 200);
// Declaring variables to be used
double angle;
int x, y;
// Second hand's angle in Radian
angle = Math.toRadians((15 - second) * 6);
// Position of the second hand
// with length 100 unit
x = (int)(Math.cos(angle) * 100);
y = (int)(Math.sin(angle) * 100);
// Red color second hand
g.setColor(Color.red);
g.drawLine(400, 200, 400 + x, 200 - y);
// Minute hand's angle in Radian
angle = Math.toRadians((15 - minute) * 6);
// Position of the minute hand
// with length 80 unit
x = (int)(Math.cos(angle) * 80);
y = (int)(Math.sin(angle) * 80);
// blue color Minute hand
g.setColor(Color.blue);
g.drawLine(400, 200, 400 + x, 200 - y);
// Hour hand's angle in Radian
angle = Math.toRadians((15 - (hour * 5)) * 6);
// Position of the hour hand
// with length 50 unit
x = (int)(Math.cos(angle) * 50);
y = (int)(Math.sin(angle) * 50);
// Black color hour hand
Dhriti 02213302720 Page 13
g.setColor(Color.black);
g.drawLine(400, 200, 400 + x, 200 - y);
}
}

OUTPUT :-

Dhriti 02213302720 Page 14


EXPERIMENT-4

Dhriti 02213302720 Page 15


AIM: Write a program to access super class methods and instance variables without super
keyword in java

SOFTWARE USED : Apache NetBeans IDE 15

THEORY :-

SUPER CLASS : The parent class from which many subclasses can be created. All the
subclasses have all the attributes and properties that have parent class. 

INHERITANCE is the mechanism of object-oriented language by which any class can (child
class) inherit other class all the properties and behaviour of the parent class.

PARENT CLASS: FRUIT

CHILD CLASS: APPLE

 There are two methods to call the instance variables and methods of the superclass
(parent class) in the child class.
1) First Method: super keyword is one of the reserved words in java. Super refers to an
object of the parent class.
 Uses:
 We can invoke the overridden method of the parent class with the help of the super
keyword.
 super() is used for executing the constructor of the parent class and should be used
in the first line in the derived class constructor.

2) Second Method: Without using the keyword super keyword after inheritance all the
methods and instance variables of the parent class is inherited by the child class. So we
can direct them in the child class.

G Class: parent class

Arraylist Class: Derived class

Dhriti 02213302720 Page 16


CODE :-

class Arraylist extends G {


void hello()

System.out.println("This is the Main class");

}
public static void main(String args[])

// calling the constructor

Arraylistob = new Arraylist();

// calling the inherited name method

ob.name();

class G{

G()

{ // constructor of the parent class

System.out.println("This is the constructor");

void name() { System.out.println("Hello world"); }

Dhriti 02213302720 Page 17


OUTPUT :-

EXPERIMENT-5

Dhriti 02213302720 Page 18


AIM: Write a program to convert the content of a given file into the uppercase content of the
same file in java.

SOFTWARE USED : Apache NetBeans IDE 15

CODE :-
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
public class Uppercase {
public static void main(String[] args) {
try {
File file = new File("e.txt");
if (!file.exists()) {
// File does not exist, print error message and return
System.err.println("Error: file " + file.getName() + " does not exist.");
return;
}
FileReader reader = new FileReader("e.txt");
String result = "";
int data;
int data2;
System.out.println("Before :");
while ((data = reader.read()) != -1) {
System.out.println((char)data);
data2 = Character.toUpperCase(data);
result += (char)data2;
}
reader.close();
System.out.println("After :");
System.out.println(result);
FileWriter writer = new FileWriter("e.txt");
writer.write(result);
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT :-

Dhriti 02213302720 Page 19


EXPERIMENT-6

Dhriti 02213302720 Page 20


AIM: Write a program to create a customized exception and also make use of all 5 exception
keywords in java.

SOFTWARE USED : Apache NetBeans IDE 15

THEORY :-

EXCEPTION- In Java, an exception is an event that disrupts the normal flow of the program. It
is an object which is thrown at runtime.

EXCEPTION HANDLING - The Exception Handling in Java is one of the


powerful mechanismto handlethe runtime errors so that the normal flow of the application can be
maintained.

EXCEPTION HANDLING KEYWORDS :-

Java provides five keywords that are used to handle the exception. The following table describes
each.

KEYWORD DESCRIPTION

try The "try" keyword is used to specify a block where we should place an exception code.
It means we can't use try block alone. The try block must be followed by either catch or
finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.

CUSTOMIZED EXCEPTION - Java provides us the facility to create our own exceptions
which are basically derived classes of Exception. Creating our own Exception is known as a
custom exception or user-defined exception. Basically, Java custom exceptions are used to
customize the exception according to user needs.

CODE :-

Dhriti 02213302720 Page 21


class exception {
// Unhandled Exceptions are specified
static void procA() throws IllegalAccessException {
System.out.println("inside procA");
throw new IllegalAccessException("procA throwing an exception which it cant handle on its
own using 'throws' clause");
}
static void procB() {
try {
System.out.println("inside procB");
throw new NullPointerException("Manually thrown Exception using 'throw' clause");
}
catch (NullPointerException e)
{
System.out.println(e+"\nCaught Inside procB");
}
finally {
System.out.println("procB finally statement. Executed after the try and catch clause\n");
}
}
// Return from within a try block.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally statement. Excecuted after try and before its return
statement");
}
}
public static void main(String args[]) {
try {
procA();
} catch (IllegalAccessException e) {
System.out.println(e+"\nException caught in procA using 'catch' \n");
}
procB();
procC();
}
}

OUTPUT :-

Dhriti 02213302720 Page 22


EXPERIMENT-7

Dhriti 02213302720 Page 23


AIM: Write a program to implement the concept of multithreading using : a) Runnable Interface
b) Thread class

SOFTWARE USED : Apache NetBeans IDE 15

THEORY :-

Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.
Threads can be created by using two mechanisms : 
1. Implementing the Runnable Interface
2. Extending the Thread class 

THREAD CREATION BY IMPLEMENTING THE RUNNABLE INTERFACE :

We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.  

THREAD CREATION BY EXTENDING THE THREAD CLASS :

We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We create an
object of our new class and call start() method to start the execution of a thread. Start() invokes
the run() method on the Thread object.

THREAD CLASS VS RUNNABLE INTERFACE :

1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t
support multiple inheritance. But, if we implement the Runnable interface, our class can
still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it
provides some inbuilt methods like yield(), interrupt() etc. that are not available in
Runnable interface.
3. Using runnable will give you an object that can be shared amongst multiple threads.  

CODE :-

Dhriti 02213302720 Page 24


a) RUNNABLE INTERFACE

public class Multi1 implements Runnable {


public void run() {
System.out.println("thread is running...through Runnable interface");
}
public static void main(String[] args) {
Multi1 m1=new Multi1();
Thread t1 =new Thread(m1);
t1.start();
}
}

b) THREAD CLASS

public class Multi extends Thread {


public void run() {
System.out.println("thread is running...through Thread class");
}

public static void main(String[] args) {


Multi t1=new Multi();
t1.start();
}
}

OUTPUT :-

Dhriti 02213302720 Page 25


a) RUNNABLE INTERFACE

b) THREAD CLASS

Dhriti 02213302720 Page 26

You might also like