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

Java Swing and Thread Programming Guide

Uploaded by

aryanpurihrd
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 views14 pages

Java Swing and Thread Programming Guide

Uploaded by

aryanpurihrd
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

Q.

(a) Classify the Swing hierarchy with a suitable diagram. Write a Java program to
demonstrate the uses of the following classes:

(i) JButton (ii) JLabel (iii) JTable (iv) JList (v) JSlider

Swing Hierarchy Diagram:

The Swing hierarchy is structured as follows:

css
Copy code
[Link]
|
+--[Link]
|
+--[Link]
|
+--[Link]
|
+--[Link]
| |
| +--[Link]
|
+--[Link]
|
+--[Link]
|
+--[Link]
|
+--[Link]

Java Program Example:

java
Copy code
import [Link].*;

public class SwingExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](500, 500);

JPanel panel = new JPanel();

JButton button = new JButton("Click Me");


JLabel label = new JLabel("This is a label");
String[] columnNames = {"Column 1", "Column 2"};
Object[][] data = {{1, "One"}, {2, "Two"}};
JTable table = new JTable(data, columnNames);
JList<String> list = new JList<>(new String[]{"Item 1", "Item 2",
"Item 3"});
JSlider slider = new JSlider(0, 100);

[Link](button);
[Link](label);
[Link](new JScrollPane(table));
[Link](new JScrollPane(list));
[Link](slider);

[Link](panel);
[Link](true);
}
}

(b) Differences between a TCP socket and a UDP socket? How are they created in Java?

TCP vs UDP:

 TCP (Transmission Control Protocol): Connection-oriented, reliable, ensures data


is received in order, more overhead.
 UDP (User Datagram Protocol): Connectionless, not reliable, does not guarantee
order, less overhead.

Creating Sockets in Java:

TCP Socket:

java
Copy code
// Server side
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = [Link]();

// Client side
Socket socket = new Socket("hostname", port);

UDP Socket:

java
Copy code
// Server and Client side
DatagramSocket socket = new DatagramSocket(port);

(c) What are the directive tags of JSP? Write a JSP page to demonstrate the use of
them.

Directive Tags:

 Page: Defines page-dependent attributes.


 Include: Includes a file during the translation phase.
 Taglib: Declares a tag library.

JSP Page Example:

jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="[Link]" %>
<%@ taglib uri="[Link] prefix="c" %>
<html>
<head>
<title>Directive Example</title>
</head>
<body>
<h2>Directive Example</h2>
<c:out value="Welcome to JSP Directives!" />
</body>
</html>

(d) What do you understand by session tracking? What are the session tracking
techniques? Demonstrate any one of them.

Session Tracking:

 Session tracking is used to maintain state about a series of requests from the same
user (session) across some period.

Techniques:

 Cookies
 URL rewriting
 Hidden form fields
 HttpSession

HttpSession Example:

jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
HttpSession session = [Link]();
String username = (String) [Link]("username");
if (username == null) {
[Link]("username", "Guest");
username = "Guest";
}
%>
<html>
<head>
<title>Session Example</title>
</head>
<body>
<h2>Welcome, <%= username %></h2>
</body>
</html>

Q.2

(a) What is a Daemon Thread? Write a Java program to implement following methods
in a Thread:

(i) getPriority() (ii) isAlive() (iii) setPriority() (iv) getName() (v) yield()
Daemon Thread:

 A daemon thread is a low-priority thread that runs in the background to perform tasks
such as garbage collection.

Java Program Example:

java
Copy code
class MyThread extends Thread {
public void run() {
[Link]("Running thread: " + getName());
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]("Thread-1");
[Link](Thread.MAX_PRIORITY);

[Link]("Thread Name: " + [Link]());


[Link]("Thread Priority: " + [Link]());
[Link]("Is Thread Alive: " + [Link]());

[Link]();

[Link]("Is Thread Alive after start: " + [Link]());

[Link]();

[Link]("Yielding to other threads");


}
}

(b) What is Servlet? Differentiate ServletConfig and ServletContext objects.

Servlet:

 A servlet is a Java program that extends the capabilities of servers that host
applications accessed by means of a request-response programming model.

ServletConfig vs ServletContext:

 ServletConfig: Provides servlet-specific configuration. Used to initialize parameters.


 ServletContext: Provides context for the servlet within the web application. Used for
application-wide parameters.

(c) Write a Java program to replace the second element of an array list with the
specified element and then reverse this array list.

Java Program Example:

java
Copy code
import [Link];
import [Link];

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("One");
[Link]("Two");
[Link]("Three");

[Link]("Original list: " + list);

[Link](1, "New Element");


[Link]("After replacement: " + list);

[Link](list);
[Link]("After reversing: " + list);
}
}

(d) Write a Java program to create and start multiple threads that increment a shared
counter variable concurrently.

Java Program Example:

java
Copy code
class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

class CounterThread extends Thread {


private Counter counter;

public CounterThread(Counter counter) {


[Link] = counter;
}

public void run() {


for (int i = 0; i < 1000; i++) {
[Link]();
}
}
}

public class ThreadExample {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new CounterThread(counter);
Thread t2 = new CounterThread(counter);

[Link]();
[Link]();

[Link]();
[Link]();

[Link]("Final count: " + [Link]());


}
}

Q.3

(a) Write a program to display an error message to the user if an exception occurs in the
JSP page. Consider a null string and find out the length of the string using length()
method of Java. Create an error handler to handle the exception thrown by this JSP
page.

JSP Error Handling Example:

jsp
Copy code
<%@ page isErrorPage="false" %>
<%
try {
String str = null;
int length = [Link]();
} catch (NullPointerException e) {
[Link]("[Link]");
}
%>

[Link]:

jsp
Copy code
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h2>An error occurred: <%= [Link]() %></h2>
</body>
</html>

(b) What do you understand by Java thread synchronization problem? Explain with
suitable example. Write a Java program to book the tickets for a cricket match, when
multiple persons trying to book tickets on a same time (Using synchronized block
method).

Java Thread Synchronization Problem:

 Occurs when multiple threads try to access a shared resource simultaneously leading
to inconsistent results.

Java Program Example:


java
Copy code
class TicketBooking {
private int tickets = 10;

public void bookTicket(String name, int numberOfTickets) {


synchronized(this) {
if (tickets >= numberOfTickets) {
[Link](name + " booked " + numberOfTickets + "
tickets.");
tickets -= numberOfTickets;
} else {
[Link]("Not enough tickets for " + name);
}
}
}
}

class BookingThread extends Thread {


private TicketBooking booking;
private String name;
private int tickets;

public BookingThread(TicketBooking booking, String name, int tickets) {


[Link] = booking;
[Link] = name;
[Link] = tickets;
}

public void run() {


[Link](name, tickets);
}
}

public class BookingExample {


public static void main(String[] args) {
TicketBooking booking = new TicketBooking();

BookingThread t1 = new BookingThread(booking, "User1", 5);


BookingThread t2 = new BookingThread(booking, "User2", 7);

[Link]();
[Link]();
}
}

(c) Explain MouseListener interface. Create a login form which contains a userID,
password field, and two buttons, Submit and Reset. If the userID or password field is
left blank, then on click of submit button, show a message to the user to fill the empty
fields. On click of reset button, clear the fields.

MouseListener Explanation:

 An interface for receiving mouse events (clicks, presses, releases, enters, exits).

Java Program Example:

java
Copy code
import [Link].*;
import [Link].*;

public class LoginForm extends JFrame implements MouseListener {


JTextField userIDField;
JPasswordField passwordField;
JButton submitButton, resetButton;
JLabel messageLabel;

public LoginForm() {
userIDField = new JTextField(20);
passwordField = new JPasswordField(20);
submitButton = new JButton("Submit");
resetButton = new JButton("Reset");
messageLabel = new JLabel();

[Link](this);
[Link](this);

setLayout(new [Link](4, 2));


add(new JLabel("User ID:"));
add(userIDField);
add(new JLabel("Password:"));
add(passwordField);
add(submitButton);
add(resetButton);
add(messageLabel);

setTitle("Login Form");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void mouseClicked(MouseEvent e) {


if ([Link]() == submitButton) {
if ([Link]().isEmpty() ||
[Link]().length == 0) {
[Link]("Please fill in all fields.");
} else {
[Link]("Welcome " + [Link]());
}
} else if ([Link]() == resetButton) {
[Link]("");
[Link]("");
[Link]("");
}
}

public void mousePressed(MouseEvent e) {}


public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

public static void main(String[] args) {


new LoginForm();
}
}
Q.4

(a) What is socket programming? Write a Java program where the client sends a string
as a message and the server counts the characters in the received message from the
client. Server sends this value back to the client. (Server should be able to serve multiple
clients simultaneously).

Socket Programming:

 Networking concept where a socket provides the endpoint for sending or receiving
data across a computer network.

Java Server Program:

java
Copy code
import [Link].*;
import [Link].*;

public class Server {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345);
[Link]("Server started...");

while (true) {
Socket socket = [Link]();
new ClientHandler(socket).start();
}
}
}

class ClientHandler extends Thread {


private Socket socket;

public ClientHandler(Socket socket) {


[Link] = socket;
}

public void run() {


try {
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](),
true);

String message = [Link]();


int length = [Link]();
[Link]("Message length: " + length);

[Link]();
} catch (IOException e) {
[Link]();
}
}
}

Java Client Program:


java
Copy code
import [Link].*;
import [Link].*;

public class Client {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));

[Link]("Hello Server");
String response = [Link]();
[Link]("Server response: " + response);

[Link]();
}
}

(b) Explain the uses of prepared and callable statements with a suitable example. Write
a JDBC program to accept empid as command line argument and display the name of
the employee who is getting highest salary from the employee table.

PreparedStatement vs CallableStatement:

 PreparedStatement: Used for executing SQL queries with parameters.


 CallableStatement: Used for executing stored procedures.

JDBC Program Example:

java
Copy code
import [Link].*;

public class JDBCExample {


public static void main(String[] args) {
if ([Link] < 1) {
[Link]("Please provide empid as argument");
return;
}
int empid = [Link](args[0]);

String url = "jdbc:mysql://localhost:3306/yourdatabase";


String user = "yourusername";
String password = "yourpassword";

try (Connection con = [Link](url, user,


password)) {
String query = "SELECT name FROM employees WHERE salary =
(SELECT MAX(salary) FROM employees)";
PreparedStatement pst = [Link](query);
ResultSet rs = [Link]();

if ([Link]()) {
[Link]("Employee with highest salary: " +
[Link]("name"));
}
} catch (SQLException e) {
[Link]();
}
}
}

(c) Explain the Queue interface of collection framework. Write a Java program to
perform following actions on priority Queue:

(i) Add all elements from one priority queue to another (ii) Remove all elements (iii) Retrieve
the first element (iv) Compare two priority queues (v) Count the number of elements

Queue Interface:

 The Queue interface is part of the Java Collections Framework and represents a
collection designed for holding elements prior to processing. Implementations include
LinkedList, PriorityQueue, etc.

Java Program Example:

java
Copy code
import [Link];

public class PriorityQueueExample {


public static void main(String[] args) {
PriorityQueue<Integer> pq1 = new PriorityQueue<>();
PriorityQueue<Integer> pq2 = new PriorityQueue<>();

[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);

// (i) Add all elements from one priority queue to another


[Link](pq2);
[Link]("After adding pq2 to pq1: " + pq1);

// (ii) Remove all elements


[Link]();
[Link]("After clearing pq1: " + pq1);

// Adding elements back to pq1 for further operations


[Link](10);
[Link](20);
[Link](30);

// (iii) Retrieve the first element


[Link]("First element: " + [Link]());

// (iv) Compare two priority queues


[Link]("pq1 equals pq2: " + [Link](pq2));

// (v) Count the number of elements


[Link]("Number of elements in pq1: " + [Link]());
}
}
Q.5

(a) Write short notes on the following:

(i) Layout Managers (ii) Runnable interface (iii) ActionListener (iv) [Link]() method

Layout Managers:

 FlowLayout: Default layout manager for a JPanel. Lays out components in a


directional flow.
 BorderLayout: Lays out components in five regions: north, south, east, west, and
center.
 GridLayout: Lays out components in a rectangular grid.

Runnable Interface:

 Represents a task that can be executed by a thread. Implementing classes define the
run() method.

ActionListener:

 An interface that receives action events, e.g., button clicks. Implement the
actionPerformed method to handle actions.

[Link]() Method:

 Causes the current thread to pause execution for a specified period.

(b) Define Encapsulation. Write a Java program to create a class called Student with
private instance variables student_id, student_name, and grades. Provide public getter
and setter methods to access and modify the student_id and student_name variables.
However, provide a method called addGrade() that allows adding a grade to the grades
variable while performing additional validation.

Encapsulation:

 Encapsulation is the wrapping of data (variables) and methods (functions) into a


single unit called a class. It restricts direct access to some of the object's components.

Java Program Example:

java
Copy code
import [Link];

class Student {
private int student_id;
private String student_name;
private ArrayList<Integer> grades = new ArrayList<>();

public int getStudentId() {


return student_id;
}

public void setStudentId(int student_id) {


this.student_id = student_id;
}

public String getStudentName() {


return student_name;
}

public void setStudentName(String student_name) {


this.student_name = student_name;
}

public void addGrade(int grade) {


if (grade >= 0 && grade <= 100) {
[Link](grade);
} else {
[Link]("Invalid grade: " + grade);
}
}

public ArrayList<Integer> getGrades() {


return grades;
}
}

public class EncapsulationExample {


public static void main(String[] args) {
Student student = new Student();
[Link](1);
[Link]("John Doe");

[Link](85);
[Link](95);
[Link](105); // Invalid grade

[Link]("Student ID: " + [Link]());


[Link]("Student Name: " + [Link]());
[Link]("Grades: " + [Link]());
}
}

(c) What is polymorphism? Explain how it is achieved in Java. Write a program to


demonstrate the concept of polymorphism by creating a class hierarchy of shapes where
each shape has a method to calculate its area. Override this method in different
subclasses to provide their specific area calculation implementations.

Polymorphism:

 Polymorphism in Java allows methods to do different things based on the object it is


acting upon. It is achieved via method overriding and method overloading.

Java Program Example:

java
Copy code
class Shape {
public double calculateArea() {
return 0;
}
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


[Link] = radius;
}

@Override
public double calculateArea() {
return [Link] * radius * radius;
}
}

class Rectangle extends Shape {


private double length, width;

public Rectangle(double length, double width) {


[Link] = length;
[Link] = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

public class PolymorphismExample {


public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);

[Link]("Area of Circle: " + [Link]());


[Link]("Area of Rectangle: " +
[Link]());
}
}

Common questions

Powered by AI

Session tracking is the method used to maintain state across multiple requests from the same user session. Techniques for session tracking include cookies, URL rewriting, hidden form fields, and HttpSession. One common technique is the HttpSession, where the server maintains a session ID for each client, storing and retrieving session data across various HTTP requests.

Directive tags in JSP include Page, Include, and Taglib. These are used to define page-dependent attributes, include files during the translation phase, and declare tag libraries, respectively. In a JSP page, these directives configure settings and establish dependencies during the compilation of JSP to a servlet, affecting its behavior and performance.

The MouseListener interface in Java is used to handle mouse events like clicks, presses, releases, enters, and exits. In a login form, it can be implemented to give feedback to the user when buttons are clicked, such as validating input fields on the submit button or clearing input fields on the reset button, enhancing interactivity.

Polymorphism in Java allows methods to perform different tasks based on the object they act upon, achieved through method overriding and overloading. It can be illustrated with a class hierarchy of shapes like Circle and Rectangle, where each shape overrides a method to calculate its area, demonstrating polymorphism by executing the appropriate implementation based on the instance type.

ServletConfig provides servlet-specific configuration for initialization parameters particular to one servlet instance. In contrast, ServletContext offers a broader context within the web application, used for global initialization parameters, resources, and communication between components. ServletConfig is accessed once per servlet, while ServletContext is accessible application-wide across all servlets.

TCP (Transmission Control Protocol) is connection-oriented, reliable, and ensures data is received in order, but it comes with more overhead. In contrast, UDP (User Datagram Protocol) is connectionless, not reliable, does not guarantee message order, and has less overhead. TCP requires establishing a connection before data is transferred, while UDP does not, making it faster but less reliable.

PreparedStatement is utilized in JDBC for executing SQL queries with parameters, offering improved security and performance over simple queries by preventing SQL injection. CallableStatement is used for calling stored procedures in a database, useful for executing complex transactions. Both enhance interaction by abstracting SQL syntax complexities and boosting performance through precompiled queries.

Java thread synchronization prevents concurrent thread access to shared resources, avoiding inconsistent results. This is achieved using synchronized methods or blocks, ensuring only one thread can execute the critical section of code at a time. In ticket booking systems, it prevents overselling by allowing one thread at a time to update the ticket count safely.

A daemon thread in Java is a low-priority thread running in the background to perform tasks such as garbage collection. It can be demonstrated through thread operations like getPriority(), isAlive(), setPriority(), getName(), and yield(). These methods can be used to manage thread priorities, monitor thread state, and allow threads to wait for others, showcasing typical daemon behavior.

The Swing hierarchy is structured starting from the java.lang.Object class, extending through java.awt.Component and java.awt.Container, followed by javax.swing.JComponent. Key classes in this hierarchy include JButton, JLabel, JTable, JList, and JSlider, which are all subclasses of JComponent. This structure provides the foundation for creating graphical user interfaces in Java.

You might also like