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

Java

The document contains multiple Java programming tasks, including multithreading to display alphabets, a GUI for employee details, sorting names using HashSet, HTTP request handling with servlets, displaying patient details with JSP, and managing collections like LinkedList and HashMap. Each task includes code snippets demonstrating the implementation of specific functionalities such as database interactions, GUI components, and data structures. Overall, the document serves as a collection of programming exercises focusing on Java's core concepts and libraries.

Uploaded by

swapnilruikar45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java

The document contains multiple Java programming tasks, including multithreading to display alphabets, a GUI for employee details, sorting names using HashSet, HTTP request handling with servlets, displaying patient details with JSP, and managing collections like LinkedList and HashMap. Each task includes code snippets demonstrating the implementation of specific functionalities such as database interactions, GUI components, and data structures. Overall, the document serves as a collection of programming exercises focusing on Java's core concepts and libraries.

Uploaded by

swapnilruikar45
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

Slip 1

Q1 Write a Java program using Multithreading to


display all the alphabets between ‘A’ to
‘Z’ after every 2 seconds
public class AlphabetDisplay extends Thread {
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.println(c);
try {
Thread.sleep(2000); // Pause for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {


AlphabetDisplay thread = new AlphabetDisplay();
thread.start();
}
}

---

2 Write a Java program to accept the details of


Employee (Eno, EName, Designation,Salary) from a user and
store it into the database
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class EmployeeForm extends JFrame {


private JTextField txtEno, txtEname, txtDesignation, txtSalary;
private JButton btnSave;

public EmployeeForm() {
setTitle("Employee Form");
setSize(400, 300);
setLayout(new GridLayout(5, 2));

add(new JLabel("Employee No:"));


txtEno = new JTextField();
add(txtEno);

add(new JLabel("Employee Name:"));


txtEname = new JTextField();
add(txtEname);

add(new JLabel("Designation:"));
txtDesignation = new JTextField();
add(txtDesignation);

add(new JLabel("Salary:"));
txtSalary = new JTextField();
add(txtSalary);
btnSave = new JButton("Save");
add(btnSave);

btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveEmployee();
}
});

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

private void saveEmployee() {


String eno = txtEno.getText();
String ename = txtEname.getText();
String designation = txtDesignation.getText();
String salary = txtSalary.getText();

try {
Connection conn =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/your_databas
e", "your_username", "your_password");
String sql = "INSERT INTO employee (eno, ename, designation, salary)
VALUES (?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, Integer.parseInt(eno));
stmt.setString(2, ename);
stmt.setString(3, designation);
stmt.setDouble(4, Double.parseDouble(salary));

stmt.executeUpdate();
stmt.close();
conn.close();

JOptionPane.showMessageDialog(this, "Employee Saved Successfully!");


} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error saving employee.");
}
}

public static void main(String[] args) {


new EmployeeForm();
}
}
Slip 2
Q1 Write a java program to read ‘N’ names of your
friends, store it into HashSet and
display them in ascending order.
import java.util.*;
public class SortNames {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
HashSet<String> namesSet = new HashSet<>();

System.out.print("Enter the number of friends: ");


int n = scanner.nextInt();
scanner.nextLine(); // Consume newline

for (int i = 0; i < n; i++) {


System.out.print("Enter name " + (i + 1) + ": ");
namesSet.add(scanner.nextLine());
}

// Convert HashSet to TreeSet to sort names


TreeSet<String> sortedNames = new TreeSet<>(namesSet);

System.out.println("\nNames in Ascending Order:");


for (String name : sortedNames) {
System.out.println(name);
}
scanner.close();
}
}

2. Servlet to Display HTTP Request and Server Information


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@WebServlet("/InfoServlet")
public class InfoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Client Information
String clientIP = request.getRemoteAddr();
String userAgent = request.getHeader("User-Agent");
// Server Information
String serverOS = System.getProperty("os.name");
String serverName = request.getServerName();
int serverPort = request.getServerPort();

out.println("<html><body>");
out.println("<h2>Client Information</h2>");
out.println("IP Address: " + clientIP + "<br>");
out.println("Browser: " + userAgent + "<br>");

out.println("<h2>Server Information</h2>");
out.println("Operating System: " + serverOS + "<br>");
out.println("Server Name: " + serverName + "<br>");
out.println("Server Port: " + serverPort + "<br>");

// Display all loaded servlets


out.println("<h2>Loaded Servlets</h2>");
Enumeration<String> servletNames =
getServletContext().getServletNames();
while (servletNames.hasMoreElements()) {
out.println(servletNames.nextElement() + "<br>");
}

out.println("</body></html>");
out.close();
}
}
Slip 3
Q1. Write a JSP program to display the details of Patient (PNo, PName, Address,
age, disease) in tabular form on browser*/
%@ page import="java.sql.*" %>
<html>
<head>
<title>Patient Details</title>
<style>
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid black; padding: 10px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<h2>Patient Details</h2>
<table>
<tr>
<th>PNo</th>
<th>PName</th>
<th>Address</th>
<th>Age</th>
<th>Disease</th>
</tr>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital", "root",
"password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM patient");

while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("PNo") + "</td>");
out.println("<td>" + rs.getString("PName") + "</td>");
out.println("<td>" + rs.getString("Address") + "</td>");
out.println("<td>" + rs.getInt("Age") + "</td>");
out.println("<td>" + rs.getString("Disease") + "</td>");
out.println("</tr>");
}
con.close();
} catch (Exception e) {
out.println("Error: " + e.getMessage());
}
%>
</table>
</body>
</html>
Q2. Write a Java program to create LinkedList of String objects and perform the
following: i. Add element at the end of the list ii. Delete first element of the list
iii. Display the contents of list in reverse order
import java.util.LinkedList;
import java.util.Iterator;

public class LinkedListDemo {


public static void main(String[] args) {
// Creating a LinkedList of Strings
LinkedList<String> list = new LinkedList<>();

// Adding elements at the end of the list


list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.add("Date");

// Displaying the original list


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

// Deleting the first element


list.removeFirst();
System.out.println("After deleting first element: " + list);

// Displaying the list in reverse order


System.out.print("List in Reverse Order: ");
Iterator<String> itr = list.descendingIterator();
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}
Slip 4
1. Java Program using Runnable Interface to Blink Text on a Frame
import javax.swing.*;
import java.awt.*;

class BlinkingText extends JFrame implements Runnable {


JLabel label;
boolean visible = true;

public BlinkingText() {
setTitle("Blinking Text");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

label = new JLabel("Blinking Text");


label.setFont(new Font("Arial", Font.BOLD, 20));
add(label);

Thread thread = new Thread(this);


thread.start();

setVisible(true);
}
public void run() {
try {
while (true) {
visible = !visible;
label.setVisible(visible);
Thread.sleep(500); // Blinking interval
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


new BlinkingText();
}
}
Q2. Write a Java program to store city names and their STD codes using an
appropriate collection and perform following operations: i. Add a new city and
its code (No duplicates) ii. Remove a city from the collection iii. Search for a city
name and display the code
public class slip4_2
{
public static void main(String[] args)
{
Map cityMap = new HashMap<>();
Scanner sc = new Scanner(System.in);
int ch;
String code, city;
do {
System.out.println("Menu");
System.out.println("1. Add City and std code.(no duplicates)");
System.out.println("2. Remove City.");
System.out.println("3. Search city name dsiplay std code");
System.out.println("4. Exit");
System.out.println("------------------------------");
System.out.println("Enter your choice:");
ch = sc.nextInt();
sc.nextLine();
System.out.println();
switch(ch)
{
case 1: System.out.println("Enter std code.");
code = sc.nextLine();
System.out.println("Enter City.");
city = sc.nextLine();
cityMap.put(code, city);
break;
case 2: System.out.println("Enter std code.");
code = sc.nextLine();
cityMap.remove(code);
break;
case 3: System.out.println("Enter city:");
city = sc.nextLine();
code = null;
for(Map.Entry map : cityMap.entrySet())
{
if(map.getValue().equals(city))
code = map.getKey();
}
if(code != null)
System.out.println("Code is " + code);
Else
System.out.println("Not found.");
break;
default: System.out.println("Invalid choice.");
}
System.out.println("-------------------------------");
}
while(ch != 4);
}
}
Slip 5
Q1. Write a Java Program to create the hash table that will maintain the mobile
number and student name. Display the details of student using Enumeration
interface */
import java.util.Enumeration;
import java.util.Hashtable;

public class StudentHashTable {


public static void main(String[] args) {
// Creating a Hashtable to store student details
Hashtable<String, String> students = new Hashtable<>();

// Adding students (Mobile Number -> Student Name)


students.put("9876543210", "John Doe");
students.put("8765432109", "Alice Smith");
students.put("7654321098", "Bob Johnson");

// Displaying student details using Enumeration


Enumeration<String> mobileNumbers = students.keys();

System.out.println("Student Details:");
while (mobileNumbers.hasMoreElements()) {
String mobile = mobileNumbers.nextElement();
System.out.println("Mobile: " + mobile + ", Name: " +
students.get(mobile));
}
}
}
2. Create a JSP page for an online multiple choice test. The questions are
randomly selected from a database and displayed on the screen. The choices
are displayed using radio buttons. When the user clicks on next, the next
question is displayed. When the user clicks on submit, display the total score
on the screen.
<%@ page import="java.sql.*, java.util.Random" %>
<%
// Database Connection
String url = "jdbc:postgresql://localhost:5432/quizdb";
String user = "postgres";
String pass = "yourpassword";

Connection conn = null;


PreparedStatement pstmt = null;
ResultSet rs = null;

// Get Current Score from Session


Integer score = (Integer) session.getAttribute("score");
if (score == null) {
score = 0;
}

// Handle Answer Submission


String answer = request.getParameter("answer");
String correct = request.getParameter("correct");

if (answer != null && correct != null) {


if (answer.equals(correct)) {
score++;
}
}

session.setAttribute("score", score);

try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url, user, pass);

// Select a random question


pstmt = conn.prepareStatement("SELECT * FROM questions ORDER BY
RANDOM() LIMIT 1");
rs = pstmt.executeQuery();

if (rs.next()) {
int id = rs.getInt("id");
String question = rs.getString("question");
String option1 = rs.getString("option1");
String option2 = rs.getString("option2");
String option3 = rs.getString("option3");
String option4 = rs.getString("option4");
int correctOption = rs.getInt("correct_option");
%>
<!DOCTYPE html>
<html>
<head>
<title>Online Quiz</title>
</head>
<body>
<h2>Question:</h2>
<p><%= question %></p>
<form method="post" action="quiz.jsp">
<input type="radio" name="answer" value="1"> <%= option1 %><br>
<input type="radio" name="answer" value="2"> <%= option2 %><br>
<input type="radio" name="answer" value="3"> <%= option3 %><br>
<input type="radio" name="answer" value="4"> <%= option4 %><br>
<input type="hidden" name="correct" value="<%= correctOption %>">
<input type="submit" name="next" value="Next">
<input type="submit" name="submit" value="Submit">
</form>

<%
} else {
out.println("<p>No questions available.</p>");
}
} catch (Exception e) {
out.println("Error: " + e.getMessage());
} finally {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}
%>

<% if (request.getParameter("submit") != null) { %>


<h3>Your Final Score: <%= score %></h3>
<a href="quiz.jsp">Restart Quiz</a>
<% } %>
</body>
</html>
slip 6
Q1 Write a Java program to accept ‘n’ integers from the user and store them in
a Collection. Display them in the sorted order. The collection should not accept
duplicate elements. (Use a suitable collection). Search for a particular element
using predefined search method in the Collection framework
import java.util.*;

public class SortedCollectionSearch {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
TreeSet<Integer> numbers = new TreeSet<>();

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();

System.out.println("Enter " + n + " integers:");


for (int i = 0; i < n; i++) {
numbers.add(scanner.nextInt()); // TreeSet ensures sorting &
uniqueness
}

System.out.println("Sorted Elements: " + numbers);

// Searching for a particular element


System.out.print("Enter the number to search: ");
int searchNum = scanner.nextInt();
if (numbers.contains(searchNum)) {
System.out.println(searchNum + " is present in the collection.");
} else {
System.out.println(searchNum + " is NOT present in the collection.");
}
scanner.close();
}
}
2. Java Program to Simulate a Traffic Signal Using Threads
class TrafficSignal extends Thread {
public void run() {
String[] signals = {"RED", "YELLOW", "GREEN"};
int[] durations = {5000, 2000, 5000}; // Red - 5s, Yellow - 2s, Green - 5s

while (true) {
for (int i = 0; i < signals.length; i++) {
System.out.println("Signal: " + signals[i]);
try {
Thread.sleep(durations[i]); // Delay based on signal
} catch (InterruptedException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
public static void main(String[] args) {
TrafficSignal signal = new TrafficSignal();
signal.start(); // Start the traffic signal simulation
}
}
Slip 7
1. Java Program for Multi-Threaded Application with Three Threads
import java.util.Random;

class NumberGenerator extends Thread {


static int num;

public void run() {


Random rand = new Random();
while (true) {
num = rand.nextInt(100); // Generate a random number (0-99)
System.out.println("Generated Number: " + num);
try {
Thread.sleep(1000); // Wait for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
class SquareCalculator extends Thread {
public void run() {
while (true) {
if (NumberGenerator.num % 2 == 0) {
System.out.println("Square of " + NumberGenerator.num + " = " +
(NumberGenerator.num * NumberGenerator.num));
}
try {
Thread.sleep(1000); // Wait for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

class CubeCalculator extends Thread {


public void run() {
while (true) {
if (NumberGenerator.num % 2 != 0) {
System.out.println("Cube of " + NumberGenerator.num + " = " +
(NumberGenerator.num * NumberGenerator.num * NumberGenerator.num));
}
try {
Thread.sleep(1000); // Wait for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

public class MultiThreadNumberProcessing {


public static void main(String[] args) {
NumberGenerator generator = new NumberGenerator();
SquareCalculator squareThread = new SquareCalculator();
CubeCalculator cubeThread = new CubeCalculator();

generator.start();
squareThread.start();
cubeThread.start();
}
}
2. Java Program for Product Table in PostgreSQL
i) Insert at Least Five Records
(ii) Java Code to Insert and Display Records
CREATE TABLE Product (
Pid SERIAL PRIMARY KEY,
Pname VARCHAR(50),
Price DECIMAL(10,2)
);
INSERT INTO Product (Pname, Price) VALUES
('Laptop', 75000.00),
('Mobile', 25000.00),
('Tablet', 30000.00),
('Smartwatch', 15000.00),
('Headphones', 5000.00);
import java.sql.*;

public class ProductDatabase {


public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/your_database";
String user = "your_username";
String password = "your_password";

try {
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();

// Inserting records
String insertQuery = "INSERT INTO Product (Pname, Price) VALUES " +
"('Laptop', 75000.00), ('Mobile', 25000.00), " +
"('Tablet', 30000.00), ('Smartwatch', 15000.00),
('Headphones', 5000.00)";
stmt.executeUpdate(insertQuery);
System.out.println("Records inserted successfully.");

// Retrieving records
String selectQuery = "SELECT * FROM Product";
ResultSet rs = stmt.executeQuery(selectQuery);
System.out.println("Product Details:");
while (rs.next()) {
System.out.println("ID: " + rs.getInt("Pid") + ", Name: " +
rs.getString("Pname") + ", Price: " + rs.getDouble("Price"));
}

// Close resources
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Slip 8
1. Java Program with Three Threads for Printing Text
class PrintTask implements Runnable {
private String message;
private int count;

public PrintTask(String message, int count) {


this.message = message;
this.count = count;
}
public void run() {
for (int i = 0; i < count; i++) {
System.out.println(message);
try {
Thread.sleep(100); // Adding a small delay for better readability
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

public class MultiThreadPrinting {


public static void main(String[] args) {
Thread t1 = new Thread(new PrintTask("COVID19", 10));
Thread t2 = new Thread(new PrintTask("LOCKDOWN2020", 20));
Thread t3 = new Thread(new PrintTask("VACCINATED2021", 30));

t1.start();
t2.start();
t3.start();
}
}
2. JSP Page to Check If a Number is Prime
The user enters a number.
The page checks if it is prime.
The result is displayed in red color.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Prime Number Checker</title>
</head>
<body>
<form method="post">
<label>Enter a Number:</label>
<input type="text" name="number">
<input type="submit" value="Check">
</form>

<%
String numStr = request.getParameter("number");
if (numStr != null) {
try {
int num = Integer.parseInt(numStr);
boolean isPrime = true;

if (num < 2) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
%>
<h3 style="color: red;">
<%= num %> is <%= isPrime ? "a Prime Number" : "Not a Prime Number"
%>
</h3>
<%
} catch (NumberFormatException e) {
%>
<h3 style="color: red;">Invalid input! Please enter a valid number.</h3>
<%
}
}
%>
</body>
</html>
Slip 9
Q1 write a java program TO CREATE a thread for moving a ball inside a panel
vertically
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class BallPanel extends JPanel implements Runnable {


private int y = 50; // Initial position
private boolean movingDown = true;

public void run() {


while (true) {
if (movingDown) {
y += 5;
if (y >= getHeight() - 50) movingDown = false;
} else {
y -= 5;
if (y <= 0) movingDown = true;
}
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

protected void paintComponent(Graphics g) {


super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(100, y, 50, 50);
}
}

public class BallAnimation extends JFrame {


private BallPanel panel = new BallPanel();

public BallAnimation() {
setTitle("Ball Animation");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

JButton startButton = new JButton("Start");


startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread ballThread = new Thread(panel);
ballThread.start();
}
});

add(panel, BorderLayout.CENTER);
add(startButton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new BallAnimation().setVisible(true));
}
}
Q2 write a java program using spring to display the message
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class MessageController {

@GetMapping("/message")
public String displayMessage() {
return "If you can't explain it simply, you don't understand it well enough";
}
}
Slip 10
Q1 spring
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
@RestController
@RequestMapping("/api")
public class DateController {

@GetMapping("/date")
public String getCurrentDate() {
return "Current Date: " + LocalDate.now();
}
}
Q2. Write a Java program to display first record from student table (RNo,
SName, Per) onto the TextFields by clicking on button. (Assume Student table is
already created)
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class StudentRecord extends JFrame {


private JTextField rnoField, nameField, perField;
private JButton fetchButton;

public StudentRecord() {
setTitle("Student Record");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
add(new JLabel("Roll No:"));
rnoField = new JTextField();
add(rnoField);

add(new JLabel("Name:"));
nameField = new JTextField();
add(nameField);

add(new JLabel("Percentage:"));
perField = new JTextField();
add(perField);

fetchButton = new JButton("Fetch First Record");


add(fetchButton);

fetchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fetchFirstRecord();
}
});

setVisible(true);
}

private void fetchFirstRecord() {


try {
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database",
"root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Student LIMIT 1");

if (rs.next()) {
rnoField.setText(String.valueOf(rs.getInt("RNo")));
nameField.setText(rs.getString("SName"));
perField.setText(String.valueOf(rs.getFloat("Per")));
}

con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

public static void main(String[] args) {


new StudentRecord();
}
}
Slip 11
1.
Design an HTML page which passes customer number to a search servlet. The
servletsearches for the customer number in a database (customer table) and
returns customerdetails if found the number otherwise display error message.
<!DOCTYPE html>
<html>
<head>
<title>Customer Search</title>
</head>
<body>
<h2>Search Customer</h2>
<form action="SearchServlet" method="post">
Customer Number: <input type="text" name="customerNumber"
required>
<input type="submit" value="Search">
</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String customerNumber = request.getParameter("customerNumber");

try {
Class.forName("org.postgresql.Driver"); // Load PostgreSQL Driver
Connection con =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/yourDatabase
", "username", "password");

String query = "SELECT * FROM customer WHERE customer_number =


?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, customerNumber);
ResultSet rs = ps.executeQuery();

if (rs.next()) {
out.println("<h2>Customer Details</h2>");
out.println("Customer Number: " + rs.getString("customer_number")
+ "<br>");
out.println("Name: " + rs.getString("name") + "<br>");
out.println("Contact: " + rs.getString("contact") + "<br>");
out.println("Address: " + rs.getString("address") + "<br>");
} else {
out.println("<h2 style='color:red;'>Customer not found!</h2>");
}

con.close();
} catch (Exception e) {
out.println("<h2>Error: " + e.getMessage() + "</h2>");
}
}
}
2.
Write a Java program to display information about all columns in the DONAR
tableusing ResultSetMetaData.
import java.sql.*;

public class TableMetadata {


public static void main(String[] args) {
try {
// Load PostgreSQL Driver
Class.forName("org.postgresql.Driver");
Connection con =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/yourDatabase
", "username", "password");

// Query to fetch table metadata


String query = "SELECT * FROM DONAR";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();

int columnCount = rsmd.getColumnCount();


System.out.println("Columns in DONAR table:");

for (int i = 1; i <= columnCount; i++) {


System.out.println("Column " + i + ": " + rsmd.getColumnName(i) + " ("
+ rsmd.getColumnTypeName(i) + ")");
}

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Slip 12
1.Write a JSP program to check whether given number is Perfect or not. (Use
Includedirective)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Perfect Number Checker</title>
</head>
<body>
<h2>Check Perfect Number</h2>
<form method="post">
Enter a Number: <input type="number" name="number" required>
<input type="submit" value="Check">
</form>

<%
String numStr = request.getParameter("number");
if (numStr != null) {
int number = Integer.parseInt(numStr);
int sum = 0;

for (int i = 1; i < number; i++) {


if (number % i == 0) {
sum += i;
}
}

if (sum == number) {
out.println("<h3 style='color:green;'>" + number + " is a Perfect
Number</h3>");
} else {
out.println("<h3 style='color:red;'>" + number + " is NOT a Perfect
Number</h3>");
}
}
%>
</body>
</html>

2.Write a Java Program to create a PROJECT table withfield’s project_id,


Project_name,Project_description, Project_Status. Insert values in the table.
Display all the details
ofthe PROJECT table in a tabular format on the screen.(using swing).
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class ProjectTable {


private static final String URL =
"jdbc:postgresql://localhost:5432/yourDatabase";
private static final String USER = "username";
private static final String PASSWORD = "password";

public static void main(String[] args) {


SwingUtilities.invokeLater(ProjectTable::createAndShowGUI);
}

private static void createAndShowGUI() {


JFrame frame = new JFrame("Project Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);

DefaultTableModel model = new DefaultTableModel();


JTable table = new JTable(model);
model.addColumn("ID");
model.addColumn("Project Name");
model.addColumn("Project Description");
model.addColumn("Project Status");

try {
Connection con = DriverManager.getConnection(URL, USER,
PASSWORD);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM PROJECT");

while (rs.next()) {
model.addRow(new Object[]{
rs.getInt("id"),
rs.getString("project_name"),
rs.getString("project_description"),
rs.getString("project_status")
});
}

con.close();
} catch (Exception e) {
e.printStackTrace();
}

JScrollPane scrollPane = new JScrollPane(table);


frame.add(scrollPane, BorderLayout.CENTER);
frame.setVisible(true);
}
}
Slip 13
1.Write a Java program to display information about the database and list all
the tables inthe database. (Use DatabaseMetaData).
import java.sql.*;

public class DatabaseInfo {


public static void main(String[] args) {
String url = "jdbc:postgresql://localhost:5432/your_database"; // Change
as per your DB
String user = "your_username";
String password = "your_password";

try (Connection conn = DriverManager.getConnection(url, user, password))


{
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("Database Product Name: " +
metaData.getDatabaseProductName());
System.out.println("Database Product Version: " +
metaData.getDatabaseProductVersion());
System.out.println("Driver Name: " + metaData.getDriverName());
System.out.println("Driver Version: " + metaData.getDriverVersion());

System.out.println("\nList of Tables:");
ResultSet tables = metaData.getTables(null, null, "%", new
String[]{"TABLE"});
while (tables.next()) {
System.out.println(tables.getString("TABLE_NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

2.Write a Java program to show lifecycle (creation, sleep, and dead) of a thread.
Programshould print randomly the name of thread and value of sleep time. The
name of thethread should be hard coded through constructor. The sleep time
of a thread will be arandom integer in the range 0 to 4999.
import java.util.Random;

class MyThread extends Thread {


private int sleepTime;
public MyThread(String name) {
super(name);
Random rand = new Random();
this.sleepTime = rand.nextInt(5000); // Random sleep time (0-4999 ms)
}

@Override
public void run() {
System.out.println(getName() + " is created and running.");
try {
System.out.println(getName() + " is sleeping for " + sleepTime + " ms.");
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
System.out.println(getName() + " was interrupted.");
}
System.out.println(getName() + " is dead.");
}
}

public class ThreadLifecycle {


public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
MyThread t3 = new MyThread("Thread-3");
t1.start();
t2.start();
t3.start();
}
}

Slip 14
1. Write a Java program for a simple search engine. Accept a string to be
searched. Searchthe string in all text files in the current folder. Use a separate
thread for each file. Theresult should display the filename and line
number where the string is found
import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class SearchTask implements Runnable {


private File file;
private String searchString;

public SearchTask(File file, String searchString) {


this.file = file;
this.searchString = searchString;
}

@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
int lineNumber = 0;
while ((line = reader.readLine()) != null) {
lineNumber++;
if (line.contains(searchString)) {
System.out.println("Found in: " + file.getName() + " at line " +
lineNumber);
}
}
} catch (IOException e) {
System.out.println("Error reading file: " + file.getName());
}
}
}

public class SimpleSearchEngine {


public static void main(String[] args) {
File folder = new File("."); // Current directory
File[] files = folder.listFiles((dir, name) -> name.endsWith(".txt"));

if (files == null || files.length == 0) {


System.out.println("No text files found in the directory.");
return;
}
try (BufferedReader br = new BufferedReader(new
InputStreamReader(System.in))) {
System.out.print("Enter the string to search: ");
String searchString = br.readLine();

ExecutorService executor = Executors.newFixedThreadPool(5); // Thread


pool

for (File file : files) {


executor.execute(new SearchTask(file, searchString));
}

executor.shutdown();
} catch (IOException e) {
System.out.println("Error reading input.");
}
}
}

2. Write a JSP program to calculate sum of first and last digit of a given
number. Displaysum in Red Color with font size 18
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Sum of First and Last Digit</title>
</head>
<body>
<form method="post">
Enter a number: <input type="text" name="number">
<input type="submit" value="Calculate">
</form>

<%
String numStr = request.getParameter("number");
if (numStr != null && numStr.matches("\\d+")) { // Ensuring input is
numeric
int number = Integer.parseInt(numStr);
int firstDigit = Integer.parseInt(Character.toString(numStr.charAt(0)));
int lastDigit = number % 10;
int sum = firstDigit + lastDigit;
%>
<p style="color: red; font-size: 18px;">Sum of first and last digit: <%=
sum %></p>
<%
} else if (numStr != null) {
out.println("<p style='color: red;'>Please enter a valid number.</p>");
}
%>
</body>
</html>

Slip 15
1.Write a java program to display name and priority of a Thread.
class MyThread extends Thread {
public MyThread(String name, int priority) {
super(name);
setPriority(priority);
}

@Override
public void run() {
System.out.println("Thread Name: " + getName());
System.out.println("Thread Priority: " + getPriority());
}
}

public class ThreadInfo {


public static void main(String[] args) {
MyThread t1 = new MyThread("HighPriorityThread",
Thread.MAX_PRIORITY);
MyThread t2 = new MyThread("LowPriorityThread",
Thread.MIN_PRIORITY);

t1.start();
t2.start();
}
}
2.Write a SERVLET program which counts how many times a user has visited a
web page. If user is visiting the page for the first time, display
a welcome message. If theuser is revisiting the page, display the number of
times visited. (Use Cookie)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@WebServlet("/VisitCounterServlet")
public class VisitCounterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

int visitCount = 0;
Cookie[] cookies = request.getCookies();
boolean found = false;

if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("visitCount")) {
visitCount = Integer.parseInt(cookie.getValue());
visitCount++;
cookie.setValue(String.valueOf(visitCount));
response.addCookie(cookie);
found = true;
break;
}
}
}

if (!found) {
visitCount = 1;
Cookie newCookie = new Cookie("visitCount", "1");
newCookie.setMaxAge(60 * 60 * 24 * 365); // 1 year
response.addCookie(newCookie);
out.println("<h2>Welcome! This is your first visit.</h2>");
} else {
out.println("<h2>You have visited this page " + visitCount + "
times.</h2>");
}

out.close();
}
}

Slip 16
1.Write a java program to create a TreeSet, add some colors (String) and print
out thecontent of TreeSet in ascending order. [15 M]
import java.util.TreeSet;

public class TreeSetExample {


public static void main(String[] args) {
// Creating a TreeSet to store colors
TreeSet<String> colors = new TreeSet<>();

// Adding some colors


colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.add("Yellow");
colors.add("Black");

// Displaying the colors in ascending order


System.out.println("Colors in Ascending Order: " + colors);
}
}
2.Write a Java program to accept the details of Teacher (TNo, TName, Subject).
Insert atleast 5 Records into Teacher Table and display the details of Teacher
who is teaching
“JAVA” Subject. (Use PreparedStatement Interface)
import java.sql.*;
import java.util.Scanner;
public class TeacherDatabase {
public static void main(String[] args) {
// Database connection details (Update these with your actual credentials)
String url = "jdbc:postgresql://localhost:5432/your_database"; // Change
your_database
String user = "your_username"; // Change your_username
String password = "your_password"; // Change your_password

try (Connection conn = DriverManager.getConnection(url, user, password);


Scanner scanner = new Scanner(System.in)) {

// Step 1: Create the Teacher table if it does not exist


String createTableSQL = "CREATE TABLE IF NOT EXISTS Teacher ("
+ "TNo SERIAL PRIMARY KEY, " // Auto-increment primary key
+ "TName VARCHAR(100), "
+ "Subject VARCHAR(50))";

conn.createStatement().executeUpdate(createTableSQL);
System.out.println("Teacher table is ready.\n");

// Step 2: Insert at least 5 teacher records


String insertSQL = "INSERT INTO Teacher (TName, Subject) VALUES (?,
?)";
PreparedStatement pstmt = conn.prepareStatement(insertSQL);

System.out.println("Enter details of 5 teachers:");


for (int i = 1; i <= 5; i++) {
System.out.print("Enter Teacher Name: ");
String name = scanner.nextLine();
System.out.print("Enter Subject: ");
String subject = scanner.nextLine();

pstmt.setString(1, name);
pstmt.setString(2, subject);
pstmt.executeUpdate();
System.out.println("Record inserted successfully!\n");
}

// Step 3: Fetch and display teachers who teach "JAVA"


String selectSQL = "SELECT * FROM Teacher WHERE Subject = ?";
PreparedStatement selectStmt = conn.prepareStatement(selectSQL);
selectStmt.setString(1, "JAVA");

ResultSet rs = selectStmt.executeQuery();

System.out.println("\nTeachers who teach JAVA:");


boolean found = false;
while (rs.next()) {
found = true;
System.out.println("TNo: " + rs.getInt("TNo") +
", TName: " + rs.getString("TName") +
", Subject: " + rs.getString("Subject"));
}
if (!found) {
System.out.println("No teachers found for JAVA.");
}

} catch (SQLException e) {
e.printStackTrace();
}
}
}

Slip 17
1.Write a java program to accept ‘N’ integers from
a user. Store and display integers insorted order having proper collection class.
The collection should not accept duplicateelements.[15 M]
import java.util.Scanner;
import java.util.TreeSet;

public class SortedUniqueIntegers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
TreeSet<Integer> numbers = new TreeSet<>(); // TreeSet maintains sorted
order and prevents duplicates

System.out.print("Enter the number of integers (N): ");


int n = scanner.nextInt();
System.out.println("Enter " + n + " unique integers:");
for (int i = 0; i < n; i++) {
int num = scanner.nextInt();
if (!numbers.add(num)) { // If number is duplicate
System.out.println("Duplicate entry! Enter a unique number.");
i--; // Retry input
}
}

System.out.println("Sorted Unique Integers: " + numbers);


scanner.close();
}
}
2.Write a Multithreading program in java to display the number’s between 1 to
100
continuously in a TextField by clicking on button. (Use Runnable Interface).
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class NumberThread implements Runnable {


private JTextField textField;

public NumberThread(JTextField textField) {


this.textField = textField;
}

@Override
public void run() {
for (int i = 1; i <= 100; i++) {
textField.setText(String.valueOf(i)); // Update TextField with current
number
try {
Thread.sleep(100); // Pause for 100 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class NumberDisplayApp {


public static void main(String[] args) {
// Create JFrame
JFrame frame = new JFrame("Number Display");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Create TextField
JTextField textField = new JTextField(10);
textField.setFont(new Font("Arial", Font.BOLD, 20));
textField.setHorizontalAlignment(JTextField.CENTER);
frame.add(textField);

// Create Button
JButton startButton = new JButton("Start");
frame.add(startButton);

// Button Click Listener


startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Thread thread = new Thread(new NumberThread(textField));
thread.start(); // Start the thread
}
});

frame.setVisible(true);
}
}

Slip 18
1.Write a java program to display name and priority of a Thread. [15 M]
class MyThread extends Thread {
public MyThread(String name, int priority) {
super(name); // Set thread name
setPriority(priority); // Set thread priority
}

@Override
public void run() {
System.out.println("Thread Name: " + getName());
System.out.println("Thread Priority: " + getPriority());
}
}

public class ThreadInfo {


public static void main(String[] args) {
// Creating two threads with different priorities
MyThread t1 = new MyThread("HighPriorityThread",
Thread.MAX_PRIORITY); // Priority 10
MyThread t2 = new MyThread("LowPriorityThread",
Thread.MIN_PRIORITY); // Priority 1

t1.start();
t2.start();
}
}
2.Write a SERVLET program in java to accept details of
student (SeatNo, Stud_Name,Class, Total_Marks). Calculate percentage and gra
de obtained and display details on page.
Html
<!DOCTYPE html>
<html>
<head>
<title>Student Form</title>
</head>
<body>
<h2>Enter Student Details</h2>
<form action="StudentServlet" method="post">
Seat No: <input type="text" name="seatNo" required><br><br>
Name: <input type="text" name="studName" required><br><br>
Class: <input type="text" name="studClass" required><br><br>
Total Marks (out of 500): <input type="number" name="totalMarks"
required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Servlet

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Retrieving form data


String seatNo = request.getParameter("seatNo");
String studName = request.getParameter("studName");
String studClass = request.getParameter("studClass");
int totalMarks = Integer.parseInt(request.getParameter("totalMarks"));

// Calculate percentage
double percentage = (totalMarks / 500.0) * 100;

// Determine grade
String grade;
if (percentage >= 90) grade = "A+";
else if (percentage >= 80) grade = "A";
else if (percentage >= 70) grade = "B";
else if (percentage >= 60) grade = "C";
else if (percentage >= 50) grade = "D";
else grade = "Fail";

// Display output
out.println("<h2>Student Details</h2>");
out.println("<p><strong>Seat No:</strong> " + seatNo + "</p>");
out.println("<p><strong>Name:</strong> " + studName + "</p>");
out.println("<p><strong>Class:</strong> " + studClass + "</p>");
out.println("<p><strong>Total Marks:</strong> " + totalMarks +
"/500</p>");
out.println("<p><strong>Percentage:</strong> " + percentage + "%</p>");
out.println("<p><strong>Grade:</strong> " + grade + "</p>");
}
}

Slip 19
1.Write a java program to accept ‘N’ Integers from
a user store them into
LinkedListCollection and display only negative integers. [15 M]
import java.util.LinkedList;
import java.util.Scanner;

public class NegativeIntegers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
LinkedList<Integer> numbers = new LinkedList<>();

System.out.print("Enter the number of integers (N): ");


int n = scanner.nextInt();

System.out.println("Enter " + n + " integers:");


for (int i = 0; i < n; i++) {
numbers.add(scanner.nextInt());
}

System.out.println("Negative Integers in the List:");


for (int num : numbers) {
if (num < 0) {
System.out.println(num);
}
}

scanner.close();
}
}
2.Write a SERVLET application to accept username and password, search them
intodatabase, if found then display appropriate message on the browser
otherwise displayerror message
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="LoginServlet" method="post">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Get username and password from form


String username = request.getParameter("username");
String password = request.getParameter("password");

// Database connection details (Update these)


String url = "jdbc:postgresql://localhost:5432/your_database";
String user = "your_username";
String pass = "your_password";

try {
// Load PostgreSQL Driver
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);

// Prepare SQL query to check credentials


String sql = "SELECT * FROM users WHERE username = ? AND password
= ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);

ResultSet rs = pstmt.executeQuery();

if (rs.next()) {
out.println("<h2 style='color:green;'>Login Successful! Welcome, " +
username + ".</h2>");
} else {
out.println("<h2 style='color:red;'>Invalid Username or
Password</h2>");
}

// Close resources
rs.close();
pstmt.close();
conn.close();

} catch (Exception e) {
e.printStackTrace();
out.println("<h2 style='color:red;'>Database Connection Error!</h2>");
}
}
}

Slip 20
1.Create a JSP page to accept a number from a user and display it in words:
Example:123– One Two Three. The output should be in red color. [15 M]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Number to Words</title>
</head>
<body>
<h2>Enter a Number</h2>
<form method="post">
<input type="text" name="number" required>
<input type="submit" value="Convert">
</form>

<%
String numStr = request.getParameter("number");

if (numStr != null && numStr.matches("\\d+")) {


String[] words = { "Zero", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine" };
StringBuilder wordOutput = new StringBuilder();

for (char digit : numStr.toCharArray()) {

wordOutput.append(words[Character.getNumericValue(digit)]).append(" ");
}

out.println("<h3 style='color:red;'>Number in Words: " +


wordOutput.toString().trim() + "</h3>");
} else if (numStr != null) {
out.println("<h3 style='color:red;'>Invalid Input! Please enter a valid
number.</h3>");
}
%>
</body>
</html>

2.Write a java program to blink image on the JFrame continuous


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

public class BlinkingImage extends JFrame {


private JLabel imageLabel;
private boolean isVisible = true;

public BlinkingImage() {
// Set up JFrame
setTitle("Blinking Image");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// Load Image
ImageIcon icon = new ImageIcon("image.jpg"); // Change to your image
path
imageLabel = new JLabel(icon);
add(imageLabel);

// Thread for Blinking Effect


Thread blinkThread = new Thread(() -> {
while (true) {
isVisible = !isVisible; // Toggle visibility
imageLabel.setVisible(isVisible);

try {
Thread.sleep(500); // Pause for 500ms
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

blinkThread.start(); // Start the thread

setVisible(true);
}

public static void main(String[] args) {


new BlinkingImage();
}
}

Slip 21
1.Write a java program to accept ‘N’ Subject Names from a user store them into
LinkedList Collection and Display them by using Iterator interface. [15 M]
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;

public class SubjectList {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
LinkedList<String> subjects = new LinkedList<>();

System.out.print("Enter the number of subjects (N): ");


int n = scanner.nextInt();
scanner.nextLine(); // Consume newline

System.out.println("Enter " + n + " subject names:");


for (int i = 0; i < n; i++) {
subjects.add(scanner.nextLine());
}

// Displaying subjects using Iterator


System.out.println("\nSubjects entered:");
Iterator<String> iterator = subjects.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

scanner.close();
}
}

2.Write a java program to solve producer consumer problem in which a


producer produces a value and consumer consume the value before producer g
enerate the nextvalue. (Hint: use thread synchronization)
class SharedResource {
private int data;
private boolean isAvailable = false; // Indicates if data is ready

// Producer method
public synchronized void produce(int value) {
while (isAvailable) {
try {
wait(); // Wait if data is not consumed yet
} catch (InterruptedException e) {
e.printStackTrace();
}
}
data = value;
System.out.println("Produced: " + data);
isAvailable = true;
notify(); // Notify consumer that data is ready
}

// Consumer method
public synchronized void consume() {
while (!isAvailable) {
try {
wait(); // Wait if there is no data to consume
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consumed: " + data);
isAvailable = false;
notify(); // Notify producer to generate new data
}
}

class Producer extends Thread {


private SharedResource resource;

public Producer(SharedResource resource) {


this.resource = resource;
}

public void run() {


for (int i = 1; i <= 5; i++) { // Producing 5 values
resource.produce(i);
try {
Thread.sleep(500); // Simulating production time
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer extends Thread {
private SharedResource resource;

public Consumer(SharedResource resource) {


this.resource = resource;
}

public void run() {


for (int i = 1; i <= 5; i++) { // Consuming 5 values
resource.consume();
try {
Thread.sleep(1000); // Simulating consumption time
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ProducerConsumerDemo {


public static void main(String[] args) {
SharedResource resource = new SharedResource();

Producer producer = new Producer(resource);


Consumer consumer = new Consumer(resource);
producer.start();
consumer.start();
}
}

Slip 22
1.Write a Menu Driven program in Java for the following: Assume Employee
table withattributes (ENo, EName, Salary) is already created. 1. Insert 2. Update
3. Display 4.Exit.
import java.sql.*;
import java.util.Scanner;

public class EmployeeCRUD {


// Database connection details (Update as per your DB)
static final String URL = "jdbc:postgresql://localhost:5432/your_database";
static final String USER = "your_username";
static final String PASSWORD = "your_password";

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

try (Connection conn = DriverManager.getConnection(URL, USER,


PASSWORD)) {
Class.forName("org.postgresql.Driver");

while (true) {
System.out.println("\nEmployee Database Menu:");
System.out.println("1. Insert Employee");
System.out.println("2. Update Employee Salary");
System.out.println("3. Display Employees");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();

switch (choice) {
case 1:
insertEmployee(conn, scanner);
break;
case 2:
updateEmployeeSalary(conn, scanner);
break;
case 3:
displayEmployees(conn);
break;
case 4:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid choice! Try again.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

// Insert Employee
private static void insertEmployee(Connection conn, Scanner scanner)
throws SQLException {
System.out.print("Enter Employee Number: ");
int eno = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Employee Name: ");
String ename = scanner.nextLine();
System.out.print("Enter Employee Salary: ");
double salary = scanner.nextDouble();

String sql = "INSERT INTO Employee (ENo, EName, Salary) VALUES (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, eno);
pstmt.setString(2, ename);
pstmt.setDouble(3, salary);
pstmt.executeUpdate();
System.out.println("Employee inserted successfully!");
}
}

// Update Employee Salary


private static void updateEmployeeSalary(Connection conn, Scanner scanner)
throws SQLException {
System.out.print("Enter Employee Number to update salary: ");
int eno = scanner.nextInt();
System.out.print("Enter New Salary: ");
double newSalary = scanner.nextDouble();

String sql = "UPDATE Employee SET Salary = ? WHERE ENo = ?";


try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setDouble(1, newSalary);
pstmt.setInt(2, eno);
int rowsUpdated = pstmt.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("Salary updated successfully!");
} else {
System.out.println("Employee not found!");
}
}
}

// Display All Employees


private static void displayEmployees(Connection conn) throws SQLException
{
String sql = "SELECT * FROM Employee";
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
System.out.println("\nEmployee Details:");
while (rs.next()) {
System.out.println("ENo: " + rs.getInt("ENo") +
", EName: " + rs.getString("EName") +
", Salary: " + rs.getDouble("Salary"));
}
}
}
}

2.Write a JSP program which accepts UserName in a TextBox and greets the
useraccording to the time on server machine.

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%@ page import="java.util.Calendar" %>
<!DOCTYPE html>
<html>
<head>
<title>Greet User</title>
</head>
<body>
<form method="post">
Enter Your Name: <input type="text" name="username" required>
<input type="submit" value="Greet Me">
</form>
<%
String username = request.getParameter("username");
if (username != null && !username.trim().isEmpty()) {
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
String greeting;

if (hour < 12) {


greeting = "Good Morning";
} else if (hour < 17) {
greeting = "Good Afternoon";
} else if (hour < 20) {
greeting = "Good Evening";
} else {
greeting = "Good Night";
}

out.println("<h2 style='color:blue;'> " + greeting + ", " + username + "!


</h2>");
}
%>
</body>
</html>

.
Slip 23
1.Write a java program to accept a String from a user and display each vowel
from aString after every 3 seconds. [15 M]
import java.util.Scanner;

public class VowelDisplay {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String input = scanner.nextLine();
scanner.close();

// Convert input to lowercase for uniformity


String vowels = "aeiouAEIOU";

System.out.println("\nDisplaying vowels every 3 seconds...");


for (char ch : input.toCharArray()) {
if (vowels.indexOf(ch) != -1) { // Check if character is a vowel
System.out.println(ch);
try {
Thread.sleep(3000); // Pause for 3 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("All vowels displayed!");
}
}
2.Write a java program to accept ‘N’ student names through command line,
store theminto the appropriate Collection and display them by using Iterator
and ListIteratorinterface.
import java.util.*;

public class StudentList {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide student names as command line
arguments.");
return;
}

// Store student names in LinkedList


LinkedList<String> students = new LinkedList<>(Arrays.asList(args));

// Display using Iterator (Forward Traversal)


System.out.println("\nStudent Names (Forward Traversal using Iterator):");
Iterator<String> itr = students.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
// Display using ListIterator (Backward Traversal)
System.out.println("\nStudent Names (Backward Traversal using
ListIterator):");
ListIterator<String> listItr = students.listIterator(students.size());
while (listItr.hasPrevious()) {
System.out.println(listItr.previous());
}
}
}

Slip 24
1.Write a java program to scroll the text from left to right continuously.
import javax.swing.*;
import java.awt.*;

public class ScrollingText extends JFrame implements Runnable {


private JLabel label;
private String text = " Welcome to Java Programming! ";
private int x = 10, y = 50;

public ScrollingText() {
setTitle("Scrolling Text");
setSize(400, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);

label = new JLabel(text);


label.setFont(new Font("Arial", Font.BOLD, 20));
label.setBounds(x, y, 300, 30);
add(label);

Thread t = new Thread(this);


t.start();
}

@Override
public void run() {
while (true) {
x += 5; // Move text to the right
if (x > getWidth()) {
x = -200; // Reset position to left when text moves out of frame
}
label.setBounds(x, y, 300, 30);
try {
Thread.sleep(100); // Control speed of scrolling
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new ScrollingText().setVisible(true));
}
}
2.Write a JSP script to accept username and password from user, if they are
same thendisplay “Login Successfully” message in Login.html file, otherwise
display “LoginFailed” Message in Error.html file.
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="validate.jsp" method="post">
<label>Username: </label>
<input type="text" name="username" required><br><br>
<label>Password: </label>
<input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username != null && password != null && username.equals(password)) {
response.sendRedirect("Login.html");
} else {
response.sendRedirect("Error.html");
}
%>

Slip 25
1.Write a JSP program to accept Name and Age of Voter and check whether he
iseligible for voting or not. [15 M]

<!DOCTYPE html>
<html>
<head>
<title>Voter Eligibility</title>
</head>
<body>
<h2>Check Voter Eligibility</h2>
<form action="voterCheck.jsp" method="post">
<label>Enter Name:</label>
<input type="text" name="name" required><br><br>

<label>Enter Age:</label>
<input type="number" name="age" required><br><br>

<input type="submit" value="Check Eligibility">


</form>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));

if (age >= 18) {


%>
<h2 style="color:green;">Hello <%= name %>, You are Eligible for
Voting!</h2>
<%
} else {
%>
<h2 style="color:red;">Sorry <%= name %>, You are NOT Eligible for
Voting!</h2>
<%
}
%>
2.Write a Java Program for the following: Assume database is already

created.[15

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class DDLExecutor extends JFrame implements ActionListener {


private JTextField queryField;
private JButton createBtn, alterBtn, dropBtn;
private Connection con;

public DDLExecutor() {
setTitle("DDL Query Executor");
setSize(500, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

queryField = new JTextField(30);


add(new JLabel("Type Your DDL Query Here:"));
add(queryField);

createBtn = new JButton("Create Table");


alterBtn = new JButton("Alter Table");
dropBtn = new JButton("Drop Table");

createBtn.addActionListener(this);
alterBtn.addActionListener(this);
dropBtn.addActionListener(this);

add(createBtn);
add(alterBtn);
add(dropBtn);

// Connect to database
try {
con =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/yourDB",
"yourUser", "yourPass");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Database Connection Failed!");
}
}

@Override
public void actionPerformed(ActionEvent e) {
String query = queryField.getText();
if (query.isEmpty()) {
JOptionPane.showMessageDialog(this, "Enter a DDL Query!");
return;
}

try (Statement stmt = con.createStatement()) {


stmt.execute(query);
JOptionPane.showMessageDialog(this, "Query Executed Successfully!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new DDLExecutor().setVisible(true));
}
}

Slip 26
1.Write a Java program to delete the details of given employee (ENo EName
Salary).Accept employee ID through command line. (Use PreparedStatement
Interface)[15 M]

import java.sql.*;

public class DeleteEmployee {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java DeleteEmployee <Employee_ID>");
return;
}

int employeeID = Integer.parseInt(args[0]); // Accept Employee ID

String url = "jdbc:postgresql://localhost:5432/yourDB"; // Change for


MySQL
String user = "yourUsername";
String password = "yourPassword";

try (Connection con = DriverManager.getConnection(url, user, password)) {


String deleteQuery = "DELETE FROM Employee WHERE ENo = ?";
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
pstmt.setInt(1, employeeID);

int rowsAffected = pstmt.executeUpdate();

if (rowsAffected > 0) {
System.out.println("Employee with ID " + employeeID + " deleted
successfully.");
} else {
System.out.println("Employee with ID " + employeeID + " not found.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.Write a JSP program to calculate sum of first and last digit of a given number.
Displaysum in Red Color with font size 18
<!DOCTYPE html>
<html>
<head>
<title>Sum of First and Last Digit</title>
</head>
<body>
<h2>Enter a Number</h2>
<form action="sumDigits.jsp" method="post">
<input type="number" name="num" required>
<input type="submit" value="Calculate Sum">
</form>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%
int num = Integer.parseInt(request.getParameter("num"));
int lastDigit = num % 10;
int firstDigit = num;

while (firstDigit >= 10) {


firstDigit /= 10;
}

int sum = firstDigit + lastDigit;


%>
<h2 style="color:red; font-size:18px;">Sum of First and Last Digit: <%= sum
%></h2>

Slip 27
1.Write a Java Program to display the details of College (CID, CName, address,
Year)on JTable.
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;

public class CollegeTable extends JFrame {


public CollegeTable() {
setTitle("College Details");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

String[] columnNames = {"CID", "CName", "Address", "Year"};


DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
add(new JScrollPane(table));
try {
Connection con =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/yourDB",
"yourUser", "yourPass");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM College");

while (rs.next()) {
int cid = rs.getInt("CID");
String cname = rs.getString("CName");
String address = rs.getString("Address");
int year = rs.getInt("Year");

model.addRow(new Object[]{cid, cname, address, year});


}

con.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Database Connection Error: " +
e.getMessage());
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new CollegeTable().setVisible(true));
}
}
2.Write a SERVLET program to change inactive time interval of session.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@WebServlet("/SessionTimeoutServlet")
public class SessionTimeoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session = request.getSession();


session.setMaxInactiveInterval(300); // 300 seconds = 5 minutes

out.println("<h2>Session Timeout Set to 5 Minutes</h2>");


out.println("<h3>Current Session Timeout: " +
session.getMaxInactiveInterval() + " seconds</h3>");
}
}
Slip 28
1.Write a JSP script to accept a String from a user and display it in reverse
order.[15 M]

<!DOCTYPE html>
<html>
<head>
<title>Reverse String</title>
</head>
<body>
<h2>Enter a String to Reverse:</h2>
<form action="reverseString.jsp" method="post">
<input type="text" name="inputString" required>
<input type="submit" value="Reverse">
</form>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%
String inputString = request.getParameter("inputString");
if (inputString != null) {
String reversedString = new StringBuilder(inputString).reverse().toString();
%>
<h2>Reversed String: <%= reversedString %></h2>
<%
}
%>

2.Write a java program to display name of currently executing Thread in


multithreading.
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}

public void run() {


System.out.println("Currently Executing Thread: " +
Thread.currentThread().getName());
}
}

public class ThreadName {


public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
MyThread t3 = new MyThread("Thread-3");

t1.start();
t2.start();
t3.start();
}
}
Slip 29
1.Write a Java program to display information about all columns in the DONAR
tableusing ResultSetMetaData.

import java.sql.*;

public class DonarMetaData {


public static void main(String[] args) {
try {
// Establish database connection (Update DB details)
Connection con =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/yourDB",
"yourUser", "yourPass");

// Prepare SQL Query


String query = "SELECT * FROM DONAR";
PreparedStatement stmt = con.prepareStatement(query);

// Execute Query
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();

// Get Column Count


int columnCount = rsmd.getColumnCount();
System.out.println("Column Information of DONAR Table:");
// Display Column Details
for (int i = 1; i <= columnCount; i++) {
System.out.println("Column " + i + ": " + rsmd.getColumnName(i) +
" | Type: " + rsmd.getColumnTypeName(i) +
" | Size: " + rsmd.getColumnDisplaySize(i));
}

// Close Connection
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.Write a Java program to create LinkedList of integer objects and perform the
following:
i.Add element at first position
ii.Delete last element
iii.Display the size of link list

import java.util.LinkedList;

public class LinkedListOperations {


public static void main(String[] args) {
// Create LinkedList of Integers
LinkedList<Integer> list = new LinkedList<>();
// Adding elements
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);

System.out.println("Initial LinkedList: " + list);

// Add element at the first position


list.addFirst(5);
System.out.println("After Adding 5 at First Position: " + list);

// Delete last element


list.removeLast();
System.out.println("After Deleting Last Element: " + list);

// Display size of LinkedList


System.out.println("Size of LinkedList: " + list.size());
}
}

Slip 30
1.Write a java program for the implementation of synchronization.

class BankAccount {
private int balance = 1000; // Initial balance

// Synchronized method to withdraw money


public synchronized void withdraw(String name, int amount) {
if (balance >= amount) {
System.out.println(name + " is withdrawing $" + amount);
balance -= amount;
System.out.println("Remaining Balance: $" + balance);
} else {
System.out.println(name + " tried to withdraw $" + amount + " -
Insufficient Funds!");
}
}
}

// Thread class
class Customer extends Thread {
private BankAccount account;
private String customerName;
private int amount;

public Customer(BankAccount account, String name, int amount) {


this.account = account;
this.customerName = name;
this.amount = amount;
}
public void run() {
account.withdraw(customerName, amount);
}
}

public class SynchronizationExample {


public static void main(String[] args) {
BankAccount account = new BankAccount();

// Creating multiple threads trying to withdraw money


Customer c1 = new Customer(account, "Alice", 500);
Customer c2 = new Customer(account, "Bob", 700);
Customer c3 = new Customer(account, "Charlie", 300);

c1.start();
c2.start();
c3.start();
}
}
2.Write a Java Program for the implementation of scrollable ResultSet. Assume
Teachertable with attributes (TID, TName, Salary) is already created.

import java.sql.*;

public class ScrollableResultSet {


public static void main(String[] args) {
try {
// Connect to the database
Connection con =
DriverManager.getConnection("jdbc:postgresql://localhost:5432/yourDB",
"yourUser", "yourPass");

// Create a Scrollable ResultSet


Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM Teacher");

// Move to last row


if (rs.last()) {
System.out.println("Last Record - TID: " + rs.getInt("TID") + ", Name: "
+ rs.getString("TName") + ", Salary: " + rs.getDouble("Salary"));
}

// Move to first row


if (rs.first()) {
System.out.println("First Record - TID: " + rs.getInt("TID") + ", Name: "
+ rs.getString("TName") + ", Salary: " + rs.getDouble("Salary"));
}

// Move backward
System.out.println("\nDisplaying in Reverse Order:");
rs.afterLast(); // Move cursor after last row
while (rs.previous()) {
System.out.println("TID: " + rs.getInt("TID") + ", Name: " +
rs.getString("TName") + ", Salary: " + rs.getDouble("Salary"));
}

// Close Connection
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

You might also like