0% found this document useful (0 votes)
10 views43 pages

Organized

The document is a practical lab report for the Computer Laboratory and Practical Work of Java Programming and Dynamic Webpage Design course at Chaudhary Charan Singh University. It includes a student declaration, acknowledgments, an index of various programming assignments, and detailed code examples for each assignment. The assignments cover a range of Java programming concepts including command-line arguments, exception handling, inheritance, and GUI design.

Uploaded by

pravipundir003
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)
10 views43 pages

Organized

The document is a practical lab report for the Computer Laboratory and Practical Work of Java Programming and Dynamic Webpage Design course at Chaudhary Charan Singh University. It includes a student declaration, acknowledgments, an index of various programming assignments, and detailed code examples for each assignment. The assignments cover a range of Java programming concepts including command-line arguments, exception handling, inheritance, and GUI design.

Uploaded by

pravipundir003
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/ 43

Chaudhary Charan Singh University

Delhi Institute of Higher Education (DIHE)


College Code: - 1214 Session
2023-2024

5th Semester

Subject: - Computer Laboratory and Practical Work of Java


Programming & Dynamic Webpage Design

Code: - BCA-508P

Submitted to: - Submitted by: -


Ms. Vandana Kumari Ravi Pundir
Assistant Professor B.C.A - B

Enrolment No: - 22415765


Roll No: - 221214106091
Course: - Bachelor of Computer Application
Student Declaration

I,Ravi Pundir, Roll No. 221214106091, student of “BCA SECTION-


B”, Semester- 5, hereby declare that the Lab and Practical file of
Computer Laboratory and Practical Work of Java Programming &
Dynamic Webpage Design has been submitted by me to Delhi Institute
of Higher Education (DIHE) for fulfilment of Degree of Bachelor of
Computer Application.

Ms. Vandana Kumari Student Name: -Ravi Pundir


Assistant. professor Enrolment No: - 22415765
Course: - B.C.A-B

Semester: - SEM-5
Acknowledgement

I would like to express my special thanks of gratitude to my Professor,


Ms. Vandana Kumari for her guidance and support in completing my
project file. I would like to extend my gratitude to the Director, Dr.
Rajeev Kumar for providing me with all the facility that was required.

Students Name: -Ravi Pundir


Course: - B.C.A-B
Semester: - SEM-5
Enrolment No: - 22415765
INDEX
S.No. PROGRAM PAGE NO.
WAP to find the average and sum of the N numbers Using Command 1
1
line argument.
2 WAP to find the number of arguments provide at runtime. 2
3 WAP to calculate the Simple Interest and Input by the user. 3
WAP to create a Simple class to find out the Area and perimeter of 4
4
rectangle and box using super and this keyword.
WAP to design a class account using the inheritance and static that 5
5
show all function of bank (withdrawl, deposite).
6 WAP to design a class using abstract Methods and Classes. 6
WAP to design a String class that perform String 7
7
Method(Equal,Reverse the string,change case).
8 WAP to handle the Exception using try and multiple catch block. 8
9 WAP that show the partial implementation of Interface. 9
10 WAP to create a thread that Implement the Runable interface. 10
WAP to create a class component that show controls and event 11-12
11
handling on that controls.(math calc).
12 WAP to create a Menu using the frame. 13-14
13 WAP to create a Dialogbox. 15-16
14 WAP to Implement the flow layout And Border Layout. 17
15 WAP to Implement the GridLayout, CardLayout. 18-19
16 Demonstrate Network programming 20
17 WAP to retrieve IPAddress of a local machine on a network. 21
18 Demonstrate Mouse event Handling 22
19 Demonstrate Keyboard event Handling 23
20 How to establish a connection with Database 24-25
21 WAP to retrieve a records from a table 26
22 WAP to execute SQL statements 27
23 WAP to update data in a table 28
24 WAP to delete data from a table 29
25 Create a simple servlet that responds with "Hello, World!" 30
26 Create a servlet to handle form data submitted via a POST request. 31
Create a servlet that demonstrates session management by storing and retrieving 32-33
27
user information in a session.
28 Create a simple JSP page that displays "Hello, World!". 34
29 Create a JavaBean and use it in a JSP page. 35
30 Create a JSP page that uses directives and scriptlets to display dynamic content. 36
WAP to

Q1 find the average and sum of the N numbers Using Command line
argument..

CODE:

public class SumAndAverage {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide numbers as command-line
arguments."); return;
}
double sum = 0;
int count = 0;
for (String arg : args)
{ try {
double number =
Double.parseDouble(arg); sum += number;
count++;
} catch (NumberFormatException e) {
System.out.println(arg + " is not a valid number. Skipping.");
}
}
if (count > 0) {
double average = sum / count; System.out.println("Sum:
" + sum);
System.out.println("Average: " + average);
} else {
System.out.println("No valid numbers were provided.");
}
}
}

OUTPUT:-

SumAndAverage.java javac
SumAndAverage.java java
SumAndAverage 10 20 30 40 50
Sum: 150.0
Average: 30.0

OUTPUT:-

java SumAndAverage 10 abc 20.5 abc


is not a valid number. Skipping.
Sum: 30.5
Average: 15.25
Q2 find the number of arguments provide at runtime.

Page 1
WAP to

Code:

public class CountArguments {


public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
}
}

OUTPUT:-

CountArguments.java javac
CountArguments.java java
CountArguments arg1 arg2 arg3 Input:
java CountArguments arg1 arg2 arg3
OUTPUT:-: Number of arguments: 3

Page 2
WAP to

Q3 calculate the Simple Interest and Input by the user.

Code:

import java.util.Scanner;

public class SimpleInterest {


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

System.out.print("Enter Principal: ");


double principal = scanner.nextDouble();

System.out.print("Enter Rate of Interest: ");


double rate = scanner.nextDouble();

System.out.print("Enter Time (in years): ");


double time = scanner.nextDouble();

double simpleInterest = (principal * rate * time) / 100;


System.out.println("Simple Interest: " + simpleInterest);

scanner.close();
}
}

OUTPUT:-

SimpleInterest.java javac
SimpleInterest.java java
SimpleInterest

Enter Principal: 1000 Enter Rate of Interest: 5 Enter Time (in years): 2
Simple Interest: 100.0
Q4 create a Simple class to find out the Area and perimeter of
rectangle and box using super and this keyword.

CODE:

class Rectangle {
double length, width;
Rectangle(double length, double width)
{ this.length = length;
this.width = width;
}
double getArea() {

Page 3
WAP to

return length * width;


}
double getPerimeter() {
return 2 * (length + width);
} } class Box extends
Rectangle {
double height;
Box(double length, double width, double height)
{ super(length, width); this.height = height; }
double getVolume() {
return length * width * height; }
double getSurfaceArea() {
return 2 * (length * width + width * height + height * length);
} } public class
ShapeCalculation {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(10, 5);
System.out.println("Rectangle Area: " + rectangle.getArea());
System.out.println("Rectangle Perimeter: " + rectangle.getPerimeter());
Box box = new Box(10, 5, 8);
System.out.println("Box Volume: " + box.getVolume());
System.out.println("Box Surface Area: " +
box.getSurfaceArea()); } }

OUTPUT:-
ShapeCalculation.java
javac
ShapeCalculation.java
java ShapeCalculation

Input:
(Rectangle with length = 10, width = 5)
(Box with length = 10, width = 5, height = 8)
OUTPUT:-
Rectangle Area: 50.0
Rectangle Perimeter: 30.0
Box Volume: 400.0
Box Surface Area: 340.0

Page 4
Q5 WAP to design a class account using the inheritance and static that
show all function of bank (withdrawl, deposite).

CODE:

class Account {
static double balance = 0; static
void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
static void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance.");
} }
static void displayBalance() {
System.out.println("Current Balance: " + balance);
} } class SavingsAccount extends
Account {
SavingsAccount()
{ balance = 0;
} } public class
BankAccount {
public static void main(String[] args) {
SavingsAccount account = new SavingsAccount();
account.deposit(5000);
account.displayBalance();
account.withdraw(2000);
account.displayBalance();
account.withdraw(4000);
account.displayBalance();
}
}

OUTPUT:-
BankAccount.java
javac
BankAccount.java java
BankAccount

Deposited: 5000.0
Current Balance: 5000.0
Withdrawn: 2000.0

Page 5
WAP to

Current Balance: 3000.0


Withdrawn: 4000.0
Insufficient balance.
Current Balance: 3000.0
Q6 design a class using abstract Methods and Classes.

CODE:

abstract class Shape {


abstract void draw();
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing Circle");
}
}

class Rectangle extends Shape {


void draw() {
System.out.println("Drawing Rectangle");
}
}

public class AbstractExample { public


static void main(String[] args) {
Shape circle = new Circle();
Shape rectangle = new Rectangle();

circle.draw();
rectangle.draw();
}
}

OUTPUT:-

AbstractExample.java
javac
AbstractExample.java java
AbstractExample Drawing
Circle
Drawing Rectangle
Q7 design a String class that perform String Method(Equal,Reverse the
string,change case).

CODE:

class StringOperations {

Page 6
WAP to

String str;
StringOperations(String str)
{ this.str = str;
}
boolean equals(String other)
{ return str.equals(other);
}
String reverse()
{ String reversed =
"";
for (int i = str.length() - 1; i >= 0; i--)
{ reversed += str.charAt(i);
}
return reversed;
}
String changeCase()
{ String result = "";
for (int i = 0; i < str.length(); i++) { char
ch = str.charAt(i); if
(Character.isLowerCase(ch)) { result
+= Character.toUpperCase(ch);
} else { result +=
Character.toLowerCase(ch);
} }
return result;
} }
public class StringMethodsExample
{ public static void main(String[] args) {
StringOperations strOps = new StringOperations("Hello World");
System.out.println("Original String: " + strOps.str);
System.out.println("Check if equal to 'Hello World': " + strOps.equals("Hello
World"));
System.out.println("Check if equal to 'hello world': " + strOps.equals("hello world"));
System.out.println("Reversed String: " + strOps.reverse());
System.out.println("Changed Case: " + strOps.changeCase());
}
}

OUTPUT:-

StringMethodsExample.java
javac
StringMethodsExample.java java
StringMethodsExample Original
String: Hello World
Check if equal to 'Hello World': true
Check if equal to 'hello world': false
Reversed String: dlroW olleH
Changed Case: hELLO wORLD

Page 7
WAP to

Q8 handle the Exception using try and multiple catch block. CODE

import java.util.Scanner; public class


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

try {
System.out.print("Enter a number: ");
int num1 = scanner.nextInt();

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


int num2 = scanner.nextInt();

int result = num1 / num2; // Division operation that might throw an exception
System.out.println("Division Result: " + result);

} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} catch (java.util.InputMismatchException e) {
System.out.println("Error: Invalid input. Please enter valid integers.");
} catch (Exception e) {
System.out.println("Error: Something went wrong.");
} finally
{ scanner.close();
System.out.println("Scanner
closed."); }
}
}

OUTPUT:-

MultipleCatchExample.java
javac
MultipleCatchExample.java
java MultipleCatchExample

Input 1:
Enter a number: 10
Enter another number: 2

OUTPUT:- 1:
Division Result: 5
Scanner closed.

Page 8
WAP

Q9 that show the partial implementation of Interface.

CODE:

interface Vehicle {
void start(); void
stop(); void
accelerate();
}

abstract class Car implements Vehicle {


@Override
public void start() {
System.out.println("Car is starting...");
}

@Override public
void stop() {
System.out.println("Car is stopping...");
}
}

class SportsCar extends Car


{ @Override
public void accelerate() {
System.out.println("SportsCar is
accelerating..."); }
}

public class InterfacePartialImplementation {


public static void main(String[] args) { Vehicle
myCar = new SportsCar();
myCar.start();
myCar.accelerate();
myCar.stop();
}
}

OUTPUT:-

InterfacePartialImplementation.java
javac
InterfacePartialImplementation.java java
InterfacePartialImplementation Car is
starting...
SportsCar is accelerating...
Car is stopping...
Q10 WAP to create a thread that Implement the Runable interface.

CODE:

Page 9
class MyThread implements Runnable {
@Override public
void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread is running: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread
interrupted"); }
}
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread myRunnable = new MyThread();
Thread thread = new Thread(myRunnable);
thread.start();

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


System.out.println("Main thread: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Main thread
interrupted"); }
}
}
}

OUTPUT:-

ThreadExample.java
javac
ThreadExample.java java
ThreadExample Thread is
running: 1
Main thread: 1
Thread is running: 2
Main thread: 2
Thread is running: 3
Main thread: 3
Thread is running: 4
Main thread: 4
Thread is running: 5
Main thread: 5

Page 10
WAP to create a

Q11 class component that show controls and event handling on that
controls.(math calc).

CODE:

import javax.swing.*; import


java.awt.*; import
java.awt.event.ActionEvent; import
java.awt.event.ActionListener;
public class CalculatorGUI extends JFrame implements ActionListener {
private JTextField num1Field, num2Field, resultField;
private JButton addButton, subtractButton, multiplyButton,
divideButton; public CalculatorGUI() {
setTitle("Math Calculator");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 2));
JLabel num1Label = new JLabel("Number 1:");
num1Field = new JTextField();
JLabel num2Label = new JLabel("Number 2:");
num2Field = new JTextField();
JLabel resultLabel = new
JLabel("Result:"); resultField = new
JTextField(); resultField.setEditable(false);
addButton = new JButton("Add");
subtractButton = new JButton("Subtract");
multiplyButton = new
JButton("Multiply"); divideButton = new
JButton("Divide");
addButton.addActionListener(this);
subtractButton.addActionListener(this);
multiplyButton.addActionListener(this);
divideButton.addActionListener(this);
add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(addButton);
add(subtractButton);
add(multiplyButton);
add(divideButton);
add(resultLabel);
add(resultField); }
@Override
public void actionPerformed(ActionEvent e)
{ try {
double num1 =
Double.parseDouble(num1Field.getText()); double num2
= Double.parseDouble(num2Field.getText()); double result
= 0; if (e.getSource() == addButton) {

Page 11
result = num1 + num2;
} else if (e.getSource() == subtractButton)
{ result = num1 - num2;
} else if (e.getSource() == multiplyButton) {
result = num1 * num2;
} else if (e.getSource() == divideButton)
{ if (num2 != 0) {
result = num1 / num2;
} else { resultField.setText("Error: Divide
by 0");
return;
} }
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex)
{ resultField.setText("Error: Invalid Input");
} }
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
CalculatorGUI calculator = new CalculatorGUI();
calculator.setVisible(true);
});
}
}

OUTPUT:-

CalculatorGUI.java
javac
CalculatorGUI.java java
CalculatorGUI

| Number 1: [ ]|
| Number 2: [ ]|
| [ Add ] [Subtract] |
| [Multiply] [ Divide ] |
| Result: [ ]

Result: 15.0

Page 12
WAP to create a

CODE:
Q12 Menu using the frame.

import javax.swing.*; import


java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MenuExample extends JFrame


{ public MenuExample()
{ setTitle("Menu Example"); setSize(400,
300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenu helpMenu = new JMenu("Help");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem saveItem = new JMenuItem("Save");
JMenuItem exitItem = new JMenuItem("Exit");
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");
JMenuItem aboutItem = new JMenuItem("About");
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(exitItem);
editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
helpMenu.add(aboutItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
openItem.addActionListener(e -> JOptionPane.showMessageDialog(this, "Open
selected")); saveItem.addActionListener(e -> JOptionPane.showMessageDialog(this, "Save
selected")); exitItem.addActionListener(e -> System.exit(0)); cutItem.addActionListener(e
-> JOptionPane.showMessageDialog(this, "Cut selected")); copyItem.addActionListener(e
-> JOptionPane.showMessageDialog(this, "Copy
selected")); pasteItem.addActionListener(e ->
JOptionPane.showMessageDialog(this, "Paste
selected")); aboutItem.addActionListener(e -> JOptionPane.showMessageDialog(this, "This is
a menu
example."));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MenuExample frame = new MenuExample();
frame.setVisible(true);

Page 13
});
} }
OUTPUT:-

MenuExample.java
javac
MenuExample.java java
MenuExample
+ +
| File Edit Help |
| |
| |
| |
| [ Application Frame ] |
| |

File

Open
Save
Exit

Open selected

File

Open
Save
Exit

Save selected
Q13 Dialogbox.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DialogBoxExample extends JFrame {


public DialogBoxExample()
{ setTitle("Dialog Box
Example"); setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
JButton showDialogButton = new JButton("Show Dialog");
showDialogButton.setBounds(80, 60, 140, 30);
add(showDialogButton);
showDialogButton.addActionListener(new ActionListener() {
@Override

Page 14
WAP to create a

CODE:
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog(DialogBoxExample.this, "Sample Dialog",
true); dialog.setSize(250, 150); dialog.setLayout(null);
JLabel messageLabel = new JLabel("This is a dialog
box!"); messageLabel.setBounds(50, 30, 150, 20);
dialog.add(messageLabel);
JButton okButton = new JButton("OK");
okButton.setBounds(80, 70, 80, 30);
dialog.add(okButton);
okButton.addActionListener(event -> dialog.dispose());
dialog.setLocationRelativeTo(DialogBoxExample.this);
dialog.setVisible(true);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
DialogBoxExample frame = new DialogBoxExample();
frame.setVisible(true);
}); } }
OUTPUT:-

DialogBoxExample.java
javac
DialogBoxExample.java
java DialogBoxExample

+ +
| [ Show Dialog ] |

+ +
| Sample Dialog |
| | | This is a dialog
box! |

Page 15
| |
| [ OK ] |

+
---+
| Sample Dialog
|
|
--|
| This is a dialog
box! |
| |
| [ OK ] |
+
---+

Page 16
WAP to

CODE:
Q14 Implement the flow layout And Border Layout

import javax.swing.*;
import java.awt.*;

public class LayoutExample extends JFrame {


public LayoutExample() {
setTitle("FlowLayout and BorderLayout Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel borderPanel = new JPanel(new BorderLayout());
borderPanel.add(new JButton("North"), BorderLayout.NORTH);
borderPanel.add(new JButton("South"), BorderLayout.SOUTH);
borderPanel.add(new JButton("East"), BorderLayout.EAST);
borderPanel.add(new JButton("West"), BorderLayout.WEST);
borderPanel.add(new JButton("Center"),
BorderLayout.CENTER);
JPanel flowPanel = new JPanel(new
FlowLayout()); flowPanel.add(new
JButton("Button 1")); flowPanel.add(new
JButton("Button 2")); flowPanel.add(new
JButton("Button 3")); flowPanel.add(new
JButton("Button 4")); flowPanel.add(new
JButton("Button 5")); add(borderPanel,
BorderLayout.CENTER);
add(flowPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
LayoutExample frame = new LayoutExample();
frame.setVisible(true);
});
}
}

OUTPUT:-

LayoutExample.java
javac
LayoutExample.java java
LayoutExample
+ +
| [ North ] |
| |
| [ West ] [ Center ] [East]|
| |

Page 17
| [ South ] |

+ +
| [ Button 1 ] [ Button 2 ] [ Button 3 ]|
| [ Button 4 ] [ Button 5 ] |

Q15 WAP to Implement the GridLayout, CardLayout.

CODE:

import javax.swing.*; import


java.awt.*; import
java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LayoutExample extends JFrame {


public LayoutExample() {
setTitle("GridLayout and CardLayout Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel gridPanel = new JPanel(new GridLayout(2,
2)); gridPanel.add(new JButton("Button 1"));
gridPanel.add(new JButton("Button 2"));
gridPanel.add(new JButton("Button 3"));
gridPanel.add(new JButton("Button 4")); JPanel
cardPanel = new JPanel(new CardLayout()); JPanel
card1 = new JPanel(); card1.add(new JButton("Card
1")); JPanel card2 = new JPanel(); card2.add(new
JButton("Card 2")); JPanel card3 = new JPanel();
card3.add(new JButton("Card 3"));
cardPanel.add(card1, "Card 1"); cardPanel.add(card2,
"Card 2"); cardPanel.add(card3, "Card 3"); JPanel
cardControlPanel = new JPanel(); JButton nextButton
= new JButton("Next Card");
nextButton.addActionListener(new ActionListener()
{
int currentCard = 1;
@Override
public void actionPerformed(ActionEvent e) {
currentCard = (currentCard % 3) + 1;
CardLayout cl = (CardLayout) cardPanel.getLayout();
cl.show(cardPanel, "Card " + currentCard);
} });
cardControlPanel.add(nextButton);
add(gridPanel, BorderLayout.NORTH);
add(cardPanel, BorderLayout.CENTER);
add(cardControlPanel, BorderLayout.SOUTH);
}

Page 18
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
LayoutExample frame = new LayoutExample();
frame.setVisible(true);
}); } }
OUTPUT:-

+ +
| Card 1 |
| [ Card 1 ] |
++

++
| Card 2 |
| [ Card 2 ] |
++

++
| Card 3 |
| [ Card 3 ] |
+ +

Page 19
Q16 Demonstrate Network programming

CODE:

SERVER CODE

import java.net.*;
import java.io.*;
public class Server
{
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server is waiting for client...");
Socket socket = serverSocket.accept();
System.out.println("Client connected.");
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter OUTPUT:- = new PrintWriter(socket.getOUTPUT:-Stream(),
true);
String clientMessage = input.readLine();
System.out.println("Client: " + clientMessage);
OUTPUT:-.println("Hello from Server!");
socket.close();
serverSocket.close();
}
}

CLIENT CODE

import java.net.*;
import java.io.*;
public class Client
{
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 1234);
BufferedReader input = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter OUTPUT:- = new PrintWriter(socket.getOUTPUT:-Stream(),
true);
OUTPUT:-.println("Hello from Client!");
String serverResponse = input.readLine();
System.out.println("Server: " +
serverResponse); socket.close();
}
}

OUTPUT:-

Server OUTPUT:-:

Page 20
Server is waiting for client...
Client connected.
Client: Hello from Client!

Client OUTPUT:-:
Server: Hello from Server!
Q17 WAP to retrieve IPAddress of a local machine on a network.

CODE:

import java.net.*;

public class GetIPAddress {


public static void main(String[] args) throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
String ipAddress = localHost.getHostAddress();
System.out.println("IP Address of local machine: " +
ipAddress); }
}

OUTPUT:-

GetIPAddress.java
javac
GetIPAddress.java java
GetIPAddress
IP Address of local machine: 192.168.1.5

Page 21
Q18 Demonstrate Mouse event Handling

CODE:

import java.awt.*;
import java.awt.event.*;

public class MouseEventExample extends Frame implements MouseListener


{ String message = ""; public MouseEventExample() {
setTitle("Mouse Event Handling Example");
setSize(400, 300);
setVisible(true);
addMouseListener(this);
}
public void paint(Graphics g) {
g.drawString(message, 100,
100); }
public void mouseClicked(MouseEvent e) {
message = "Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")";
repaint();
}
public void mousePressed(MouseEvent e) {
message = "Mouse Pressed at (" + e.getX() + ", " + e.getY() + ")";
repaint();
}
public void mouseReleased(MouseEvent e) {
message = "Mouse Released at (" + e.getX() + ", " + e.getY() + ")";
repaint();
}
public void mouseEntered(MouseEvent e) {
message = "Mouse Entered the Frame";
repaint();
}
public void mouseExited(MouseEvent e) {
message = "Mouse Exited the Frame";
repaint();
}
public static void main(String[] args) {
new MouseEventExample();
}
}

OUTPUT:-

MouseEventExample.java
javac
MouseEventExample.java java
MouseEventExample Mouse
Entered the Frame
Mouse Clicked at (x, y)

Page 22
Mouse Pressed at (x, y)
Mouse Released at (x, y)
Mouse Exited the Frame
Q19 Demonstrate Keyboard event Handling

CODE:

import java.awt.*;
import java.awt.event.*;

public class KeyboardEventExample extends Frame implements KeyListener


{ String message = ""; public KeyboardEventExample() {
setTitle("Keyboard Event Handling Example");
setSize(400, 300);
setVisible(true);
addKeyListener(this);
}
public void paint(Graphics g) {
g.drawString(message, 100,
100); }
public void keyPressed(KeyEvent e) {
message = "Key Pressed: " + e.getKeyChar();
repaint();
}
public void keyReleased(KeyEvent e) {
message = "Key Released: " + e.getKeyChar();
repaint();
}
public void keyTyped(KeyEvent e) {
message = "Key Typed: " + e.getKeyChar();
repaint();
}
public static void main(String[] args) {
new KeyboardEventExample();
}
}

OUTPUT:-

KeyboardEventExample.java
javac
KeyboardEventExample.java java
KeyboardEventExample Key
Pressed: [key_char]
Key Released: [key_char]
Key Typed: [key_char]

Page 23
to

Q20 How establish a connection with Database

1. Import JDBC Packages: You need to import the necessary JDBC classes to interact
with the database.
2. Load Database Driver: You must load the database driver for the specific database
you are using (e.g., MySQL, Oracle, etc.).
3. Create a Connection: You need to use the DriverManager.getConnection() method to
establish the connection to the database.
4. Create a Statement: Once the connection is established, you can create a statement
object to execute SQL queries.
5. Execute Query: Use the statement object to execute queries (e.g., SELECT, INSERT,
UPDATE, etc.).
6. Close the Connection: After finishing the database operations, close the connection to
release the resources.

Example: Connecting to MySQL Database


Steps:
1. Install MySQL JDBC Driver: Make sure you have the MySQL JDBC driver (mysql-
connector-java-x.x.x.jar) in your classpath.
2. Database Setup: Assume the following details for the database:
o URL: jdbc:mysql://localhost:3306/testdb
o Username: root o Password: password

Code:
import java.sql.*;

public class DatabaseConnection


{ public static void main(String[] args)
{
String url = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password =
"password"; Connection conn
= null; try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, username, password);
System.out.println("Connection Established Successfully!");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println("User ID: " + rs.getInt("id"));
System.out.println("Username: " + rs.getString("username"));
System.out.println("Email: " + rs.getString("email"));
} rs.close();
stmt.close()
;
} catch (SQLException | ClassNotFoundException e) {

Page 24
e.printStackTrace();
} finally { try { if
(conn != null)
{ conn.close();
System.out.println("Connection Closed.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

OUTPUT:-

Connection Established Successfully!


User ID: 1
Username:RAJNISHMISHRA
Email:[email protected]
Connection Closed.

Page 25
WAP to

CODE:
Q21 retrieve a records from a table

import java.sql.Connection; import


java.sql.DriverManager; import
java.sql.ResultSet; import
java.sql.Statement; public class
RetrieveRecords { public static void
main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name";
String username =
"your_username"; String password
= "your_password"; try {
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String query = "SELECT id, name, department FROM employees";
ResultSet resultSet =
statement.executeQuery(query); while
(resultSet.next()) { int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String department = resultSet.getString("department");
System.out.println("ID: " + id + ", Name: " + name + ", Department: " + department);
}
resultSet.close();
statement.close();
connection.close(
);
} catch (Exception e) {
e.printStackTrace();
}
}
}

OUTPUT:-

Assume the employees table contains the following data:


Id name department
1 RAJNISHMISHRA HR
2 SIRI IT
3 Coco Sales

ID: 1, Name:RAJNISHMISHRA, Department: HR


ID: 2, Name: SIRI, Department: IT
ID: 3, Name: COco, Department: Sales

Page 26
WAP to

CODE:
Q22 execute SQL statements using java whiout comment with OUTPUT:-

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class ExecuteSQLStatements


{ public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name";
String username = "your_username";
String password = "your_password";

try {
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();

String createTableSQL = "CREATE TABLE IF NOT EXISTS employees (id INT


PRIMARY KEY, name VARCHAR(50), department VARCHAR(50))";
statement.execute(createTableSQL);

String insertSQL = "INSERT INTO employees (id, name, department) VALUES (1,
'Alice', 'HR'), (2, 'Bob', 'IT')"; int rowsInserted =
statement.executeUpdate(insertSQL);
System.out.println("Rows inserted: " + rowsInserted);

String updateSQL = "UPDATE employees SET department = 'Sales' WHERE id =


1"; int rowsUpdated = statement.executeUpdate(updateSQL);
System.out.println("Rows updated: " + rowsUpdated);

String deleteSQL = "DELETE FROM employees WHERE id =


2"; int rowsDeleted = statement.executeUpdate(deleteSQL);
System.out.println("Rows deleted: " + rowsDeleted);

statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

OUTPUT:-

Page 27
WAP to

CODE:
Rows inserted: 2
Rows updated: 1
Rows deleted: 1
Q23 update data in a table

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class UpdateTable { public static


void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name";
String username =
"your_username"; String password
= "your_password"; try {
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
String updateSQL = "UPDATE employees SET department = 'Marketing' WHERE id =
1"; int rowsUpdated = statement.executeUpdate(updateSQL);
System.out.println("Rows updated: " + rowsUpdated);
statement.close(); connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

OUTPUT:-

Assume the employees table initially contains:


id name department 1
RAJNISHMISHRA HR
2 VIki IT

Rows updated: 1

And the table will now contain:


id name department
1 RAJNISHMISHRA Marketing
2 Viki IT
Q24 delete data from a table

Page 28
WAP to

CODE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class DeleteDataFromTable


{ public static void main(String[] args)
{
String url = "jdbc:mysql://localhost:3306/your_database_name";
String username = "your_username";
String password = "your_password";

try {
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();

String deleteSQL = "DELETE FROM employees WHERE id =


2"; int rowsDeleted = statement.executeUpdate(deleteSQL);
System.out.println("Rows deleted: " + rowsDeleted);

statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

OUTPUT:-

Assume the employees table initially contains:


id name department
1 RAJNISHMISHRA HR
2 Viv IT
After running the program, the OUTPUT:- will be:

Rows deleted: 1
And the table will now contain:
id name department
1 RAJNISHMISHRA HR

Page 29
a

Q25 Create simple servlet that responds with "Hello, World!"

CODE:

import java.io.IOException; import


javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
response.getWriter().write("Hello, World!"); }
}

OUTPUT:-

Hello, World!

Page 30
Q26 Create a servlet to handle form data submitted via a POST request.

CODE:

import java.io.IOException; import


javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
@WebServlet("/submitForm")
public class FormHandlerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
response.setContentType("text/html");
response.getWriter().write("<html>
<body>");
response.getWriter().write("<h1>Form Submission
Received</h1>"); response.getWriter().write("<p>Name: " + name +
"</p>"); response.getWriter().write("<p>Email: " + email + "</p>");
response.getWriter().write("</body> </html>"); }
}
<!DOCTYPE html>
<html>
<head>
<title>Form Submission</title>
</head> <body>
<form action="submitForm" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<button type="submit">Submit</button>
</form> </body> </html>
<html> <body>
<h1>Form Submission Received</h1>
<p>Name:RAJNISHMISHRA</p>
<p>Email:[email protected]</p>
</body> </html>

OUTPUT:-

http://localhost:8080/your-webapp/form.html
Form Submission

Name: [ ]
Email: [ ]
[Submit ]

Page 31
a

Q27Create servlet that demonstrates session management by storing and retrieving user
information in a session.

CODE:

import java.io.IOException; import


javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/sessionDemo")
public class SessionManagementServlet extends HttpServlet { protected void
doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session = request.getSession();
String name =
request.getParameter("name"); String email
= request.getParameter("email");
session.setAttribute("userName", name);
session.setAttribute("userEmail", email);
response.setContentType("text/html");
response.getWriter().write("<html><body>"
);
response.getWriter().write("<h1>Session Data Stored</h1>");
response.getWriter().write("<p>Name: " + name + "</p>");
response.getWriter().write("<p>Email: " + email + "</p>");
response.getWriter().write("<a href='sessionRetrieve'>Retrieve Session
Data</a>"); response.getWriter().write("</body></html>"); }
}
@WebServlet("/sessionRetrieve")
class RetrieveSessionServlet extends HttpServlet { protected void
doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session = request.getSession(false); // Do not create a new session
response.setContentType("text/html");
response.getWriter().write("<html><body>");
if (session != null) {
String name = (String) session.getAttribute("userName"); String
email = (String) session.getAttribute("userEmail"); if (name !=
null && email != null) { response.getWriter().write("<h1>Session
Data Retrieved</h1>"); response.getWriter().write("<p>Name: " +
name + "</p>"); response.getWriter().write("<p>Email: " + email
+ "</p>");
} else { response.getWriter().write("<p>No data found in
session.</p>"); }
} else { response.getWriter().write("<p>No active session
found.</p>");
}

Page 32
response.getWriter().write("</body></
html>"); } }

Page 33
<!DOCTYPE html>
<html>
<head>
<title>Session Demo</title>
</head>
<body>
<h1>Session Management Demo</h1>
<form action="sessionDemo" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>

<button type="submit">Submit</button>
</form>
</body>
</html>

OUTPUT:-

Session Data Stored

Name:RAJNISHMISHRA
Email:[email protected]
[Retrieve Session Data]

Session Data Retrieved

Name:RAJNISHMISHRA
Email: [email protected]
Q28Create simple JSP page that displays "Hello, World!".

CODE:

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>

OUTPUT:-

Page 34
a

Hello, World!

Page 35
a

Q29 Create JavaBean and use it in a JSP page.

CODE:

package com.example;

public class User


{ private String name;
private String email;

public User() {
}
public String getName()
{ return name;
}
public void setName(String name)
{ this.name = name;
}
public String getEmail()
{ return email;
}
public void setEmail(String email)
{ this.email = email;
}
}

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-


8"
%>
<%@ page import="com.example.User" %>
<jsp:useBean id="user" class="com.example.User" scope="page" />
<jsp:setProperty name="user" property="name" value="RAJNISHMISHRA" />
<jsp:setProperty name="user" property="email"
value="[email protected]" />

<!DOCTYPE html>
<html>
<head>
<title>JavaBean Example</title>
</head>
<body>
<h1>User Details</h1>
<p>Name: <jsp:getProperty name="user" property="name" /></p>
<p>Email: <jsp:getProperty name="user" property="email" /></p>
</body>
</html>

Page 36
a

OUTPUT:-

User Details

Name: RAJNISHMISHRA
Email: [email protected]
Q30 Create JSP page that uses directives and scriptlets to display dynamic content.

CODE:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-


8"
%>
<%@ page import="java.time.LocalDateTime" %>

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content Example</title>
</head>
<body>
<h1>Dynamic Content Example</h1> <
%
String userName = "John Doe";
LocalDateTime currentTime = LocalDateTime.now();
%>
<p>Welcome, <%= userName %>!</p>
<p>Current Date and Time: <%= currentTime %></p>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content Example</title>
</head>
<body>
<h1>Dynamic Content Example</h1>
<p>Welcome,RAJNISHMISHRA!</p>
<p>Current Date and Time: 2024-11-21T10:45:00</p>
</body>
</html>

OUTPUT:-

Dynamic Content Example

Page 37
a

Welcome, RAJNISHMISHRA!
Current Date and Time: 2024-11-21T10:45:00

Page 38

You might also like