Ayush Java
Ayush Java
(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
css
Copy code
java.lang.Object
|
+--java.awt.Component
|
+--java.awt.Container
|
+--javax.swing.JComponent
|
+--javax.swing.AbstractButton
| |
| +--javax.swing.JButton
|
+--javax.swing.JLabel
|
+--javax.swing.JTable
|
+--javax.swing.JList
|
+--javax.swing.JSlider
java
Copy code
import javax.swing.*;
panel.add(button);
panel.add(label);
panel.add(new JScrollPane(table));
panel.add(new JScrollPane(list));
panel.add(slider);
frame.add(panel);
frame.setVisible(true);
}
}
(b) Differences between a TCP socket and a UDP socket? How are they created in Java?
TCP vs UDP:
TCP Socket:
java
Copy code
// Server side
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
// 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:
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" 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 = request.getSession();
String username = (String) session.getAttribute("username");
if (username == null) {
session.setAttribute("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
Copy code
class MyThread extends Thread {
public void run() {
System.out.println("Running thread: " + getName());
}
}
t1.start();
Thread.yield();
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:
(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
Copy code
import java.util.ArrayList;
import java.util.Collections;
Collections.reverse(list);
System.out.println("After reversing: " + list);
}
}
(d) Write a Java program to create and start multiple threads that increment a shared
counter variable concurrently.
java
Copy code
class Counter {
private int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
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
Copy code
<%@ page isErrorPage="false" %>
<%
try {
String str = null;
int length = str.length();
} catch (NullPointerException e) {
response.sendRedirect("error.jsp");
}
%>
error.jsp:
jsp
Copy code
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h2>An error occurred: <%= exception.getMessage() %></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).
Occurs when multiple threads try to access a shared resource simultaneously leading
to inconsistent results.
t1.start();
t2.start();
}
}
(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
Copy code
import javax.swing.*;
import java.awt.event.*;
public LoginForm() {
userIDField = new JTextField(20);
passwordField = new JPasswordField(20);
submitButton = new JButton("Submit");
resetButton = new JButton("Reset");
messageLabel = new JLabel();
submitButton.addMouseListener(this);
resetButton.addMouseListener(this);
setTitle("Login Form");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
(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
Copy code
import java.io.*;
import java.net.*;
while (true) {
Socket socket = serverSocket.accept();
new ClientHandler(socket).start();
}
}
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
out.println("Hello Server");
String response = in.readLine();
System.out.println("Server response: " + response);
socket.close();
}
}
(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:
java
Copy code
import java.sql.*;
if (rs.next()) {
System.out.println("Employee with highest salary: " +
rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
(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
Copy code
import java.util.PriorityQueue;
pq1.add(10);
pq1.add(20);
pq1.add(30);
pq2.add(40);
pq2.add(50);
(i) Layout Managers (ii) Runnable interface (iii) ActionListener (iv) Thread.sleep() method
Layout Managers:
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.
Thread.sleep() Method:
(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:
java
Copy code
import java.util.ArrayList;
class Student {
private int student_id;
private String student_name;
private ArrayList<Integer> grades = new ArrayList<>();
student.addGrade(85);
student.addGrade(95);
student.addGrade(105); // Invalid grade
Polymorphism:
java
Copy code
class Shape {
public double calculateArea() {
return 0;
}
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
@Override
public double calculateArea() {
return length * width;
}
}