java II
java II
The List Interface in Java is a part of the Collection Framework and represents an ordered
collection of elements. It allows duplicate elements and provides methods to access elements by
index. Example implementations include ArrayList and LinkedList.
b) What is JDBC?
JDBC (Java Database Connectivity) is an API in Java that helps in connecting and interacting
with databases. It allows Java programs to insert, update, delete, and retrieve data from a
database.
A thread in Java can be started using the start() method after creating a thread using Thread class or
Runnable interface.
Example:
e) What is JSP?
JSP (JavaServer Pages) is a technology used to create dynamic web pages using Java. It allows
embedding Java code inside HTML using special tags like <% %>.
Spring Framework is a Java framework used for developing enterprise applications. It provides
features like dependency injection, MVC architecture, and security.
g) Define Hashtable.
A Hashtable is a Java collection that stores key-value pairs. It is similar to a HashMap, but it is
synchronized (thread-safe).
The join() method in Java is used to pause the execution of the current thread until another thread
finishes its execution.
d) What is scriplet?
A scriptlet is Java code written inside a JSP page using <% and %>. It allows dynamic content
generation in web pages.
i) What is ArrayList?
ArrayList is a dynamic array in Java that can grow or shrink as needed. It is part of the java.util
package.
j) Define Cookie.
A cookie is a small piece of data stored in a web browser. It helps in maintaining user sessions and
preferences.
a) Define Collection.
A Collection in Java is a framework that provides a way to store, manipulate, and process a group of
objects efficiently.
d) What is Servlet?
A Servlet is a Java program that runs on a web server and handles client requests, usually for web
applications.
i) Define Multithreading.
Multithreading is a process where multiple threads run simultaneously to perform different tasks
within a single program.
j) What is a Session?
A session is a way to store user-specific data across multiple requests in a web application, using
mechanisms like HTTP sessions or cookies.
c) What is JDBC?
JDBC (Java Database Connectivity) is an API that allows Java applications to interact with
databases using SQL queries.
d) Define Session.
A session is a mechanism to store user data across multiple requests in a web application, usually
using HTTP sessions or cookies.
e) What is use of request object?
The request object in JSP and Servlets is used to get data sent by the client, such as form inputs and
parameters.
h) Define HashTable.
A HashTable in Java is a data structure that stores key-value pairs and synchronizes access for
thread safety.
b) What is Thread?
A thread is a lightweight process that runs independently within a program, allowing multitasking.
d) Define Set.
A Set in Java is a collection that stores unique elements and does not allow duplicates.
f) Define Spring.
Spring is a Java framework for building enterprise applications, providing features like dependency
injection and MVC architecture.
j) What is Cookie?
A cookie is a small piece of data stored in a web browser to track user sessions and preferences.
Q2
Here are the answers with a little more explanation for better understanding:
ResultSet Interface in JDBC is used to store and retrieve the result of a SQL query execution. It
allows navigating through records in a database table row by row.
next() – Moves the cursor to the next row in the result set. Returns true if a row exists,
otherwise false.
JSP provides several implicit objects that can be used without explicit declaration.
1. request – Represents the HttpServletRequest object, which contains client request data
(e.g., form inputs, URL parameters).
2. <%= request.getParameter("name") %>
3. session – Represents HttpSession, which stores user session data across multiple requests.
4. <%= session.getAttribute("username") %>
c) List the parameters of doPost() in Servlet.
The doPost() method in a Servlet is used to handle POST requests from clients. It takes two
parameters:
1. HttpServletRequest request – Contains data sent by the client in the request body (e.g., form
data).
2. HttpServletResponse response – Used to send response back to the client.
Example:
Java provides inter-thread communication methods to allow threads to coordinate their execution.
wait() – Makes a thread pause execution until another thread notifies it using notify().
synchronized(obj) {
obj.wait(); // Makes the current thread wait
}
notify() – Wakes up a waiting thread that has called wait().
synchronized(obj) {
obj.notify(); // Wakes up a thread waiting on obj
}
These methods help in avoiding race conditions and ensuring proper synchronization between
threads.
1. Extending the Thread class: Create a class that extends Thread, override the run() method,
and start the thread using start().
2. Implementing the Runnable interface: Implement Runnable, define the run() method, and
pass the instance to a Thread object before calling start().
List Set
1. setAttribute(String name, Object value) – Stores an attribute in the session for future use.
2. getAttribute(String name) – Retrieves the stored attribute from the session.
1. Web Applications – Spring MVC is widely used for building web applications.
2. Enterprise Applications – Spring Boot helps in developing scalable enterprise applications.
3. Microservices – Spring Cloud is used for developing distributed microservices.
4. Security – Spring Security is used for authentication and authorization in applications.
1. Easier to Write – JSP allows embedding Java code in HTML, making it more readable than
Servlets.
2. Less Code Complexity – In Servlets, handling HTML with Java code is complex, while JSP
simplifies this.
3. Automatic Compilation – JSP pages are automatically compiled into Servlets, reducing
manual effort.
4. Built-in Implicit Objects – JSP provides objects like request, response, and session without
needing explicit creation.
The key difference between ArrayList and LinkedList is that ArrayList uses an internal array to
store elements, leading to faster random access, while LinkedList uses a doubly linked list
structure, making it more efficient for insertions and deletions in the middle of the list, especially
when compared to ArrayList where such operations often require shifting elements within the
array.
1. Generic Servlet – A protocol-independent servlet that can handle any type of request.
2. HTTP Servlet – A servlet designed specifically to handle HTTP requests like GET and
POST.
Implementation Example:
import java.util.*;
class Example {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
System.out.println(map);
}
}
b) What is DatabaseMetaData?
DatabaseMetaData is an interface in JDBC that provides information about the database, such as
its version, tables, and supported SQL features.
Example:
Example:
thread.setPriority(Thread.MAX_PRIORITY);
Q3
a) Write a Java Program to accept n characters from user, store them into
Linkedlist, remove duplicate characters & display in sorted order.
import java.util.*;
} catch (Exception e) {
System.out.println(e);
}} }
import java.sql.*;
import java.util.Scanner;
class BookJDBC {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root",
"password");
Scanner sc = new Scanner(System.in);
c) Write a JSP script to check whether given number is perfect or not &
display the result in yellow colour.
<%@ page language="java" %>
<html>
<body style="background-color:yellow;">
<form method="post">Enter a Number: <input type="text" name="num">
<input type="submit" value="Check"></form>
<%
String numStr = request.getParameter("num");
if (numStr != null) {
int num = Integer.parseInt(numStr), sum = 0;
for (int i = 1; i < num; i++) if (num % i == 0) sum += i;
out.println("<h2>" + num + (sum == num ? " is" : " is NOT") + " a Perfect Number</h2>");
}
%>
</body>
</html>
a) Write a java program to accept N integer from user store them into suitable
collection and display only even integers.
import java.util.*;
class EvenNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
System.out.print("Enter N: ");
int N = sc.nextInt();
System.out.println("Even Numbers:");
numbers.stream().filter(n -> n % 2 == 0).forEach(System.out::println);
sc.close();
}
}
import java.sql.*;
import java.util.Scanner;
class TeacherJDBC {
public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root",
"password");
Scanner sc = new Scanner(System.in);
con.prepareStatement("INSERT INTO teacher VALUES (" + id + ", '" + name + "', '" + subject
+ "')").executeUpdate();
sc.close(); con.close();
}
}
c) Write a JSP program to accept user name and greets the user according
to time of system.
<%@ page language="java" %>
<html>
<body>
<form method="post">
Name: <input type="text" name="user">
<input type="submit" value="Greet">
</form>
<%
String user = request.getParameter("user");
if (user != null) {
int hour = new java.util.Date().getHours();
String greet = (hour < 12) ? "Good Morning" : (hour < 18) ? "Good Afternoon" : "Good
Evening";
out.println("<h2>" + greet + ", " + user + "!</h2>");
}
%>
</body>
</html>
b) Write a java program in multithreading to display all the numbers between
1 to 10. Each number should display after 2 seconds.
import java.sql.*;
import java.util.Scanner;
class StudentJDBC {
public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college",
"root", "password");
Scanner sc = new Scanner(System.in);
sc.close(); con.close();
}
}
c) Write a jsp script to check the given number is prime or not. Display the
result in blue color.
<%@ page language="java" %>
<html>
<body style="color:blue;">
<form method="post">Enter a Number: <input type="text" name="num">
<input type="submit" value="Check"></form>
<%
String numStr = request.getParameter("num");
if (numStr != null) {
int num = Integer.parseInt(numStr), i, flag = 0;
for (i = 2; i <= num / 2; i++) if (num % i == 0) { flag = 1; break; }
out.println("<h2>" + num + (flag == 0 && num > 1 ? " is" : " is NOT") + " Prime</h2>");
}
%>
</body> </html>
a) Write a java program to accept 'N' student name from user, store them in
Linked list collection and display in reverse order.
import java.util.*;
class ReverseStudents {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList<String> students = new LinkedList<>();
System.out.print("Enter N: ");
for (int i = sc.nextInt(); i-- > 0; sc.nextLine()) students.addFirst(sc.nextLine());
students.forEach(System.out::println);
}
}
class StudentJDBC {
public static void main(String[] args) throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college",
"root", "password");
Scanner sc = new Scanner(System.in);
System.out.print("Roll No: "); int rn = sc.nextInt();
sc.nextLine();
System.out.print("Name: "); String name = sc.nextLine();
System.out.print("Percentage: "); float perc = sc.nextFloat();
con.createStatement().executeUpdate("INSERT INTO student VALUES (" + rn + ", '" + name
+ "', " + perc + ")");
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM student");
while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getFloat(3));
}
}
c) Write a JSP program to accept username & password, if username &
password is same then display "Login sucessful" message on the browser
other - wise display "Login failed" message.
<%@ page language="java" %>
<form method="post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" value="Login">
</form>
Q4
a) Life Cycle of Servlet
The Servlet Life Cycle consists of five stages managed by the Servlet Container:
1. Loading & Instantiation – The servlet class is loaded, and an instance is created.
2. Initialization (init()) – Called only once when the servlet is first loaded.
3. Request Handling (service()) – Handles client requests (doGet(), doPost()).
4. Destruction (destroy()) – Called before removing the servlet from memory.
5. Garbage Collection – The servlet object is removed when not needed.
Diagram Representation:
import java.awt.*;
import javax.swing.*;
public BlinkingText() {
label = new JLabel("Blinking Text", JLabel.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 30));
add(label);
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
new Thread(this).start();
}
Explanation:
JDBC allows Java programs to connect to a database and perform operations like inserting,
updating, and retrieving data.
JDBC Steps:
import java.sql.*;
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getDouble(3));
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Explanation:
1. New: A new thread begins its life cycle in the new state. It remains in this state until the program
starts the thread. It is also referred to as a born thread. The thread is in new state if you create an
instance of Thread class but before the invocation of start() method.
2. Runnable: The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3. Running: The thread is in running state if the thread scheduler has selected it.
4. Non-Runnable (Blocked): This is the state when the thread is still alive, but is currently not
eligible to run.
5. Terminated: A thread is in terminated or dead state when its run() method exits.
New
Non-Runnable
( Blocked )
Running
sleep, block on I/O, wait
run() method for lock, suspend, wait
exits
Terminated
c) Differentiate between statement & prepared statement interface.
Feature Statement PreparedStatement
SQL Compilation Compiled each time. Precompiled once, reused with parameters.
Performance Slower for repeated queries. Faster for multiple executions.
SQL Injection Safety Vulnerable (string concatenation). Safer (uses parameterized queries).
Syntax No placeholders. Uses ? placeholders for parameters.
Use Case Static SQL queries. Dynamic queries with parameters.
Example:
• Statement:
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM users WHERE id = " + userId);
• PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id =
?");
pstmt.setInt(1, userId);
pstmt.execute();
Initialization jsplnit()
request lifecycle
Request
Response
jspDestroy()
Shutdown
b) Explain synchronization with an example.
Synchronization in Java is a mechanism that allows only one thread to access a shared resource
at a time. It prevents race conditions and ensures data consistency when multiple threads try to
modify the same resource.
• If multiple threads access a shared resource (e.g., a bank account, file, or database), data
inconsistency may occur.
• Synchronization ensures that only one thread can execute a critical section at a time
Example -
class Counter {
synchronized void count() {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Session tracking is a technique used to maintain user data across multiple requests in a web
application. Since HTTP is stateless, session tracking helps identify and manage user
interactions.
Cookies – Stores user session data in a small file on the client’s browser.
Hidden Fields – Stores data inside HTML forms, passed with each request.
URL Rewriting – Appends session ID to the URL.
HTTP Session (Best Method) – Uses HttpSession to store session data on the server.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
class UpdateSalary {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname",
"username", "password");
PreparedStatement pst = con.prepareStatement("UPDATE Emp SET Esal = ? WHERE
Eno = ?");
Scanner sc = new Scanner(System.in);
System.out.print("Enter Employee Number: ");
int eno = sc.nextInt();
System.out.print("Enter New Salary: ");
double sal = sc.nextDouble();
pst.setDouble(1, sal);
pst.setInt(2, eno);
int rows = pst.executeUpdate();
if (rows > 0) System.out.println("Salary updated successfully.");
else System.out.println("Employee not found.");
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
c) Write a java program to delete the details of given teacher & display
remaining records from Teacher Table. Assume teacher table (tid, tname,
subject) already created.
import java.sql.*;
con.close();
}
}
Q5
Spring Framework is widely used in enterprise applications due to its flexibility and modular
architecture. Here are three key applications:
1. Web Applications – Spring MVC helps develop dynamic web applications with features
like form handling, validation, and security. Example: E-commerce websites.
2. Microservices Development – Spring Boot simplifies building microservices, making
applications lightweight, fast, and scalable. Example: Cloud-based applications.
3. Enterprise Applications – Used in banking, healthcare, and finance for handling large-
scale data and secure transactions. Example: Banking systems for loan processing.
b) Difference Between JSP & Servlet (3 Marks)
JDBC (Java Database Connectivity) is an API that allows Java applications to interact with
databases. It has four main components:
b) Write a java program to accept ‘n’ numbers from user, store them into LinkedList
collection. Display only odd numbers.
import java.util.*;
class OddNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList<Integer> list = new LinkedList<>();
System.out.print("Enter n: ");
int n = sc.nextInt();
System.out.println("Enter numbers:");
while (n-- > 0) list.add(sc.nextInt());
list.stream().filter(x -> x % 2 != 0).forEach(x -> System.out.print(x + " "));
}
}
a) What is Spring Framework? Explain its Advantages.
Spring Framework is a Java-based framework used for building enterprise applications. It provides
support for dependency injection, aspect-oriented programming, and integration with various
technologies like Hibernate and JDBC.
1. Client Request – A web browser sends a request to the server for a servlet.
2. Servlet Container – The server passes the request to the servlet container (like Tomcat).
3. Servlet Loading – The container loads the servlet if it is not already loaded.
4. Servlet Initialization – Calls the init() method once when the servlet is created.
5. Request Handling – The container calls the service() method to process requests.
6. Response Generation – The servlet generates an HTML response and sends it back to the
client.
7. Servlet Destruction – When no longer needed, destroy() is called before removing the
servlet.
b) Write a java program to accept 'n' names from user store them into Array
List, sort them in ascending order and display it.
import java.util.*;
class SortNames {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> names = new ArrayList<>();
System.out.print("Enter n: ");
int n = sc.nextInt();
sc.nextLine();
System.out.println("Enter names:");
for (int i = 0; i < n; i++) names.add(sc.nextLine());
Collections.sort(names);
System.out.println("Sorted names: " + names);
}
}
a) Architecture of Spring
The Spring Framework follows a layered architecture, consisting of multiple modules that provide
various functionalities:
1. Directives – Provide global settings for the JSP page. Example: <%@ page language="java"
%>.
2. Declarations – Declare variables and methods using <%! ... %>.
3. Scriptlets – Contain Java code inside <% ... %>.
4. Expressions – Output values dynamically using <%= ... %>.
5. Implicit Objects – Predefined objects like request, response, session, etc.
6. Standard Actions – Built-in tags like <jsp:include> and <jsp:forward>.