0% found this document useful (0 votes)
8 views56 pages

Java Harsh Pratap

The document is a practical file for a Computer Science and Engineering lab course, detailing various programming exercises and their implementations in Java. It includes tasks such as creating data structures like stacks and queues, designing classes for complex numbers and shapes, and demonstrating concepts like dynamic polymorphism and interfaces. Each practical section contains source code, aims, and expected outputs for the exercises completed by the student, Harsh Pratap.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views56 pages

Java Harsh Pratap

The document is a practical file for a Computer Science and Engineering lab course, detailing various programming exercises and their implementations in Java. It includes tasks such as creating data structures like stacks and queues, designing classes for complex numbers and shapes, and demonstrating concepts like dynamic polymorphism and interfaces. Each practical section contains source code, aims, and expected outputs for the exercises completed by the student, Harsh Pratap.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

PRACTICAL FILE

OF
ESSENTIAL OF INFORMATION AND TECHNOLOGY LAB

SESSION: 2024-25
Submitted By: Harsh Pratap
Roll No: 2022027522
Semester: V
B. Tech (CSE)

Submitted to: Mrs. Anjali Chaudhary (Assistant professor)


Department of Computer Science and Engineering,
State Institute of Engineering and Technology, Nilokheri (Karnal),
Haryana – 132117

(Affiliated to Kurukshetra University, Kurukshetra)

1
INDEX

Page
S. No. Title of Practical Practical Date Signature
No.

1.
Write a java Package with Stack and queue
classes

Design a class for complex numbers in java.


2.
In addition to methods for basic operations
on complex numbers, provide a method to
return the number of active objects created.

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.

5. Design a java interface for ADT stack.

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;

public class usestackqueue2


public static void main(String[] args) {

BufferedReadersc = new BufferedReader(new InputStreamReader(System.in));


int c = 0;
stack2 s = null;
int n;
try {
do {
System.out.println("1. Stack 2.
Queue"); c =
Integer.parseInt(sc.readLine()); switch
(c) {
case 1 -> {
// Stack operations

System.out.println("Enter the size of the


stack:"); n = Integer.parseInt(sc.readLine());
s = new stack2(n);
int choice;
do {
System.out.println("1. Push 2. Pop 3. Display 0. Exit, enter your choice:");
choice = Integer.parseInt(sc.readLine());

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 3 -> // Display


s.display();
case 0 -> {
}

default ->System.out.println("Invalid choice");


}

// Exit inner menu


} while (choice != 0);

}
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--;
}
}

public void display() {


if (top == -1) {
System.out.println("Stack empty");
} else {
for (int i = top; i>= 0; i--)
{ System.out.println("Stack element: " + a[i]);
}
}
}
}

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;
}
}

public class Polygon extends Shape {


private ArrayList<Point> points = new ArrayList<>();

public void addPoint(Point p) {


points.add(p);
12
}

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;
}
}

public static void main(String[] args)


{ solution usq = new solution();

Rectangle rect = usq.newRectangle(4, 5);


System.out.println("Rectangle Area: " + rect.area());
System.out.println("Rectangle Perimeter: " + rect.perimeter());
13
Circle circ = usq.newCircle(3);
System.out.println("Circle Area: " + circ.area());

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();
}

class AStack implements StackOperation


{ private static final int STACK_SIZE = 5;
private int[] stack = new int[STACK_SIZE];
private int top = -1;

@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]);
}
}
}
}

public class Paint {


public static void main(String[] args)
{ AStack stack = new AStack();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int choice, item;

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.");
}

System.out.print("Do you want to continue? (0 to quit, 1 to continue): ");


choice = Integer.parseInt(reader.readLine());

} while (choice == 1);

} 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 push(int item);

void pop();

void display();

class ArrayStack implements StackOperation

{ private int[] stack = new int[5];

private int top = -1;

@Override

public void push(int item)

{ if (top <stack.length -

1) {

stack[++top] = item;

System.out.println("Item pushed: " + item);

} else {

System.out.println("Stack overflow.");

22
@Override

public void pop() {

if (top >= 0) {

System.out.println("Item popped: " + stack[top--]);

} else {

System.out.println("Stack underflow.");

@Override

public void display()

{ if (top >= 0) {

System.out.println("Stack elements:");

for (int i = 0; i<= top; i++) {

System.out.println(stack[i]);

} else

{ System.out.println("Stack is

empty.");

class LinkedListStack implements StackOperation

{ private class Node {

int data;

23
Node next;

24
Node(int data) {

this.data = data;

this.next = null;

private Node top = null;

@Override

public void push(int item) {

Node newNode = new Node(item);

newNode.next = top;

top = newNode;

System.out.println("Item pushed: " + item);

@Override

public void pop() {

if (top != null) {

System.out.println("Item popped: " + top.data);

top = top.next;

} else {

System.out.println("Stack underflow.");

@Override

public void display()

{ if (top != null) {

25
Node current = top;

System.out.println("Stack elements:");

while (current != null) {

System.out.println(current.data);

current = current.next;

} else

{ System.out.println("Stack is

empty.");

public class JavaNBasics {

public static void main(String[] args) {

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

StackOperation stack = null;

int choice, item;

try {

System.out.println("Choose Stack Implementation:");

System.out.println("1. Array-based Stack");

System.out.println("2. Linked List-based Stack");

int stackChoice = Integer.parseInt(reader.readLine());

if (stackChoice == 1) {

stack = new ArrayStack();

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:

System.out.print("Enter 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...");
28
return;

default:

System.out.println("Invalid choice.");

System.out.print("Continue? (1 for yes, 0 for no): ");

} while (Integer.parseInt(reader.readLine()) == 1);

} catch (IOException e)

{ System.out.println("Error: " + e.getMessage());

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();
}
}

public static void main(String args[])


{
paint f=new paint();
f.setSize(800,400);
f.setVisible(true);
}
}
33
OUTPUT:

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.*;

class Calculator extends JFrame {


private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN,
20); private JTextFieldtextfield;
private boolean number = true;
private String equalOp = "=";
private CalculatorOp op = new CalculatorOp();

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;

// Constructor to create a new node

public Node(int data) {

this.data = data;

this.next = null;

// JavaNbasics class contains methods for basic operations

public class JavaNBasics {

private Node head; // Head of the list

// Constructor to initialize an empty linked list

public JavaNBasics() {

this.head = null;

// Method to check if the list is empty

public booleanisEmpty() {

return head == null;

// Method to add a node at the beginning (head) of the list

public void addFirst(int data) {

39
Node newNode = new Node(data);

newNode.next = head;

head = newNode;

// Method to add a node at the end of the list

public void addLast(int data) {

Node newNode = new Node(data);

if (head == null) {

head =

newNode; return;

Node current = head;

while (current.next != null) {

current = current.next;

current.next = newNode;

// Method to delete the first node (head) of the list

public void deleteFirst() {

if (head != null)

{ head =

head.next;

// Method to delete the last node of the list

public void deleteLast() {


40
if (head == null) {

return; // List is empty

if (head.next == null) {

head = null; // Only one node exists

return;

Node current = head;

while (current.next != null &&current.next.next != null)

{ current = current.next;

current.next = null; // Remove the last node

// Method to display the

list public void display() {

if (head == null)

{ System.out.println("The list is

empty."); return;

Node current = head;

while (current != null) {

System.out.print(current.data + " -> ");

current = current.next;

System.out.println("null");

41
}

// Method to search for a value in the list

public booleansearch(int data) {

Node current = head;

while (current != null) {

if (current.data == data)

{ return true; // Data

found

current = current.next;

return false; // Data not found

}
// Method to get the size of the list

public int size() {

int size = 0;

Node current = head;

while (current != null) {

size++;

current = current.next;

return size;

// Main method for testing

public static void main(String[] args)

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();

System.out.println("List Size: " + list.size());

System.out.println("Searching for 30: " + (list.search(30) ? "Found" : "Not Found"));

list.deleteFirst();

list.deleteLast();

System.out.println("Linked List after deletions: ");

list.display();

System.out.println("List Size after deletions: " + list.size());

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.*;

public class Register extends HttpServlet

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

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

ert into registeruser values(?,?,?,?)");

45
ps.setString(1,n);

ps.setString(2,p);

ps.setString(3,e);

ps.setString(4,c);

int i=ps.executeUpdate();

if(i>0)

out.print("You are successfully registered...");

}catch (Exception e2)

{System.out.println(e2);} out.close();

The is the configuration file, providing information about the servlet.

<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:

1. When Registration is Successful:

2. When Registration is failed:

47
48
49
50
51
52
53
54

You might also like