JAVA PYQ Programs :-
1)Write a Java program to accept 'N' student names from the user, store them in a LinkedList collection, and
display in reverse order
// Import necessary classes from the Java utility package
import java.util.*;
public class StudentNames {
public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner sc = new Scanner(System.in);
// Create a LinkedList to store student names
LinkedList<String> students = new LinkedList<>();
// Ask the user for the number of students
System.out.print("Enter the number of students: ");
int n = sc.nextInt(); // Read the number of students
sc.nextLine(); // Consume the leftover newline character after nextInt()
// Loop to take 'n' student names as input
for (int i = 0; i < n; i++) {
System.out.print("Enter student name: ");
String name = sc.nextLine(); // Read the student name
students.add(name); // Add the name to the LinkedList
// Reverse the LinkedList using Collections utility class
Collections.reverse(students);
// Display the student names in reverse order
System.out.println("\nStudent names in reverse order:");
for (String name : students) {
System.out.println(name); // Print each name from the list
// Close the scanner object to prevent memory leaks
sc.close();
}
2)Write a Java program to accept details of a student (rollno, name, percentage), store them into a database &
display it. (Note: Assume JDBC setup is already done)
// Import necessary classes for SQL and user input
import java.sql.*; // For JDBC operations
import java.util.Scanner; // For taking input from the user
public class StudentDetails {
public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner sc = new Scanner(System.in);
// Ask user to enter roll number
System.out.print("Enter roll number: ");
int rollno = sc.nextInt(); // Read roll number as integer
sc.nextLine(); // Consume the leftover newline character after reading int
// Ask user to enter name
System.out.print("Enter name: ");
String name = sc.nextLine(); // Read name as string
// Ask user to enter percentage
System.out.print("Enter percentage: ");
double percentage = sc.nextDouble(); // Read percentage as double
// Start of try block to handle SQL operations
try {
// Load PostgreSQL JDBC driver class
Class.forName("org.postgresql.Driver");
// Establish connection to the PostgreSQL database
// Parameters: URL, username, password
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://192.168.1.21:5432/ty90", // Database URL
"ty90", // Username
"" // Password (empty in this case)
);
// Prepare SQL query to insert student data into the table
String query = "INSERT INTO students (rollno, name, percentage) VALUES (?, ?, ?)";
// Create PreparedStatement object to safely insert data
PreparedStatement ps = conn.prepareStatement(query);
// Set values in the prepared statement
ps.setInt(1, rollno); // Set roll number
ps.setString(2, name); // Set name
ps.setDouble(3, percentage); // Set percentage
// Execute the SQL query to insert the data
ps.executeUpdate();
// Print confirmation message
System.out.println("\nStudent details saved successfully!");
// Prepare SQL query to fetch all records from students table
String selectQuery = "SELECT * FROM students";
// Create a Statement object to execute the select query
Statement stmt = conn.createStatement();
// Execute the query and store the result in ResultSet
ResultSet rs = stmt.executeQuery(selectQuery);
// Print header
System.out.println("\n--- Student Records ---");
// Loop through the ResultSet and display each student record
while (rs.next()) {
// Get each column by name and display
System.out.println("Roll No: " + rs.getInt("rollno") +
", Name: " + rs.getString("name") +
", Percentage: " + rs.getDouble("percentage"));
// Close the database connection
conn.close();
} catch (ClassNotFoundException e) {
// Handle error if JDBC driver class not found
System.out.println("PostgreSQL JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
// Handle SQL-related errors
System.out.println("Database error occurred.");
e.printStackTrace();
// Close the scanner object
sc.close();
}
}
3)Write a JSP program to accept username & password, if username & password are the same then display "Login
successful" message on the browser otherwise display "Login failed" message.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>
<%@ page import="java.io.*, java.util.*" %>
<!-- HTML starts here -->
<html>
<head>
<title>Login Page</title>
</head>
<body>
<!-- Simple form to take username and password input from the user -->
<form method="POST">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Login" />
</form>
<%
// Retrieve the values entered by the user in the form
String username = request.getParameter("username");
String password = request.getParameter("password");
// Check if both username and password are not null (i.e., form is submitted)
if (username != null && password != null) {
// Check if both username and password are "admin"
if (username.equals("admin") && password.equals("admin")) {
// Display success message if matched
out.println("<h3 style='color:green;'>Login successful</h3>");
} else {
// Display failure message if not matched
out.println("<h3 style='color:red;'>Login failed</h3>");
%>
</body>
</html>
4)Write a Java program to delete the details of a given teacher & display remaining records from Teacher Table.
Assume teacher table (tid, tname, subject) is already created.
// Import necessary classes for JDBC and user input
import java.sql.*;
import java.util.Scanner;
public class DeleteTeacher {
public static void main(String[] args) {
// Create Scanner object to take user input
Scanner sc = new Scanner(System.in);
// Ask user to enter the Teacher ID to delete
System.out.print("Enter Teacher ID to delete: ");
int tid = sc.nextInt(); // Read the Teacher ID from user
try {
// Load the PostgreSQL JDBC driver
Class.forName("org.postgresql.Driver");
// Establish connection to the database
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://192.168.1.21:5432/ty90", // database URL
"ty90", // username
"" // password (blank in this case)
);
// SQL query to delete a teacher with given ID
String deleteQuery = "DELETE FROM teacher WHERE tid = ?";
// Use PreparedStatement to set the value dynamically
PreparedStatement ps = conn.prepareStatement(deleteQuery);
ps.setInt(1, tid); // Set the teacher ID in the query
// Execute the delete operation
ps.executeUpdate();
System.out.println("Teacher record deleted.");
// Now display remaining teacher records
String selectQuery = "SELECT * FROM teacher";
Statement stmt = conn.createStatement(); // Create statement object
ResultSet rs = stmt.executeQuery(selectQuery); // Execute the query
// Loop through the result and print each teacher's data
System.out.println("\nRemaining Teacher Records:");
while (rs.next()) {
System.out.println("Teacher ID: " + rs.getInt(1)
+ ", Name: " + rs.getString(2)
+ ", Subject: " + rs.getString(3));
// Close connections (optional good practice)
rs.close();
stmt.close();
ps.close();
conn.close();
} catch (Exception e) {
// Print any exception that occurs
e.printStackTrace();
5)Write a jdbc program to accept details of student (RN, Name, percentage) from user. Display that details.
// Import necessary packages for SQL and user input
import java.sql.*;
import java.util.Scanner;
public class StudentDetails {
public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner sc = new Scanner(System.in);
// Ask user to enter Roll Number
System.out.println("Enter Roll Number: ");
String rollNo = sc.nextLine();
// Ask user to enter Name
System.out.println("Enter Name: ");
String name = sc.nextLine();
// Ask user to enter Percentage
System.out.println("Enter Percentage: ");
float percentage = sc.nextFloat();
try {
// Load the PostgreSQL JDBC driver
Class.forName("org.postgresql.Driver");
// Establish connection to the database
Connection con = DriverManager.getConnection(
"jdbc:postgresql://192.168.1.21:5432/ty90", // DB URL
"ty90", // username
"" // password (if any)
);
// SQL query to insert data into student table
String query = "INSERT INTO student (rollNo, name, percentage) VALUES (?, ?, ?)";
// Prepare the SQL statement
PreparedStatement pstmt = con.prepareStatement(query);
// Set values to the query using user input
pstmt.setString(1, rollNo);
pstmt.setString(2, name);
pstmt.setFloat(3, percentage);
// Execute the insert query and get number of affected rows
int rowsAffected = pstmt.executeUpdate();
// If insertion was successful, print confirmation
if (rowsAffected > 0) {
System.out.println("Student details inserted successfully.");
// Display the inserted data
System.out.println("Roll Number: " + rollNo);
System.out.println("Name: " + name);
System.out.println("Percentage: " + percentage);
// Close the database connection
con.close();
} catch (Exception e) {
// Print the exception details if any error occurs
e.printStackTrace();
}
}
6)Write a java program in multithreading to display all the numbers between 1 to 10. Each number should display
after 2 seconds.
// Define a class that extends the Thread class
class NumberThread extends Thread {
// Override the run() method which contains the code to be executed by the thread
public void run() {
// Loop to print numbers from 1 to 10
for (int i = 1; i <= 10; i++) {
try {
// Make the thread sleep (pause) for 2 seconds (2000 milliseconds)
Thread.sleep(2000);
// Print the current number
System.out.println(i);
} catch (InterruptedException e) {
// Handle any interruption during the sleep
e.printStackTrace();
// Main class that will start the thread
public class DisplayNumbers {
// Main method: entry point of the program
public static void main(String[] args) {
// Create an object of the NumberThread class
NumberThread t = new NumberThread();
// Start the thread - this will call the run() method in a separate thread
t.start();
7)Write a JSP script to check the given number is prime or not. Display the result in blue color.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!-- This directive tells the server that the page uses Java language and sets character encoding -->
<!DOCTYPE html>
<!-- Declares the document type as HTML5 -->
<html>
<head>
<title>Prime Number Check</title>
<!-- Sets the title of the web page shown in the browser tab -->
</head>
<body>
<!-- The body of the web page starts here -->
<!-- HTML form to take number input from user -->
<form method="post">
<!-- This form sends data to the same JSP page using POST method -->
Enter Number: <input type="text" name="num">
<!-- Text box where user enters a number -->
<input type="submit" value="Check">
<!-- Submit button to send the form data -->
</form>
<%
// Start of JSP scriptlet - where we write Java code
String numStr = request.getParameter("num");
// Get the value entered in the input field "num" from the request and store it in numStr
if (numStr != null && !numStr.isEmpty()) {
// Check if user has entered something (not null and not empty)
int num = Integer.parseInt(numStr);
// Convert the string input to an integer
boolean isPrime = true;
// Assume the number is prime initially
// Loop from 2 to num/2 to check if the number is divisible by any number in between
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
// If number is divisible by i, then it's not a prime number
isPrime = false;
// Set the flag to false
break;
// Exit the loop as we already found it's not prime
// If number is greater than 1 and isPrime is still true
if (isPrime && num > 1) {
// Print the result in blue color saying it's a prime number
out.println("<p style='color:blue;'>The number " + num + " is a Prime number.</p>");
} else {
// Otherwise, print that it is not a prime number
out.println("<p style='color:blue;'>The number " + num + " is not a Prime number.</p>");
%>
<!-- End of JSP scriptlet -->
</body>
</html>
<!-- End of HTML document -->
8)Write a Servlet program to get information about the server such as name, port number, and version of the
server
// Import required packages
import javax.servlet.*; // Import classes for creating a servlet
import javax.servlet.http.*; // Import classes for handling HTTP requests
import java.io.*; // Import classes for input and output
// Define a servlet class by extending HttpServlet
public class ServerInfoServlet extends HttpServlet {
// Override the doGet() method to handle GET requests
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
// Set the response content type to HTML so the browser understands the output
PrintWriter out = response.getWriter();
// Get a PrintWriter object to write output (HTML) to the response
out.println("<html><body>");
// Begin writing the HTML content
out.println("<h1>Server Information</h1>");
// Display a heading on the web page
out.println("<p>Server Name: " + getServletContext().getServerInfo() + "</p>");
// Display the server name using getServerInfo() method
out.println("<p>Server Port: " + request.getServerPort() + "</p>");
// Display the port number on which the server is running
out.println("<p>Server Address: " + request.getServerName() + "</p>");
// Display the server's IP address or domain name
out.println("</body></html>");
// Close the HTML content
9)Write a Java program to accept 'n' names from the user, store them into ArrayList, sort them in ascending order,
and display them.
// Import required packages
import java.util.*; // Import utility package for Scanner, ArrayList, and Collections
// Main class
public class SortNames {
public static void main(String[] args) {
// Create a Scanner object for taking user input
Scanner sc = new Scanner(System.in);
// Ask the user for the number of names they want to enter
System.out.println("Enter number of names: ");
int n = sc.nextInt(); // Read the number of names
sc.nextLine(); // Consume the leftover newline character from previous input
// Create an ArrayList to store names
ArrayList<String> names = new ArrayList<>();
// Loop to accept 'n' names from the user
for (int i = 0; i < n; i++) {
System.out.println("Enter name " + (i + 1) + ": ");
names.add(sc.nextLine()); // Add each name to the ArrayList
}
// Sort the names in ascending (alphabetical) order
Collections.sort(names);
// Display the sorted names
System.out.println("Sorted Names: ");
for (String name : names) {
System.out.println(name); // Print each name from the sorted list
10)Write a Java program to accept N integers from the user, store them in a suitable collection, and display only
even integers.
// Import required classes from Java utility package
import java.util.*;
// Main class
public class EvenIntegers {
public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner scanner = new Scanner(System.in);
// Create a list to store the integers
List<Integer> numbers = new ArrayList<>();
// Ask the user how many numbers they want to enter
System.out.print("Enter the number of integers: ");
int N = scanner.nextInt(); // Read the number entered by the user
// Ask the user to enter N integers
System.out.println("Enter the integers:");
for (int i = 0; i < N; i++) {
// Read each integer and add it to the list
numbers.add(scanner.nextInt());
// Display even numbers from the list
System.out.println("Even integers:");
for (int num : numbers) {
// Check if the number is even (divisible by 2)
if (num % 2 == 0) {
// If it is even, print the number
System.out.println(num);
11)Write a Java program to accept details of a teacher (Tid, Tname, Tsubject), store it in the database, and display
it.
// Import necessary Java SQL classes
import java.sql.*;
// Import Scanner for taking input from the user
import java.util.Scanner;
// Class to insert and display teacher details from a database
public class TeacherDetails {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Ask the user to enter teacher ID
System.out.print("Enter Teacher ID: ");
int tid = scanner.nextInt(); // Read teacher ID as integer
scanner.nextLine(); // Consume the leftover newline character
// Ask the user to enter teacher name
System.out.print("Enter Teacher Name: ");
String tname = scanner.nextLine(); // Read teacher name
// Ask the user to enter teacher subject
System.out.print("Enter Teacher Subject: ");
String tsubject = scanner.nextLine(); // Read teacher subject
try {
// Load PostgreSQL JDBC driver
Class.forName("org.postgresql.Driver");
// Establish a connection to the database
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://192.168.1.21:5432/ty90", // DB URL
"ty90", // Username
"" // Password (empty in this case)
);
// SQL query to insert teacher details into the table
String query = "INSERT INTO teacher (Tid, Tname, Tsubject) VALUES (?, ?, ?)";
// Prepare the SQL statement
PreparedStatement stmt = conn.prepareStatement(query);
// Set values in the SQL query using user input
stmt.setInt(1, tid); // Set Teacher ID
stmt.setString(2, tname); // Set Teacher Name
stmt.setString(3, tsubject); // Set Teacher Subject
// Execute the insert operation
stmt.executeUpdate();
// Confirm that data is inserted
System.out.println("Teacher details inserted successfully.");
// SQL query to retrieve and display all teacher records
String selectQuery = "SELECT * FROM teacher";
// Create a statement to execute the select query
Statement selectStmt = conn.createStatement();
// Execute the query and get the result set
ResultSet rs = selectStmt.executeQuery(selectQuery);
// Loop through the result set and print each teacher's details
while (rs.next()) {
System.out.println("ID: " + rs.getInt("Tid") +
", Name: " + rs.getString("Tname") +
", Subject: " + rs.getString("Tsubject"));
// Close the connection (optional but good practice)
conn.close();
} catch (SQLException e) {
// Print the error if there is any SQL exception
e.printStackTrace();
} catch (ClassNotFoundException e) {
// Handle exception if JDBC driver is not found
e.printStackTrace();
12)Write a JSP program to accept the user's name and greet the user according to the time of day
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%> <%-- JSP directive to define page language and encoding --%>
<!DOCTYPE html> <%-- HTML5 doctype declaration --%>
<html>
<head>
<title>Greeting Page</title> <%-- Title of the web page --%>
</head>
<body>
<h2>Enter your name:</h2> <%-- Heading prompting user to enter their name --%>
<form method="post"> <%-- Form using POST method to send data --%>
<input type="text" name="username" /> <%-- Text field to enter username --%>
<input type="submit" value="Submit" /> <%-- Submit button --%>
</form>
<%
String username = request.getParameter("username"); // Get the value of the username entered by user
if (username != null) { // Check if the form was submitted (i.e., username is not null)
int hour = java.util.Calendar.getInstance().get(java.util.Calendar.HOUR_OF_DAY); // Get current hour of day
String greeting = ""; // Initialize greeting message
if (hour < 12) { // If time is before 12 PM
greeting = "Good Morning, " + username + "!"; // Morning greeting
} else if (hour < 18) { // If time is between 12 PM and 6 PM
greeting = "Good Afternoon, " + username + "!"; // Afternoon greeting
} else { // If time is after 6 PM
greeting = "Good Evening, " + username + "!"; // Evening greeting
out.print("<h3>" + greeting + "</h3>"); // Display the greeting message on the browser
%>
</body>
</html>
13)Write a Java program to update the salary of a given employee (use prepared statement interface).
import java.sql.*; // Import all classes from java.sql package for database operations
public class UpdateSalary { // Class to update an employee's salary
public static void main(String[] args) {
try {
// Load the PostgreSQL JDBC driver
Class.forName("org.postgresql.Driver");
// Establish a connection to the PostgreSQL database
Connection conn = DriverManager.getConnection(
"jdbc:postgresql://192.168.1.21:5432/ty90", // Database URL
"ty90", // Username
"" // Password (empty in this case)
);
// SQL query to update salary of an employee based on employee number
String query = "UPDATE employee SET Esal = ? WHERE Eno = ?";
// Create a PreparedStatement object to safely execute the query
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setDouble(1, 50000); // Set the new salary value (Esal = 50000)
stmt.setInt(2, 101); // Set the employee number (Eno = 101)
// Execute the update query and get the number of affected rows
int rowsUpdated = stmt.executeUpdate();
// If at least one row is updated, print confirmation message
if (rowsUpdated > 0) {
System.out.println("Employee salary updated successfully.");
} catch (SQLException e) {
// Handle SQL-related exceptions by printing the stack trace
e.printStackTrace();
} catch (ClassNotFoundException e) {
// Handle error if JDBC driver class is not found
e.printStackTrace();
}
}