0% found this document useful (0 votes)
19 views

Ayush Java

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)
19 views

Ayush Java

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
You are on page 1/ 14

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
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 Program Example:

java
Copy code
import javax.swing.*;

public class SwingExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(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);

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 (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 = 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:

 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="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 Program Example:

java
Copy code
class MyThread extends Thread {
public void run() {
System.out.println("Running thread: " + getName());
}
}

public class ThreadExample {


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

System.out.println("Thread Name: " + t1.getName());


System.out.println("Thread Priority: " + t1.getPriority());
System.out.println("Is Thread Alive: " + t1.isAlive());

t1.start();

System.out.println("Is Thread Alive after start: " + t1.isAlive());

Thread.yield();

System.out.println("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 java.util.ArrayList;
import java.util.Collections;

public class ArrayListExample {


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

System.out.println("Original list: " + list);

list.set(1, "New Element");


System.out.println("After replacement: " + list);

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 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) {


this.counter = counter;
}

public void run() {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}

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);

t1.start();
t2.start();

t1.join();
t2.join();

System.out.println("Final count: " + counter.getCount());


}
}

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 = 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).

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) {
System.out.println(name + " booked " + numberOfTickets + "
tickets.");
tickets -= numberOfTickets;
} else {
System.out.println("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) {


this.booking = booking;
this.name = name;
this.tickets = tickets;
}

public void run() {


booking.bookTicket(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);

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 Program Example:

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

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();

submitButton.addMouseListener(this);
resetButton.addMouseListener(this);

setLayout(new java.awt.GridLayout(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 (e.getSource() == submitButton) {
if (userIDField.getText().isEmpty() ||
passwordField.getPassword().length == 0) {
messageLabel.setText("Please fill in all fields.");
} else {
messageLabel.setText("Welcome " + userIDField.getText());
}
} else if (e.getSource() == resetButton) {
userIDField.setText("");
passwordField.setText("");
messageLabel.setText("");
}
}

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 java.io.*;
import java.net.*;

public class Server {


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

while (true) {
Socket socket = serverSocket.accept();
new ClientHandler(socket).start();
}
}
}

class ClientHandler extends Thread {


private Socket socket;

public ClientHandler(Socket socket) {


this.socket = socket;
}

public void run() {


try {
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true);

String message = in.readLine();


int length = message.length();
out.println("Message length: " + length);

socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java Client Program:


java
Copy code
import java.io.*;
import java.net.*;

public class Client {


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

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:

 PreparedStatement: Used for executing SQL queries with parameters.


 CallableStatement: Used for executing stored procedures.

JDBC Program Example:

java
Copy code
import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Please provide empid as argument");
return;
}
int empid = Integer.parseInt(args[0]);

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


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

try (Connection con = DriverManager.getConnection(url, user,


password)) {
String query = "SELECT name FROM employees WHERE salary =
(SELECT MAX(salary) FROM employees)";
PreparedStatement pst = con.prepareStatement(query);
ResultSet rs = pst.executeQuery();

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 Program Example:

java
Copy code
import java.util.PriorityQueue;

public class PriorityQueueExample {


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

pq1.add(10);
pq1.add(20);
pq1.add(30);
pq2.add(40);
pq2.add(50);

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


pq1.addAll(pq2);
System.out.println("After adding pq2 to pq1: " + pq1);

// (ii) Remove all elements


pq1.clear();
System.out.println("After clearing pq1: " + pq1);

// Adding elements back to pq1 for further operations


pq1.add(10);
pq1.add(20);
pq1.add(30);

// (iii) Retrieve the first element


System.out.println("First element: " + pq1.peek());

// (iv) Compare two priority queues


System.out.println("pq1 equals pq2: " + pq1.equals(pq2));

// (v) Count the number of elements


System.out.println("Number of elements in pq1: " + pq1.size());
}
}
Q.5

(a) Write short notes on the following:

(i) Layout Managers (ii) Runnable interface (iii) ActionListener (iv) Thread.sleep() 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.

Thread.sleep() 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 java.util.ArrayList;

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) {
grades.add(grade);
} else {
System.out.println("Invalid grade: " + grade);
}
}

public ArrayList<Integer> getGrades() {


return grades;
}
}

public class EncapsulationExample {


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

student.addGrade(85);
student.addGrade(95);
student.addGrade(105); // Invalid grade

System.out.println("Student ID: " + student.getStudentId());


System.out.println("Student Name: " + student.getStudentName());
System.out.println("Grades: " + student.getGrades());
}
}

(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) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

class Rectangle extends Shape {


private double length, width;

public Rectangle(double length, double width) {


this.length = length;
this.width = 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);

System.out.println("Area of Circle: " + circle.calculateArea());


System.out.println("Area of Rectangle: " +
rectangle.calculateArea());
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy