0% found this document useful (0 votes)
7 views17 pages

Java Exam Reference

The document provides a comprehensive reference for Java, JSP, JDBC, and Servlet programming, including code examples for various tasks such as database operations, multithreading, and user input handling. It covers topics like inserting and displaying records in a database, checking for perfect and prime numbers, and managing servlet cookies. Additionally, it includes examples for sorting names, displaying even and odd numbers, and user authentication through login forms.

Uploaded by

Red Gear
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views17 pages

Java Exam Reference

The document provides a comprehensive reference for Java, JSP, JDBC, and Servlet programming, including code examples for various tasks such as database operations, multithreading, and user input handling. It covers topics like inserting and displaying records in a database, checking for perfect and prime numbers, and managing servlet cookies. Additionally, it includes examples for sorting names, displaying even and odd numbers, and user authentication through login forms.

Uploaded by

Red Gear
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA / JSP / JDBC / Servlet

Exam-Ready Code Reference | All Questions Covered

Q3a) JDBC – Accept Book Details (B_id, B_name, B_cost) & Display
▶ Also covers: JDBC student (RN, Name, percentage) — same pattern, change table/columns

import [Link].*;
import [Link];

public class BookJDBC {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Enter Book ID: ");
int bid = [Link](); [Link]();
[Link]("Enter Book Name: ");
String bname = [Link]();
[Link]("Enter Book Cost: ");
double bcost = [Link]();

[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password");

String q = "INSERT INTO Book(B_id,B_name,B_cost) VALUES(?,?,?)";


PreparedStatement ps = [Link](q);
[Link](1, bid);
[Link](2, bname);
[Link](3, bcost);
[Link]();
[Link]("Record inserted!");

Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM Book");
[Link]("B_id\tB_name\tB_cost");
while ([Link]()) {
[Link]([Link](1)+"\t"+[Link](2)+"\t"+[Link](3));
}
[Link]();
}
}

SQL: CREATE TABLE Book(B_id INT, B_name VARCHAR(50), B_cost DOUBLE);


Q3b) Multithreading – Display Alphabets A to Z (2 sec delay)
▶ Also covers: Multithreading numbers 1 to 10 with 2 sec delay — same pattern

class AlphaThread extends Thread {


public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
[Link](c);
try {
[Link](2000); // 2 seconds
} catch (InterruptedException e) {
[Link](e);
}
}
}
}

public class AlphaDemo {


public static void main(String[] args) {
AlphaThread t = new AlphaThread();
[Link]();
}
}
Q3b-ALT) Multithreading – Display Numbers 1 to 10 (2 sec delay)

class NumThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i++) {
[Link](i);
try {
[Link](2000);
} catch (InterruptedException e) {
[Link](e);
}
}
}
}

public class NumDemo {


public static void main(String[] args) {
NumThread t = new NumThread();
[Link]();
}
}
Q3c) JSP – Check Perfect Number (display in Yellow)
▶ Also covers: Check Prime Number (display in Blue) — see next section

[Link] (Form)
<html><body>
<form action='[Link]' method='post'>
Enter Number: <input type='text' name='num'>
<input type='submit' value='Check'>
</form>
</body></html>

[Link]
<%@ page language='java' %>
<html><body>
<%
int n = [Link]([Link]("num"));
int sum = 0;
for (int i = 1; i < n; i++) {
if (n % i == 0) sum += i;
}
String result = (sum == n) ? n + " is a Perfect Number"
: n + " is NOT a Perfect Number";
%>
<p style='color:yellow; background:black;'><%=result%></p>
</body></html>
Q3c-ALT) JSP – Check Prime Number (display in Blue)

[Link]
<html><body>
<form action='[Link]' method='post'>
Enter Number: <input type='text' name='num'>
<input type='submit' value='Check'>
</form>
</body></html>

[Link]
<%@ page language='java' %>
<html><body>
<%
int n = [Link]([Link]("num"));
boolean isPrime = (n > 1);
for (int i = 2; i <= [Link](n); i++) {
if (n % i == 0) { isPrime = false; break; }
}
String result = isPrime ? n+" is Prime" : n+" is NOT Prime";
%>
<p style='color:blue;'><%=result%></p>
</body></html>
Q4a) Servlet – Count Number of Times Servlet Invoked (Cookies)

[Link]
import [Link].*;
import [Link].*;
import [Link].*;

public class CountServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
int count = 0;
Cookie[] cookies = [Link]();
if (cookies != null) {
for (Cookie c : cookies) {
if ([Link]().equals("visitCount")) {
count = [Link]([Link]());
}
}
}
count++;
Cookie ck = new Cookie("visitCount", [Link](count));
[Link](60 * 60); // 1 hour
[Link](ck);
[Link]("<h2>Servlet invoked " + count + " time(s)</h2>");
}
}

[Link] mapping
<servlet>
<servlet-name>CountServlet</servlet-name>
<servlet-class>CountServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CountServlet</servlet-name>
<url-pattern>/count</url-pattern>
</servlet-mapping>
Q4a-ALT) Servlet – Get Server Info (Name, Port, Version)

[Link]
import [Link].*;
import [Link].*;
import [Link].*;

public class ServerInfoServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
ServletContext ctx = getServletContext();
[Link]("<h2>Server Information</h2>");
[Link]("<b>Server Name:</b> " + [Link]() + "<br>");
[Link]("<b>Port Number:</b> " + [Link]() + "<br>");
[Link]("<b>Server Info:</b> " + [Link]() + "<br>");
}
}
Q4b) Java – Accept N Numbers, Store in LinkedList, Display Odd Numbers

import [Link].*;

public class LinkedListOdd {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("How many numbers? ");
int n = [Link]();
LinkedList<Integer> list = new LinkedList<>();
for (int i = 0; i < n; i++) {
[Link]("Enter number " + (i+1) + ": ");
[Link]([Link]());
}
[Link]("Odd Numbers:");
for (int x : list) {
if (x % 2 != 0) [Link](x);
}
}
}
Q4b-ALT) Java – Accept N Names, Store in ArrayList, Sort Ascending

import [Link].*;

public class SortNames {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("How many names? ");
int n = [Link](); [Link]();
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
[Link]("Enter name " + (i+1) + ": ");
[Link]([Link]());
}
[Link](list);
[Link]("Sorted Names:");
for (String s : list) [Link](s);
}
}
Q) Java – Accept N Integers, Store in Collection, Display Even Numbers

import [Link].*;

public class EvenNumbers {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("How many numbers? ");
int n = [Link]();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
[Link]("Enter number " + (i+1) + ": ");
[Link]([Link]());
}
[Link]("Even Numbers:");
for (int x : list) {
if (x % 2 == 0) [Link](x);
}
}
}
Q) JDBC – Accept Teacher Details (Tid, Tname, Tsubject), Store & Display
▶ Also covers: Delete teacher record & display remaining (see next section)

import [Link].*;
import [Link];

public class TeacherJDBC {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Enter Teacher ID: ");
int tid = [Link](); [Link]();
[Link]("Enter Teacher Name: ");
String tname = [Link]();
[Link]("Enter Subject: ");
String tsubject = [Link]();

[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password");

PreparedStatement ps = [Link](
"INSERT INTO Teacher(tid,tname,tsubject) VALUES(?,?,?)");
[Link](1, tid);
[Link](2, tname);
[Link](3, tsubject);
[Link]();
[Link]("Teacher record inserted!");

ResultSet rs = [Link]().executeQuery("SELECT * FROM Teacher");


[Link]("Tid\tTname\tTsubject");
while ([Link]())
[Link]([Link](1)+"\t"+[Link](2)+"\t"+[Link](3));
[Link]();
}
}

SQL: CREATE TABLE Teacher(tid INT, tname VARCHAR(50), tsubject VARCHAR(50));


Q) JDBC – Delete Teacher Record & Display Remaining

import [Link].*;
import [Link];

public class DeleteTeacher {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Enter Teacher ID to delete: ");
int tid = [Link]();

[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password");

PreparedStatement ps = [Link](
"DELETE FROM Teacher WHERE tid=?");
[Link](1, tid);
int rows = [Link]();
[Link](rows + " record(s) deleted.");

ResultSet rs = [Link]().executeQuery("SELECT * FROM Teacher");


[Link]("Remaining Records:");
[Link]("Tid\tTname\tTsubject");
while ([Link]())
[Link]([Link](1)+"\t"+[Link](2)+"\t"+[Link](3));
[Link]();
}
}
Q) JDBC – Update Employee Salary (PreparedStatement) — Emp(Eno,
Ename, Esal)

import [Link].*;
import [Link];

public class UpdateSalary {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Enter Employee Number: ");
int eno = [Link]();
[Link]("Enter New Salary: ");
double esal = [Link]();

[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password");

PreparedStatement ps = [Link](
"UPDATE Emp SET Esal=? WHERE Eno=?");
[Link](1, esal);
[Link](2, eno);
int rows = [Link]();
[Link](rows > 0 ? "Salary updated!" : "Employee not found.");
[Link]();
}
}
Q) JSP – Accept Username & Greet According to Time

[Link]
<html><body>
<form action='[Link]' method='post'>
Enter Name: <input type='text' name='uname'>
<input type='submit' value='Greet'>
</form>
</body></html>

[Link]
<%@ page language='java' import='[Link].*' %>
<html><body>
<%
String name = [Link]("uname");
Calendar cal = [Link]();
int hour = [Link](Calendar.HOUR_OF_DAY);
String msg;
if (hour < 12) msg = "Good Morning, " + name + "!";
else if (hour < 17) msg = "Good Afternoon, " + name + "!";
else msg = "Good Evening, " + name + "!";
%>
<h2><%=msg%></h2>
</body></html>
Q) JSP – Login: Username & Password Same → Login Successful / Failed

[Link]
<html><body>
<form action='[Link]' method='post'>
Username: <input type='text' name='uname'><br>
Password: <input type='password' name='pwd'><br>
<input type='submit' value='Login'>
</form>
</body></html>

[Link]
<%@ page language='java' %>
<html><body>
<%
String u = [Link]("uname");
String p = [Link]("pwd");
if ([Link](p)) {
%>
<h2 style='color:green;'>Login Successful</h2>
<% } else { %>
<h2 style='color:red;'>Login Failed</h2>
<% } %>
</body></html>
Q) Java – Accept N Student Names, Store in LinkedList, Display in Reverse

import [Link].*;

public class LinkedListReverse {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("How many names? ");
int n = [Link](); [Link]();
LinkedList<String> list = new LinkedList<>();
for (int i = 0; i < n; i++) {
[Link]("Enter name " + (i+1) + ": ");
[Link]([Link]());
}
[Link](list);
[Link]("Names in Reverse Order:");
for (String s : list) [Link](s);
}
}
Q) JDBC – Accept Student Details (rollno, name, percentage) & Display

import [Link].*;
import [Link];

public class StudentJDBC {


public static void main(String[] args) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("Enter Roll No: ");
int rno = [Link](); [Link]();
[Link]("Enter Name: ");
String name = [Link]();
[Link]("Enter Percentage: ");
double perc = [Link]();

[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password");

PreparedStatement ps = [Link](
"INSERT INTO Student(rollno,name,percentage) VALUES(?,?,?)");
[Link](1, rno);
[Link](2, name);
[Link](3, perc);
[Link]();
[Link]("Student record inserted!");

ResultSet rs = [Link]().executeQuery("SELECT * FROM Student");


[Link]("RollNo\tName\tPercentage");
while ([Link]())
[Link]([Link](1)+"\t"+[Link](2)+"\t"+[Link](3));
[Link]();
}
}

SQL: CREATE TABLE Student(rollno INT, name VARCHAR(50), percentage DOUBLE);

You might also like