0% found this document useful (0 votes)
9 views18 pages

Final Practical

The document provides multiple Java AWT and Swing application examples demonstrating the use of various GUI components such as Radio Buttons, Checkboxes, Text Fields, Text Areas, and Layout Managers. It also includes programs for user authentication, mouse event handling, and displaying data structures like trees. Additionally, it explains the use of listener interfaces and methods associated with them in Java GUI programming.

Uploaded by

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

Final Practical

The document provides multiple Java AWT and Swing application examples demonstrating the use of various GUI components such as Radio Buttons, Checkboxes, Text Fields, Text Areas, and Layout Managers. It also includes programs for user authentication, mouse event handling, and displaying data structures like trees. Additionally, it explains the use of listener interfaces and methods associated with them in Java GUI programming.

Uploaded by

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

🧟‍♂️

Final Practical

Design an application to demonstrate the use of Radio Button and Checkbox.

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

public class Main extends Frame {


CheckboxGroup radioGroup;
Checkbox radio1, radio2;
Checkbox check1, check2;

public Main() {
setLayout(null);
setSize(300, 200);
setVisible(true);
setTitle("Button Demo");

radioGroup = new CheckboxGroup();


radio1 = new Checkbox("Option 1", radioGroup, true);
radio1.setBounds(50, 50, 100, 30);

radio2 = new Checkbox("Option 2", radioGroup, false);


radio2.setBounds(50, 80, 100, 30);

check1 = new Checkbox("Checkbox 1");


check1.setBounds(160, 50, 100, 30);

check2 = new Checkbox("Checkbox 2");


check2.setBounds(160, 80, 100, 30);

add(radio1);
add(radio2);
add(check1);
add(check2);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String[] args) {


new Main();
}
}

Design an application to create form using Text Field, Text Area, Button and Label.

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

Final Practical 1
public class Main extends Frame {
public Main() {
setLayout(null);
setSize(400, 300);
setVisible(true);
setTitle("Simple Form");

Label nameLabel = new Label("Name:");


nameLabel.setBounds(50, 50, 50, 30);
TextField nameField = new TextField(20);
nameField.setBounds(120, 50, 200, 30);

Label addressLabel = new Label("Address:");


addressLabel.setBounds(50, 100, 60, 30);
TextArea addressArea = new TextArea(4, 30);
addressArea.setBounds(120, 100, 200, 80);

Button submitButton = new Button("Submit");


submitButton.setBounds(120, 200, 80, 30);
Button clearButton = new Button("Clear");
clearButton.setBounds(220, 200, 80, 30);

add(nameLabel);
add(nameField);
add(addressLabel);
add(addressArea);
add(submitButton);
add(clearButton);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String[] args) {


new Main();
}
}

Write JAVA program to display following output

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

public class Main extends Frame {


Choice subjects;
Label label;

Final Practical 2
public Main() {
setLayout(null);
setSize(300, 300);
setTitle("Application");
setVisible(true);

subjects = new Choice();


subjects.add("Maths");
subjects.add("Physics");
subjects.add("Chemistry");
subjects.add("C++");
subjects.add("Java");
subjects.setBounds(100, 80, 100, 30);

label = new Label("Select Subjects You Like");


label.setBounds(80, 40, 160, 30);

add(label);
add(subjects);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String[] args) {


new Main();
}
}

Develop application to select multiple names of news papers.

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

public class Main extends Frame {


private List newspaperList;
private Label headerLabel;

public Main() {
setLayout(null);
setTitle("Newspaper Selection");
setSize(300, 250);
setVisible(true);

headerLabel = new Label("Select Your Favorite Newspapers");


headerLabel.setBounds(50, 40, 200, 30);

newspaperList = new List(6, false);


newspaperList.add("The Times of India");
newspaperList.add("The Hindu");
newspaperList.add("The Indian Express");
newspaperList.add("Hindustan Times");
newspaperList.add("The Economic Times");
newspaperList.add("Dainik Bhaskar");
newspaperList.setBounds(50, 80, 200, 100);

add(headerLabel);
add(newspaperList);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

Final Practical 3
public static void main(String[] args) {
new Main();
}
}

What is use of Layout Manager? List Constructors all Layout Manager and Write a program to generate
output as below.

A Layout Manager in Java AWT/Swing is used to control the arrangement and positioning of components
within a container. It automatically handles component sizing and positioning when the container is
resized.
Main Layout Managers and their Constructors:

1. FlowLayout:

FlowLayout()
FlowLayout(int align)
FlowLayout(int align, int hgap, int vgap)

2. BorderLayout:

BorderLayout()
BorderLayout(int hgap, int vgap)

3. GridLayout:

GridLayout()
GridLayout(int rows, int cols)
GridLayout(int rows, int cols, int hgap, int vgap)

4. CardLayout:

CardLayout()
CardLayout(int hgap, int vgap)

5. GridBagLayout:

GridBagLayout()

Program:

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

public class Main extends Frame {


private Label northLabel, southLabel, eastLabel, westLabel, centerLabel;

public Main() {
setLayout(new BorderLayout(10, 10));

Final Practical 4
setTitle("Border Layout Demo");
setSize(400, 300);
setVisible(true);

northLabel = new Label("NORTH", Label.CENTER);


southLabel = new Label("SOUTH", Label.CENTER);
eastLabel = new Label("EAST", Label.CENTER);
westLabel = new Label("WEST", Label.CENTER);
centerLabel = new Label("CENTER", Label.CENTER);

northLabel.setBackground(Color.lightGray);
southLabel.setBackground(Color.lightGray);
eastLabel.setBackground(Color.lightGray);
westLabel.setBackground(Color.lightGray);
centerLabel.setBackground(Color.lightGray);

add(northLabel, BorderLayout.NORTH);
add(southLabel, BorderLayout.SOUTH);
add(eastLabel, BorderLayout.EAST);
add(westLabel, BorderLayout.WEST);
add(centerLabel, BorderLayout.CENTER);

setBackground(Color.white);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String[] args) {


new Main();
}
}

Write JAVA program to display following output

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

public class Main extends Frame {


private MenuBar menuBar;
private Menu fileMenu;
private MenuItem powerPoint, word, excel, exit;

public Main() {
setLayout(new FlowLayout());
setSize(400, 300);
setVisible(true);

menuBar = new MenuBar();

Final Practical 5
fileMenu = new Menu("File");

powerPoint = new MenuItem("Powerpoint");


word = new MenuItem("Word");
excel = new MenuItem("Excel");
exit = new MenuItem("Exit");

fileMenu.add(powerPoint);
fileMenu.add(word);
fileMenu.add(excel);
fileMenu.addSeparator();
fileMenu.add(exit);

menuBar.add(fileMenu);
setMenuBar(menuBar);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public static void main(String[] args) {


new Main();
}
}

Explain Constructors of List, JComboBox, Choice

1. List Constructors (AWT):

List() : Creates a new scrolling list with a default number of visible lines.

List(int rows) : Creates a new scrolling list with the specified number of visible lines (rows ).

: Creates a new scrolling list with a specified number of visible


List(int rows, boolean multipleMode)

lines (rows ) and enables multiple selection mode if multipleMode is true.

Example:

List myList = new List(5, true); // 5 visible rows, multiple selection enabled

2. JComboBox Constructors (Swing):

JComboBox() : Creates an empty combo box.

JComboBox(Object[] items) : Creates a combo box with items from the given array.

Example:

String[] items = {"One", "Two", "Three"};


JComboBox<String> combo = new JComboBox<>(items);

3. Choice Constructors (AWT):

Choice() : Creates an empty choice box (drop-down menu).

Example:

Choice choice = new Choice();


choice.add("Option 1");
choice.add("Option 2");

Write a program code to generate the following output

Final Practical 6
import javax.swing.*;
import javax.swing.tree.*;

public class Main extends JFrame {


private JTree tree;

public Main() {
setTitle("File Structure");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

DefaultMutableTreeNode root = new DefaultMutableTreeNode("C:");


DefaultMutableTreeNode tc = new DefaultMutableTreeNode("TC");
root.add(tc);

DefaultMutableTreeNode bin = new DefaultMutableTreeNode("BIN");


tc.add(bin);

bin.add(new DefaultMutableTreeNode("Help.c"));
bin.add(new DefaultMutableTreeNode("Help.exe"));

tc.add(new DefaultMutableTreeNode("BGI"));

tree = new JTree(root);

JScrollPane scrollPane = new JScrollPane(tree);


add(scrollPane);

for (int i = 0; i < tree.getRowCount(); i++) {


tree.expandRow(i);
}
}

public static void main(String[] args) {


Main main = new Main();
main.setVisible(true);
}
}

Develop a program to accept two numbers and display product of two numbers when user pressed
“Multiply” button.

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

public class Main extends JFrame {


private JTextField num1Field, num2Field;
private JButton multiplyButton;
private JLabel resultLabel;

public Main() {
setTitle("Multiplication Program");
setSize(300, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

JLabel num1Label = new JLabel("Enter first number:");


num1Field = new JTextField(10);
JLabel num2Label = new JLabel("Enter second number:");
num2Field = new JTextField(10);
multiplyButton = new JButton("Multiply");
resultLabel = new JLabel("Product: ");

add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(multiplyButton);

Final Practical 7
add(resultLabel);

multiplyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double product = num1 * num2;
resultLabel.setText("Product: " + product);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers.");
}
}
});
}

public static void main(String[] args) {


Main frame = new Main();
frame.setVisible(true);
}
}

List Methods of MouseListener and MouseMotionListener . Write a program to demonstrate the use of mouseDragged
and mouseMoved method of MouseMotionListener.

Methods of MouseListener :

1. mouseClicked(MouseEvent e) : Called when the mouse is clicked (pressed and released).

2. mousePressed(MouseEvent e) : Called when a mouse button is pressed.

3. mouseReleased(MouseEvent e) : Called when a mouse button is released.

4. mouseEntered(MouseEvent e) : Called when the mouse pointer enters the component.

5. mouseExited(MouseEvent e) : Called when the mouse pointer exits the component.

Methods of MouseMotionListener :

1. mouseMoved(MouseEvent e) : Called when the mouse is moved over the component.

2. mouseDragged(MouseEvent e) : Called when the mouse is moved with a button pressed.

Program to Demonstrate mouseDragged and mouseMoved Methods of MouseMotionListener :

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

public class Main extends JFrame {


private JLabel statusLabel;

public Main() {
setTitle("Mouse Motion Listener Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

statusLabel = new JLabel("Move or drag the mouse inside the frame");


add(statusLabel);

addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
statusLabel.setText("Mouse Moved at: " + e.getX() + ", " + e.getY());
}

Final Practical 8
public void mouseDragged(MouseEvent e) {
statusLabel.setText("Mouse Dragged at: " + e.getX() + ", " + e.getY());
}
});
}

public static void main(String[] args) {


Main frame = new Main();
frame.setVisible(true);
}
}

Explanation:
This program creates a window and listens for mouse movements and dragging events.

When the mouse is moved, the mouseMoved method is triggered and updates the statusLabel with the current
mouse coordinates.

When the mouse is dragged, the mouseDragged method updates the label with the drag coordinates.

This demonstrates how the MouseMotionListener methods work for tracking mouse movement and dragging inside
a JFrame.

Write a program using JPasswordField and JTextField to demonstrate the use of user authentication.

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

public class Main extends JFrame {


public Main() {
setTitle("User Authentication");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

JLabel usernameLabel = new JLabel("Username:");


JTextField usernameField = new JTextField(20);

JLabel passwordLabel = new JLabel("Password:");


JPasswordField passwordField = new JPasswordField(20);

JButton loginButton = new JButton("Login");


JLabel messageLabel = new JLabel(" ");

loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
char[] password = passwordField.getPassword();

if (username.equals("user") && new String(password).equals("pass")) {


messageLabel.setText("Login Successful");
messageLabel.setForeground(Color.GREEN);
} else {
messageLabel.setText("Invalid Credentials");
messageLabel.setForeground(Color.RED);
}
}
});

add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
add(loginButton);
add(messageLabel);
}

public static void main(String[] args) {


Main frame = new Main();

Final Practical 9
frame.setVisible(true);
}
}

Write a program to demonstrate the use of WindowAdapter class. List Methods of All Listener Interfaces

Program to Demonstrate the Use of WindowAdapter Class:

The WindowAdapter class is used to handle window events in Java without needing to implement all the
methods of the WindowListener interface.

You can override only the methods you need.

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

public class Main extends Frame {

public Main() {
setTitle("WindowAdapter Demo");
setSize(400, 300);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public static void main(String[] args) {


Main demo = new Main();
demo.setVisible(true);
}
}

Methods of All Listener Interfaces in Java:

1. ActionListener :

void actionPerformed(ActionEvent e) : Invoked when an action event occurs (e.g., button click).

2. AdjustmentListener :

void adjustmentValueChanged(AdjustmentEvent e) : Invoked when a scrollbar's value changes.

3. ContainerListener :

void componentAdded(ContainerEvent e) : Invoked when a component is added to the container.

void componentRemoved(ContainerEvent e) : Invoked when a component is removed from the container.

4. FocusListener :

void focusGained(FocusEvent e) : Invoked when a component gains focus.

void focusLost(FocusEvent e) : Invoked when a component loses focus.

5. KeyListener :

void keyPressed(KeyEvent e) : Invoked when a key is pressed.

void keyReleased(KeyEvent e) : Invoked when a key is released.

void keyTyped(KeyEvent e) : Invoked when a key is typed (pressed and released).

6. MouseListener :

void mouseClicked(MouseEvent e) : Invoked when the mouse is clicked.

void mousePressed(MouseEvent e) : Invoked when the mouse button is pressed.

void mouseReleased(MouseEvent e) : Invoked when the mouse button is released.

void mouseEntered(MouseEvent e) : Invoked when the mouse enters a component.

Final Practical 10
void mouseExited(MouseEvent e) : Invoked when the mouse exits a component.

7. MouseMotionListener :

void mouseDragged(MouseEvent e) : Invoked when the mouse is dragged.

void mouseMoved(MouseEvent e) : Invoked when the mouse is moved.

8. MouseWheelListener :

void mouseWheelMoved(MouseWheelEvent e) : Invoked when the mouse wheel is rotated.

9. WindowListener :

void windowOpened(WindowEvent e) : Invoked when a window is opened.

void windowClosing(WindowEvent e) : Invoked when a window is closing.

void windowClosed(WindowEvent e) : Invoked when a window is closed.

void windowIconified(WindowEvent e) : Invoked when a window is iconified.

void windowDeiconified(WindowEvent e) : Invoked when a window is deiconified.

void windowActivated(WindowEvent e) : Invoked when a window is activated.

void windowDeactivated(WindowEvent e) : Invoked when a window is deactivated.

10. ItemListener :

void itemStateChanged(ItemEvent e) : Invoked when the state of an item (such as a checkbox) changes.

Write a program to demonstrate all Factory methods of InetAddress class.

The InetAddress class in Java is used for representing an IP address, and it provides several factory
methods to retrieve the IP address of a machine or to resolve hostnames.

Factory Methods of InetAddress class:

1. getByName(String host) : Returns the InetAddress object for the given host name or IP address.

2. getByAddress(String host, byte[] addr) : Returns an InetAddress object for the given host and IP address in byte
format.

3. getLocalHost() : Returns the InetAddress object of the local machine (the machine running the program).

4. getAllByName(String host) : Returns an array of InetAddress objects for the given host name.

Program Demonstrating All Factory Methods of InetAddress Class:

import java.net.*;
import java.util.*;

public class Main {

public static void main(String[] args) {


try {
// 1. getByName(String host)
InetAddress address1 = InetAddress.getByName("www.google.com");
System.out.println("1. getByName(): " + address1);

// 2. getByAddress(String host, byte[] addr)


byte[] ipAddress = {127, 0, 0, 1}; // IP address for localhost (127.0.0.1)
InetAddress address2 = InetAddress.getByAddress("localhost", ipAddress);
System.out.println("2. getByAddress(): " + address2);

// 3. getLocalHost()
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("3. getLocalHost(): " + localHost);

// 4. getAllByName(String host)
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
System.out.println("4. getAllByName(): ");
for (InetAddress addr : addresses) {
System.out.println(addr);
}
} catch (UnknownHostException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Final Practical 11
Sample Output:

1. getByName(): www.google.com/142.251.42.100
2. getByAddress(): localhost/127.0.0.1
3. getLocalHost(): d4bd4d3de0d5/172.31.196.42
4. getAllByName(): www.google.com/142.251.42.100

Write a program using URL class to retrieve the host, protocol, port and file of URL
http://www.msbte.org.in

import java.net.*;

public class Main {


public static void main(String[] args) {
try {
URL url = new URL("http://www.msbte.org.in");
String protocol = url.getProtocol();
System.out.println("Protocol: " + protocol);

String host = url.getHost();


System.out.println("Host: " + host);

int port = url.getPort();


if (port == -1) {
System.out.println("Port: Default port (80 for HTTP)");
} else {
System.out.println("Port: " + port);
}

String file = url.getFile();


System.out.println("File: " + file);

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

List and explain Constructors of Socket and ServerSocket Class. Write a program using Socket and ServerSocket
to check whether given number is odd or even. Client will send number and Server will check and responds
for odd or even.

Constructors of Socket Class:

The Socket class provides constructors to establish a connection with a server over the network.

1. Socket() :

Creates an unconnected socket. You need to use the connect() method to connect it to a server.

2. Socket(String host, int port) :

Attempts to connect to the specified server at the given port.

If no exception is thrown, the connection is successful.

3. Socket(InetAddress host, int port) :

Similar to the previous constructor but takes an InetAddress object for the host.

4. Socket(String host, int port, InetAddress localAddress, int localPort) :

Connects to the specified host and port and creates a socket on the local machine at the
specified address and port.

5. Socket(InetAddress host, int port, InetAddress localAddress, int localPort) :

Similar to the previous constructor, but the host is specified by an InetAddress object instead
of a string

Constructors of ServerSocket Class:

The ServerSocket class is used for server-side communication, allowing the server to listen for incoming
client connections.

1. ServerSocket()

Creates an unbound server socket.

Final Practical 12
Use the bind() method to bind it to a specific address and port later.

2. ServerSocket(int port)

Binds the server socket to the specified port.

Throws an exception if the port is already in use.

3. ServerSocket(int port, int backlog)

Similar to the previous constructor, but the backlog parameter specifies how many incoming client
connections can be queued up before the server starts accepting them.

4. ServerSocket(int port, int backlog, InetAddress address)

Similar to the previous constructor, but the InetAddress parameter specifies the local IP address
to bind to.

This is useful if the server has multiple IP addresses and needs to choose which one to use for
client connections.

Program to Check Odd/Even Using Socket and ServerSocket :


Server.java

import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(1234)) {
System.out.println("Server is waiting for client connection...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected!");

// Input and Output streams


DataInputStream input = new DataInputStream(clientSocket.getInputStream());
DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());

// Read the number from client


int number = input.readInt();
String result = (number % 2 == 0) ? "Even" : "Odd";

// Send the result back to client


output.writeUTF(result);

// Close connections
input.close();
output.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

client.java

import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 1234)) {
// Input and Output streams
DataInputStream input = new DataInputStream(System.in);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
DataInputStream serverInput = new DataInputStream(socket.getInputStream());

// Get number from user


System.out.print("Enter a number: ");
int number = input.readInt();

// Send number to server


output.writeInt(number);

// Receive the result from server

Final Practical 13
String result = serverInput.readUTF();
System.out.println("Server response: The number is " + result);

// Close connections
input.close();
output.close();
serverInput.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explain Constructors of DatagramSocket and DatagramPacket class.

Constructors of DatagramSocket Class:

1. DatagramSocket()

Constructs a datagram socket and binds it to any available port on the local host.

2. DatagramSocket(int port)

Constructs a datagram socket and binds it to the specified port on the local host.

3. DatagramSocket(int port, InetAddress iaddr)

Creates a datagram socket, bound to the specified local address ( iaddr ).

4. DatagramSocket(DatagramSocketImpl impl)

Creates an unbound datagram socket with the specified DatagramSocketImpl .

5. DatagramSocket(SocketAddress bindaddr)

Creates a datagram socket, bound to the specified local socket address ( bindaddr ).

Constructors of DatagramPacket Class:

1. DatagramPacket(byte[] buf, int len)

Constructs a DatagramPacket for receiving packets of length len .

2. DatagramPacket(byte[] buf, int off, int len)

Constructs a DatagramPacket for receiving packets of length len , with an offset of off bytes
into the buffer.

3. DatagramPacket(byte[] buf, int len, InetAddress addr, int port)

Constructs a DatagramPacket for sending packets of length len to the specified port number on the
specified host (address).

4. DatagramPacket(byte[] buf, int off, int len, InetAddress addr, int port)

Constructs a DatagramPacket for sending packets of length len , with an offset of off , to the
specified port number on the specified host .

5. DatagramPacket(byte[] buf, int off, int len, SocketAddress addr)

Constructs a DatagramPacket for sending packets of length len , with an offset of off , to the
specified address and port.

List JDBC Driver. Write a steps to Write JDBC program

Types of JDBC Drivers:

1. JDBC-ODBC Bridge Driver (Type 1):

Uses ODBC driver to connect to the database.

Deprecated and not recommended for use in modern applications.

2. Native-API Driver (Type 2):

Uses database-specific native code to communicate with the database.

Requires a separate driver for each database.

3. Network Protocol, Pure Java Driver (Type 3):

Uses a middleware server to handle the communication between the client and the database.

Can work with any database that supports the protocol.

4. Native Protocol, Pure Java Driver (Type 4):

Communicates directly with the database using database-specific protocol.

Final Practical 14
Platform-independent and efficient, commonly used with databases like MySQL, Oracle, etc.

Steps to Write a JDBC Program:

1. Import Required Packages:

You need to import the necessary Java classes to establish a database connection.

import java.sql.*;

2. Register the JDBC Driver:

For Type 4 driver, you need to load the database driver class (optional in newer versions, as
it's automatically loaded).

Class.forName("com.mysql.cj.jdbc.Driver");

3. Establish a Connection:

Use DriverManager to establish a connection to the database.

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "user


name", "password");

4. Create a Statement Object:

Once the connection is established, you can create a Statement object to execute queries.

Statement stmt = conn.createStatement();

5. Execute SQL Query:

You can execute SQL queries using the executeQuery() method for SELECT queries or executeUpdate() for
INSERT, UPDATE, or DELETE queries.

ResultSet rs = stmt.executeQuery("SELECT * FROM users");

6. Process the Result:

If you're executing a SELECT query, you can process the results returned in a ResultSet .

while (rs.next()) {
System.out.println(rs.getString("name"));
}

7. Close the Resources:

It's important to close all database resources (Connection, Statement, ResultSet) to avoid
memory leaks.

rs.close();
stmt.close();
conn.close();

Write a Program to create a Student Table in database and insert a record in a Student table.

import java.sql.*;

public class CreateStudentTable {


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

String createTableQuery = "CREATE TABLE IF NOT EXISTS Student ("


+ "id INT PRIMARY KEY, "
+ "name VARCHAR(50), "
+ "age INT)";

String insertRecordQuery = "INSERT INTO Student (id, name, age) VALUES (?, ?, ?)";

try {
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected to the database!");

Final Practical 15
Statement stmt = conn.createStatement();
stmt.executeUpdate(createTableQuery);
System.out.println("Student table created!");

PreparedStatement pstmt = conn.prepareStatement(insertRecordQuery);


pstmt.setInt(1, 1);
pstmt.setString(2, "Jay Kadlag");
pstmt.setInt(3, 20);
pstmt.executeUpdate();
System.out.println("Record inserted successfully!");

pstmt.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Write a Program to create a Student Table in database and using ResultSet object display records of
all students.

import java.sql.*;

public class DisplayStudentRecords {


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

String createTableQuery = "CREATE TABLE IF NOT EXISTS Student ("


+ "id INT PRIMARY KEY, "
+ "name VARCHAR(50), "
+ "age INT)";

String insertRecordQuery = "INSERT INTO Student (id, name, age) VALUES (?, ?, ?)";
String selectAllQuery = "SELECT * FROM Student";

try {
// Step 1: Establish a connection
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected to the database!");

// Step 2: Create the Student table if it doesn't exist


Statement stmt = conn.createStatement();
stmt.executeUpdate(createTableQuery);
System.out.println("Student table created!");

// Step 3: Insert a record into the Student table


PreparedStatement pstmt = conn.prepareStatement(insertRecordQuery);
pstmt.setInt(1, 1); // Student ID
pstmt.setString(2, "Jay Kadlag"); // Student Name
pstmt.setInt(3, 20); // Student Age
pstmt.executeUpdate();
System.out.println("Record inserted successfully!");

// Step 4: Query all records from the Student table


ResultSet rs = stmt.executeQuery(selectAllQuery);

// Step 5: Display records using ResultSet


System.out.println("Student Records:");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}

Final Practical 16
// Step 6: Close resources
rs.close();
pstmt.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Develop servlet program to print Hello MSBTE in browser window.

HelloMSBTEServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloMSBTEServlet extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body>");
out.println("<h1>Hello MSBTE</h1>");
out.println("</body></html>");
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">

<servlet>
<servlet-name>HelloMSBTEServlet</servlet-name>
<servlet-class>HelloMSBTEServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloMSBTEServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

Develop HttpServlet program to add two numbers and display addition on browser browser window.

AddNumbersServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class AddNumbersServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Final Practical 17
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");

if (num1 != null && num2 != null) {


try {
int number1 = Integer.parseInt(num1);
int number2 = Integer.parseInt(num2);

int sum = number1 + number2;

out.println("<html><body>");
out.println("<h1>Result: " + sum + "</h1>");
out.println("</body></html>");
} catch (NumberFormatException e) {
out.println("<html><body>");
out.println("<h1>Error: Please enter valid numbers!</h1>");
out.println("</body></html>");
}
} else {
out.println("<html><body>");
out.println("<h1>Error: Please provide two numbers as parameters!</h1>");
out.println("</body></html>");
}
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">

<servlet>
<servlet-name>AddNumbersServlet</servlet-name>
<servlet-class>AddNumbersServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>AddNumbersServlet</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>

</web-app>

Final Practical 18

You might also like