Java Harsh Pratap
Java Harsh Pratap
OF
ESSENTIAL OF INFORMATION AND TECHNOLOGY LAB
SESSION: 2024-25
Submitted By: Harsh Pratap
Roll No: 2022027522
Semester: V
B. Tech (CSE)
1
INDEX
Page
S. No. Title of Practical Practical Date Signature
No.
1.
Write a java Package with Stack and queue
classes
3.
Develop with suitable hierarchy, class for
point, shape rectangle, square, circle, ellipse,
triangle, polygenetic.
4.
Design a simple test application to
demonstrate dynamic polymorphism.
6.
Develop two different classes that implement
this interface. One using array and other
using linked list.
7.
Develop a simple paint like program that can
draw basic graphical primitives.
8.
Develop a scientific calculator using event
driven programming.
9.
Develop a template for linked list class along
with its members in java.
10.
Write a program to insert and view data using
servlets.
2
Practical – 1
Aim: Write a Java Package with Stack and Queue classes.
Source code:
import java.io.*;
import queuepackage.queue2;
import stackpackage.stack2;
1
switch (choice)
{ case 1 -> {
// Push
int value;
System.out.println("Enter the element to push:");
value = Integer.parseInt(sc.readLine());
s.push(value);
}
case 2 -> // Pop
s.pop();
}
case 2 -> {
// Queue operations
queue2 theQueue = new queue2(5);
theQueue.insert(10);
theQueue.insert(20);
theQueue.insert(30);
theQueue.insert(40);
theQueue.remove();
theQueue.remove();
theQueue.remove();
2
theQueue.insert(50);
theQueue.insert(60);
theQueue.insert(70);
theQueue.insert(80);
while (!theQueue.isEmpty()) {
long n1 = theQueue.remove();
System.out.print(n1 + " ");
}
System.out.println();
}
default ->System.out.println("Invalid choice");
}
} while (c != 0);
} catch (IOException | NumberFormatException e) {
}
}
Stack Package:
package stackpackage;
public class stack2
{ int[] a;
int top;
public stack2(int n) {
a = new int[n];
top = -1;
}
public void push(int val) {
if (top == a.length - 1) {
System.out.println("Stack overflow");
3
} else {
top++;
a[top] =
val;
}
}
public void pop()
{ if (top == -1) {
System.out.println("Stack underflow");
} else {
System.out.println("Element popped: " + a[top]);
top--;
}
}
Queue Package:
package queuepackage;
public class queue2
{ private int maxsize;
private long[] queArray;
4
private int front;
5
private int rear;
private int nitems;
public queue2(int s) {
maxsize = s;
queArray = new long[maxsize];
front = 0;
rear = -1;
nitems = 0;
}
public void insert(long j)
{ if (rear == maxsize - 1)
{ rear = -1;
}
queArray[++rear] =
j; nitems++;
}
public long remove() {
long temp = queArray[front++];
if (front == maxsize) {
front = 0;
}
nitems--;
return temp;
}
public long peekFront()
{ return queArray[front];
}
public booleanisEmpty()
{ return (nitems == 0);
}
public booleanisFull() {
6
return (nitems == maxsize);
}
public int size()
{ return nitems;
}
}
Output:
7
Practical – 2
Aim: Design a class for Complex numbers in Java. In addition to methods for basic operations on complex
numbers, provide a method to return the number of active of objects created.
Source Code:
import java.util.*;
public class solution {
private static int objectCount = 0;
public static void complex_nos(int imag, int real, int imag1, int real1)
{ Scanner sc = new Scanner(System.in);
System.out.println("Select the operation to perform on complex number(+,-,*,/,%)");
char operations = sc.next().charAt(0);
switch (operations)
{ case '+' ->
System.out.println("The sum of the Complex number is " + (imag + imag1) + "i " + (real + real1));
case '-' ->
System.out.println("The Difference of the Complex number is " + (imag - imag1) + "i " + (real - real1));
case '*' ->
System.out.println("The Product of the Complex number is " + (imag * imag1) + "i " + (real *
real1)); case '/' ->
System.out.println("The division of the Complex number is " + (imag / imag1) + "i " + (real / real1));
case '%' ->
System.out.println("The modulo of the Complex number is " + (imag + imag1) + "i " + (real + real1));
}
objectCount++;
}
public static int getobjectCount()
{ return objectCount;
8
}
public static void main(String[] args)
{ Scanner sc = new Scanner(System.in);
System.out.println("Enter the imaginary number : ");
int imag = sc.nextInt();
System.out.println("Enter the Real number: ");
int real = sc.nextInt();
System.out.println("Enter the second imaginary number : ");
int imag1 = sc.nextInt();
System.out.println("Enter the second Real number: ");
int real1 = sc.nextInt();
complex_nos(imag, real, imag1, real1);
System.out.println("Number of objects created: " + getobjectCount());
}
}
Output:
9
Practical-3
Aim: Develop with suitable hierarchy, class for point, shape rectangle, square, circle, ellipse, triangle and
polygenetic.
Source Code:
import java.util.ArrayList;
import java.util.Scanner;
public class solution
{ public class Point {
public float X, Y;
Scanner sc = new Scanner(System.in);
void getData() {
System.out.print("Enter the value of the point X: ");
X = sc.nextFloat();
System.out.print("Enter the value of the point Y: ");
Y = sc.nextFloat();
}
void displayData() {
System.out.println("The value of the X-coordinate is " + X);
System.out.println("The value of the Y-coordinate is " + Y);
}
}
public abstract class Shape
{ abstract float area();
abstract float perimeter();
}
public class Rectangle extends Shape
{ private float width, height;
public Rectangle(float width, float height) {
10
this.width = width;
this.height = height;
}
float area() {
return width * height;
}
float perimeter() {
return 2 * (width + height);
}
}
public class Square extends Rectangle {
public Square(float side) {
super(side, side);
}
}
public class Circle extends Shape
{ private float radius;
public Circle(float radius)
{ this.radius = radius;
}
float area() {
return (float) (Math.PI * radius * radius);
}
float perimeter() {
return (float) (2 * Math.PI * radius);
}
}
public class Ellipse extends Shape
{ private float majorAxis, minorAxis;
public Ellipse(float majorAxis, float minorAxis) {
this.majorAxis = majorAxis;
11
this.minorAxis = minorAxis;
}
float area() {
return (float) (Math.PI * majorAxis * minorAxis);
}
float perimeter() {
return (float) (Math.PI * (3 * (majorAxis + minorAxis) -
Math.sqrt((3 * majorAxis + minorAxis) * (majorAxis + 3 * minorAxis))));
}
}
public class Triangle extends Shape
{ private float sideA, sideB, sideC;
public Triangle(float sideA, float sideB, float sideC)
{ this.sideA = sideA;
this.sideB = sideB;
this.sideC = sideC;
}
float area() {
float s = perimeter() / 2;
return (float) Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC));
}
float perimeter() {
return sideA + sideB + sideC;
}
}
float perimeter()
{ float perimeter =
0;
for (int i = 0; i<points.size(); i++) {
Point p1 = points.get(i);
Point p2 = points.get((i + 1) % points.size());
perimeter += Math.sqrt(Math.pow(p2.X - p1.X, 2) + Math.pow(p2.Y - p1.Y, 2));
}
return perimeter;
}
float area()
{ float area =
0;
int n = points.size();
for (int i = 0; i< n; i++)
{ Point p1 = points.get(i);
Point p2 = points.get((i + 1) % n);
area += p1.X * p2.Y - p2.X * p1.Y;
}
return Math.abs(area) / 2;
}
}
14
System.out.println("Circle Perimeter: " + circ.perimeter());
Polygon poly = usq.newPolygon();
Point p1 = usq.newPoint();
p1.getData();
Point p2 = usq.newPoint();
p2.getData();
Point p3 = usq.newPoint();
p3.getData();
poly.addPoint(p1);
poly.addPoint(p2);
poly.addPoint(p3);
System.out.println("Polygon Area: " + poly.area());
System.out.println("Polygon Perimeter: " + poly.perimeter());
}
}
Output:
15
Practical -4
Aim: Design a simple test application to demonstrate dynamic
polymorphism. Source-code:
class Animal {
public void makeSound()
{ System.out.println("Some generic animal
sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
public class javabasics {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
myAnimal.makeSound();
myDog.makeSound();
16
myCat.makeSound();
}
}
Output:
17
Practical-5
Aim: Design a Java interface for an ADT Stack.
Source code:
import java.io.*;
interface StackOperation {
void push(int item);
void pop();
void display();
}
@Override
public void push(int item) {
if (top >= STACK_SIZE - 1) {
System.out.println("Overflow: Stack is full.");
} else {
stack[++top] = item;
System.out.println("Item pushed: " + stack[top]);
}
}
@Override
public void pop() {
if (top < 0) {
18
System.out.println("Underflow: Stack is empty.");
} else {
System.out.println("Item popped: " + stack[top]);
stack[top--] = 0;
}
}
@Override
public void display()
{ if (top < 0) {
System.out.println("No elements in stack.");
} else {
System.out.println("Stack elements:");
for (int i = 0; i<= top; i++)
{ System.out.println("Element: " + stack[i]);
}
}
}
}
try {
do {
System.out.println("ARRAY STACK");
System.out.println("1. Push");
System.out.println("2. Pop");
19
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = Integer.parseInt(reader.readLine());
switch (choice)
{ case 1:
System.out.print("Enter the value to push: ");
item =
Integer.parseInt(reader.readLine()); stack.push(item);
break;
case 2:
stack.pop();
break;
case 3:
stack.display();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} catch (IOException e)
{ System.out.println("IO Error: " + e.getMessage());
20
}
}
}
Output:
21
Practical-6
Aim: Develop two different classes that implements this interface. One using array and other using linked
list.
Source code:
import java.io.*;
interface StackOperation {
void pop();
void display();
@Override
{ if (top <stack.length -
1) {
stack[++top] = item;
} else {
System.out.println("Stack overflow.");
22
@Override
if (top >= 0) {
} else {
System.out.println("Stack underflow.");
@Override
{ if (top >= 0) {
System.out.println("Stack elements:");
System.out.println(stack[i]);
} else
{ System.out.println("Stack is
empty.");
int data;
23
Node next;
24
Node(int data) {
this.data = data;
this.next = null;
@Override
newNode.next = top;
top = newNode;
@Override
if (top != null) {
top = top.next;
} else {
System.out.println("Stack underflow.");
@Override
{ if (top != null) {
25
Node current = top;
System.out.println("Stack elements:");
System.out.println(current.data);
current = current.next;
} else
{ System.out.println("Stack is
empty.");
try {
if (stackChoice == 1) {
26
} else if (stackChoice == 2) {
27
stack = new LinkedListStack();
} else {
System.out.println("Invalid choice.");
return;
do
{ System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.println("4. Exit");
choice =
Integer.parseInt(reader.readLine()); switch
(choice) {
case 1:
item =
Integer.parseInt(reader.readLine()); stack.push(item);
break;
case 2:
stack.pop();
break;
case 3:
stack.display();
break;
case 4:
System.out.println("Exiting...");
28
return;
default:
System.out.println("Invalid choice.");
} catch (IOException e)
Output:
Array based Implementation: Linked-list based application:
29
Practical - 7
Aim: Develop a simple paint like program that can draw basic graphical primitives.
Code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class paint extends Frame implements ActionListener
{
int x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,n=5,ch=1;
int xpoints[]=new int[n];
int ypoints[]=new
int[n]; MenuBar mb;
Menu op,col;
MenuIteml,c,r,a,po,x,br,bb,bg,fr,fb,fg;
Panel p;
TextField t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
Label l1,l2,l3,l4,l5,l6,l7,l8,l9,l10;
Button b;
paint()
{
p=new Panel();
t1=new TextField(4);
t2=new TextField(4);
t3=new TextField(4);
t4=new TextField(4);
l1=new Label("x1");
l2=new Label("y1");
l3=new Label("x2");
l4=new Label("y2");
t5=new TextField(4);
t6=new TextField(4);
l5=new Label("height");
l6=new Label("width");
t7=new TextField(4);
t8=new TextField(4);
t9=new TextField(4);
t10=new TextField(4);
l7=new Label("yaxis");
l8=new Label("yaxis");
l9=new Label("yaxis");
l10=new Label("yaxis");
b=new Button("ok");
p.add(l1);
p.add(t1);
p.add(l2);
30
p.add(t2);
p.add(l3);
p.add(t3);
p.add(l4);
p.add(t4);
p.add(l5);
p.add(t5);
p.add(l6);
p.add(t6);
p.add(l7);
p.add(t7);
p.add(l8);
p.add(t8);
p.add(l9);
p.add(t9);
p.add(l10);
p.add(t10);
p.add(b);
b.addActionListener(this);
setLayout(new BorderLayout());
add("South",p);
mb=new MenuBar();
setMenuBar(mb);
op=new Menu("option");
op.add(l=new MenuItem("Line"));
op.add(c=new MenuItem("Circle"));
op.add(r=new MenuItem("Rectangle"));
op.add(a=new MenuItem("Arc"));
op.add(po=new MenuItem("Polygon"));
op.add(x=new MenuItem("exit"));
col=new Menu("Color");
Menu back=new Menu("Background");
back.add(br=new MenuItem("Red"));
back.add(bg=new MenuItem("Green"));
back.add(bb=new MenuItem("Blue"));
col.add(back);
Menu fore=new Menu("Foreground");
fore.add(fr=new MenuItem("Red"));
fore.add(fg=new MenuItem("Green"));
fore.add(fb=new MenuItem("Blue"));
col.add(fore);
mb.add(op);
mb.add(col);
br.addActionListener(this);
bg.addActionListener(this);
bb.addActionListener(this);
fr.addActionListener(this);
fg.addActionListener(this);
fb.addActionListener(this);
l.addActionListener(this);
31
c.addActionListener(this);
r.addActionListener(this);
a.addActionListener(this);
po.addActionListener(this);
x.addActionListener(this);
addWindowListener(new
WindowAdapter()
{public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
switch(ch)
{
case 1: g.drawLine(x1,y1,x2,y2);
break;
case 2: g.drawOval(x1,y1,x2,y2);
break;
case 3: g.drawRect(x1,y1,x2,y2);
break;
case 4: g.drawArc(x1,y1,x2,y2,x3,y3);
break;
case 5: xpoints[0]=x1;
xpoints[1]=x2;
xpoints[2]=x3;
xpoints[3]=x4;
xpoints[4]=x5;
ypoints[0]=y1;
ypoints[1]=y2;
ypoints[2]=y3;
ypoints[3]=y4;
ypoints[4]=y5;
g.drawPolygon(xpoints,ypoints,n);
break;
}
}
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
Object s1=e.getSource();
if(s1==br)
setBackground(Color.red);
else if(s1==bg)
setBackground(Color.green);
else if(s1==bb)
setBackground(Color.blue);
32
else if(s1==fr)
setForeground(Color.red);
else if(s1==fg)
setForeground(Color.green);
else if(s1==fb)
setForeground(Color.blue);
if(s.equals("exit"))
System.exit(0);
else if(s.equals("Line"))
{
ch=1;
}
else if(s.equals("Circle"))
ch=2;
else if(s.equals("Rectangle"))
ch=3;
else if(s.equals("Arc"))
{
ch=4;
}
else if(s.equals("Polygon"))
{
ch=5;
}
else if(s.equals("ok"))
{
x1=Integer.parseInt(t1.getText());
x2=Integer.parseInt(t2.getText());
y1=Integer.parseInt(t3.getText());
y2=Integer.parseInt(t4.getText());
x3=Integer.parseInt(t5.getText()+0);
y3=Integer.parseInt(t6.getText()+0);
x4=Integer.parseInt(t7.getText()+0);
y4=Integer.parseInt(t8.getText()+0);
x5=Integer.parseInt(t9.getText()+0);
y5=Integer.parseInt(t10.getText()+0);
repaint();
}
}
34
Practical - 8
Aim: Develop a scientific calculator using event driven programming.
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public Calculator() {
textfield = new JTextField("", 12);
textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);
ActionListener numberListener = new NumberListener();
String buttonOrder = "1234567890 ";
JPanelbuttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));
for (int i = 0; i<buttonOrder.length(); i++) {
String key = buttonOrder.substring(i, i+1);
if (key.equals(" ")) {
buttonPanel.add(new JLabel(""));
} else {
JButton button = new JButton(key);
button.addActionListener(numberListener);
button.setFont(BIGGER_FONT);
buttonPanel.add(button);
}
}
ActionListener operatorListener = new OperatorListener();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 4, 4));
String[] opOrder = {"+", "-", "*",
"/","=","C","sin","cos","log"}; for (int i = 0;
i<opOrder.length; i++) {
JButton button = new JButton(opOrder[i]);
button.addActionListener(operatorListener);
button.setFont(BIGGER_FONT);
panel.add(button);
}
JPanel pan = new JPanel();
pan.setLayout(new BorderLayout(4, 4));
35
pan.add(textfield, BorderLayout.NORTH );
pan.add(buttonPanel , BorderLayout.CENTER);
pan.add(panel , BorderLayout.EAST);
this.setContentPane(pan);
this.pack();
this.setTitle("Calculator");
this.setResizable(false);
}
private void action()
{ number = true;
textfield.setText("");
equalOp = "=";
op.setTotal("");
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String displayText = textfield.getText();
if (e.getActionCommand().equals("sin"))
{
textfield.setText("" + Math.sin(Double.valueOf(displayText).doubleValue()));
}else
if (e.getActionCommand().equals("cos"))
{
textfield.setText("" + Math.cos(Double.valueOf(displayText).doubleValue()));
}
else
if (e.getActionCommand().equals("log"))
{
textfield.setText("" + Math.log(Double.valueOf(displayText).doubleValue()));
}
else if (e.getActionCommand().equals("C"))
{
textfield.setText("");
}
else
{
if (number)
{
action();
textfield.setText("");
}
else
{
number = true;
36
if (equalOp.equals("="))
{
op.setTotal(displayText);
}else
if (equalOp.equals("+"))
{
op.add(displayText);
}
else if (equalOp.equals("-"))
{
op.subtract(displayText);
}
else if (equalOp.equals("*"))
{
op.multiply(displayText);
}
else if (equalOp.equals("/"))
{
op.divide(displayText);
}
textfield.setText("" + op.getTotalString());
equalOp = e.getActionCommand();
}
}
}
}
class NumberListener implements ActionListener
{ public void actionPerformed(ActionEvent
event) {
String digit = event.getActionCommand();
if (number) {
textfield.setText(digit);
number = false;
} else {
textfield.setText(textfield.getText() + digit);
}
}
}
public class CalculatorOp
{ private int total;
public CalculatorOp() {
total = 0;
}
public String getTotalString() {
return ""+total;
}
public void setTotal(String n)
{ total = convertToNumber(n);
}
public void add(String n) {
37
total += convertToNumber(n);
}
public void subtract(String n) {
total -= convertToNumber(n);
}
public void multiply(String n) {
total *= convertToNumber(n);
}
public void divide(String n) {
total /= convertToNumber(n);
}
private int convertToNumber(String n)
{ return Integer.parseInt(n);
}
}
}
class SwingCalculator {
public static void main(String[] args)
{ JFrame frame = new Calculator();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
OUTPUT:
38
Practical - 9
Aim: Develop a template for linked list class along with members in Java.
Code:
class Node
{ int data;
Node next;
this.data = data;
this.next = null;
public JavaNBasics() {
this.head = null;
public booleanisEmpty() {
39
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
if (head == null) {
head =
newNode; return;
current = current.next;
current.next = newNode;
if (head != null)
{ head =
head.next;
if (head.next == null) {
return;
{ current = current.next;
if (head == null)
{ System.out.println("The list is
empty."); return;
current = current.next;
System.out.println("null");
41
}
if (current.data == data)
found
current = current.next;
}
// Method to get the size of the list
int size = 0;
size++;
current = current.next;
return size;
42
{ JavaNBasics list = new JavaNBasics();
43
list.addFirst(10);
list.addFirst(20);
list.addLast(30);
list.addLast(40);
System.out.println("Linked List:
"); list.display();
list.deleteFirst();
list.deleteLast();
list.display();
Output:
44
Practical 10
Aim: Write a program to insert and view data using servlets.
Code:
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatementps=con.prepareStatement( "ins
45
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);
int i=ps.executeUpdate();
if(i>0)
{System.out.println(e2);} out.close();
<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
46
</welcome-file-list>
</web-app>
Output:
47
48
49
50
51
52
53
54