Final Practical
Final Practical
Final Practical
import java.awt.*;
import java.awt.event.*;
public Main() {
setLayout(null);
setSize(300, 200);
setVisible(true);
setTitle("Button Demo");
add(radio1);
add(radio2);
add(check1);
add(check2);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
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");
add(nameLabel);
add(nameField);
add(addressLabel);
add(addressArea);
add(submitButton);
add(clearButton);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
import java.awt.*;
import java.awt.event.*;
Final Practical 2
public Main() {
setLayout(null);
setSize(300, 300);
setTitle("Application");
setVisible(true);
add(label);
add(subjects);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
import java.awt.*;
import java.awt.event.*;
public Main() {
setLayout(null);
setTitle("Newspaper Selection");
setSize(300, 250);
setVisible(true);
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 Main() {
setLayout(new BorderLayout(10, 10));
Final Practical 4
setTitle("Border Layout Demo");
setSize(400, 300);
setVisible(true);
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);
}
});
}
import java.awt.*;
import java.awt.event.*;
public Main() {
setLayout(new FlowLayout());
setSize(400, 300);
setVisible(true);
Final Practical 5
fileMenu = new Menu("File");
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);
}
});
}
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 ).
Example:
List myList = new List(5, true); // 5 visible rows, multiple selection enabled
JComboBox(Object[] items) : Creates a combo box with items from the given array.
Example:
Example:
Final Practical 6
import javax.swing.*;
import javax.swing.tree.*;
public Main() {
setTitle("File Structure");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
bin.add(new DefaultMutableTreeNode("Help.c"));
bin.add(new DefaultMutableTreeNode("Help.exe"));
tc.add(new DefaultMutableTreeNode("BGI"));
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 Main() {
setTitle("Multiplication Program");
setSize(300, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
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.");
}
}
});
}
List Methods of MouseListener and MouseMotionListener . Write a program to demonstrate the use of mouseDragged
and mouseMoved method of MouseMotionListener.
Methods of MouseListener :
Methods of MouseMotionListener :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public Main() {
setTitle("Mouse Motion Listener Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
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());
}
});
}
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.*;
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
char[] password = passwordField.getPassword();
add(usernameLabel);
add(usernameField);
add(passwordLabel);
add(passwordField);
add(loginButton);
add(messageLabel);
}
Final Practical 9
frame.setVisible(true);
}
}
Write a program to demonstrate the use of WindowAdapter class. List Methods of All Listener Interfaces
The WindowAdapter class is used to handle window events in Java without needing to implement all the
methods of the WindowListener interface.
import java.awt.*;
import java.awt.event.*;
public Main() {
setTitle("WindowAdapter Demo");
setSize(400, 300);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
1. ActionListener :
void actionPerformed(ActionEvent e) : Invoked when an action event occurs (e.g., button click).
2. AdjustmentListener :
3. ContainerListener :
4. FocusListener :
5. KeyListener :
6. MouseListener :
Final Practical 10
void mouseExited(MouseEvent e) : Invoked when the mouse exits a component.
7. MouseMotionListener :
8. MouseWheelListener :
9. WindowListener :
10. ItemListener :
void itemStateChanged(ItemEvent e) : Invoked when the state of an item (such as a checkbox) changes.
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.
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.
import java.net.*;
import java.util.*;
// 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.*;
} 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.
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.
Similar to the previous constructor but takes an InetAddress object for the host.
Connects to the specified host and port and creates a socket on the local machine at the
specified address and port.
Similar to the previous constructor, but the host is specified by an InetAddress object instead
of a string
The ServerSocket class is used for server-side communication, allowing the server to listen for incoming
client connections.
1. ServerSocket()
Final Practical 12
Use the bind() method to bind it to a specific address and port later.
2. ServerSocket(int port)
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.
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.
import java.io.*;
import java.net.*;
// Close connections
input.close();
output.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client.java
import java.io.*;
import java.net.*;
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();
}
}
}
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.
4. DatagramSocket(DatagramSocketImpl impl)
5. DatagramSocket(SocketAddress bindaddr)
Creates a datagram socket, bound to the specified local socket address ( bindaddr ).
Constructs a DatagramPacket for receiving packets of length len , with an offset of off bytes
into the buffer.
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 .
Constructs a DatagramPacket for sending packets of length len , with an offset of off , to the
specified address and port.
Uses a middleware server to handle the communication between the client and the database.
Final Practical 14
Platform-independent and efficient, commonly used with databases like MySQL, Oracle, etc.
You need to import the necessary Java classes to establish a database connection.
import java.sql.*;
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:
Once the connection is established, you can create a Statement object to execute queries.
You can execute SQL queries using the executeQuery() method for SELECT queries or executeUpdate() for
INSERT, UPDATE, or DELETE queries.
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"));
}
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.*;
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!");
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.*;
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!");
Final Practical 16
// Step 6: Close resources
rs.close();
pstmt.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
HelloMSBTEServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println("<html><body>");
out.println("<h1>Hello MSBTE</h1>");
out.println("</body></html>");
}
}
web.xml
<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.*;
response.setContentType("text/html");
Final Practical 17
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");
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
<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