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

java sem 6

The document provides an overview of various Java concepts including the List Interface, JDBC, Threads, Servlets, JSP, and the Spring Framework. It explains key functionalities, differences between data structures like ArrayList and LinkedList, and methods used in inter-thread communication. Additionally, it covers the usage of cookies, session management, and the advantages of JSP over Servlets.

Uploaded by

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

java sem 6

The document provides an overview of various Java concepts including the List Interface, JDBC, Threads, Servlets, JSP, and the Spring Framework. It explains key functionalities, differences between data structures like ArrayList and LinkedList, and methods used in inter-thread communication. Additionally, it covers the usage of cookies, session management, and the advantages of JSP over Servlets.

Uploaded by

ajj919611
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

a) Define List Interface.

→ 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.
c) How to start a Thread? →A thread in Java can be started using the start() method after creating
a thread using Thread class or Runnable interface. Example:
Thread t = new Thread(new MyRunnable());
t.start();
This will execute the run() method in a separate thread.
d) List the types of Servlets. →There are two types of Servlets: 1] Generic Servlet – Works with any
protocol (not specific to HTTP). 2] HTTP Servlet – Specially designed for handling HTTP requests.
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 <% %>.
f) What is Spring Framework? →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).
h) What is the use of forName()?→The Class.forName("classname") method is used to load a
class dynamically at runtime. It is commonly used in JDBC to load the database driver.
i) Write the purpose of join(). →The join() method in Java is used to pause the execution of the
current thread until another thread finishes its execution.
j) How to activate a Session in Servlet? →A session in a Servlet can be activated using:
HttpSession session = request.getSession(); This method creates a new session or returns an existing
one.
a) Define Map Interface. →A Map interface in Java stores key-value pairs where each key is unique. It
helps in fast data retrieval using keys.
b) What is use of wait()?→ The wait() method pauses a thread until another thread calls notify(). It
helps in thread synchronization.
c) What is use of getConnection()? →The getConnection() method in JDBC is used to establish a
connection between a Java application and a database.
d) What is scriplet? → A scriptlet is Java code written inside a JSP page using <% and %>. It allows
dynamic content generation in web pages.
e) What is purpose of JSP directives? → JSP directives (<%@ ... %>) provide instructions to the
JSP engine, such as importing packages and defining page settings.
f) Define Spring Framework. → Spring Framework is a Java framework for building enterprise
applications. It provides features like dependency injection and MVC architecture.
g) Give the name of JDBC API. → JDBC API includes DriverManager, Connection, Statement,
PreparedStatement, and ResultSet for database operations.
h) Define Iterator Interface. → The Iterator interface allows traversing elements of a collection one
by one in Java. It provides methods like hasNext() and next().
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.
b) Give the name of JDBC API. → JDBC API includes DriverManager, Connection, Statement,
PreparedStatement, and ResultSet for database interactions.
c) What is interthread communication? → Interthread communication allows threads to
communicate with each other using methods like wait(), notify(), and notifyAll().
d) What is Servlet? → A Servlet is a Java program that runs on a web server and handles client
requests, usually for web applications.
e) How to represent an expression in JSP? → In JSP, an expression is represented using <%=
expression %>, which evaluates and displays the result on the webpage.
f) List modules in Spring. → Spring modules include Core, AOP (Aspect-Oriented Programming),
JDBC, ORM, Web MVC, and Security.
g) Which interface is implemented by HashSet class? → The HashSet class implements the Set
interface in Java.
h) What is use of getConnection()? → The getConnection() method in JDBC is used to establish a
connection between a Java application and a database.
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.
b) Define Thread Priority. → Thread priority determines the order in which threads are scheduled for
execution. Higher priority threads are executed before lower priority ones.
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.
f) Write any one application of Spring. → Spring is used to develop enterprise web applications,
such as banking or e-commerce platforms, using Spring MVC.
g) What is use of join() method? → The join() method in Java makes a thread wait until another
thread finishes its execution, ensuring sequential execution.
h) Define HashTable. → A HashTable in Java is a data structure that stores key-value pairs and
synchronizes access for thread safety.
i) What is use of commit() method? → The commit() method in JDBC saves all changes made to
the database in a transaction permanently.
j) List any two implicit objects in JSP. → Two implicit objects in JSP are request (for handling
client data) and response (for sending output to clients).
a) What is use of CallableStatement? → CallableStatement is used in JDBC to call stored
procedures in a database and execute SQL queries with parameters.
b) What is Thread? → A thread is a lightweight process that runs independently within a program,
allowing multitasking.
c) How Servlet is different from CGI? → Servlets are Java-based, platform-independent, and run
within a server, whereas CGI (Common Gateway Interface) creates a new process for each request,
making it slower.
d) Define Set. → A Set in Java is a collection that stores unique elements and does not allow
duplicates.
e) List any two parameters using Scriptlet. → Two parameters accessed in a scriptlet are
request.getParameter("name") and request.getParameter("email").
f) Define Spring. → Spring is a Java framework for building enterprise applications, providing
features like dependency injection and MVC architecture.
g) Which interface is implemented by TreeSet class? → The TreeSet class implements the
NavigableSet and SortedSet interfaces.
h) List any two methods of Statement interface. → Two methods of the Statement interface are
executeQuery() (for retrieving data) and executeUpdate() (for updating data).
i) Write the purpose of yield(). → The yield() method in Java pauses the current thread, allowing
other threads with equal or higher priority to execute.
j) What is Cookie? → A cookie is a small piece of data stored in a web browser to track user
sessions and preferences.

ArrayList LinkedList
ArrayList internally uses dynamic array to store LinkedList internally uses doubly linked list to
the elements. store the elements.
ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque
interfaces
ArrayList is better for storing and accessing LinkedList is better for manipulating data.
data.
Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses array. If any element is removed ArrayList because it uses doubly linked list so
from the array, all the bits are shifted in memory. no bit shifting is required in memory.

GET POST
In case of Get request, only limited amount of In case of post request, large amount of data
data can be sent because data is sent in can be sent because data is sent in body
header.
Get request is not secured because data is Post request is secured because data is not
exposed in URL bar exposed in URL bar.
Get request can be bookmarked. Post request cannot be bookmarked.
Get request is more efficient and used more Post request is less efficient and used less
than Post. than get.

JSP Servlet
JSP is a webpage scripting language, Servlets are Java programs that are already
generally used to create the dynamic web compiled and which also create dynamic web
content. content.
JSP is typically more oriented towards Servlet is more oriented towards processing
displaying information information.
JSP acts as a viewer. Servlet acts as a controller.
JSP has Implicit objects. Servlets does not have such type of objects.

LIST SET
Maintains insertion order No guaranteed order (except LinkedHashSet,
TreeSet
Allows duplicates Does not allow duplicates
Supports index-based access No index-based access
When order and duplicates matter When unique elements are needed
Statement PreparedStatement

Writes SQL directly in the code QL is precompiled with placeholders (?)


Manual string concatenation Uses setter methods like setInt(), setString()
Slower for repeated execution Faster due to precompilation and caching
More prone to SQL injection Safer and prevents SQL injection

Array List Linked List


Slower (requires shifting elements) Faster (especially in the middle of the list)
Faster (uses array, supports random access) Slower (needs node traversal)
Less memory (stores only data) More memory (stores data + pointers)
Uses dynamic array Uses doubly linked list

sleep( ) interrupt( ).
Pauses the execution of the current thread Signals a thread to stop or interrupt its work
Thread class (as a static method) Thread class (as an instance method)
Thread.sleep(milliseconds) thread.interrupt()
Temporarily pauses the thread Interrupts a sleeping, waiting, or running
thread

b) What is ResultSet Interface? List any two methods. → 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.
Two methods of ResultSet:
next() – Moves the cursor to the next row in the result set. Returns true if a row exists,
otherwise false.
ResultSet rs = stmt.executeQuery("SELECT * FROM students"); while(rs.next()) {
System.out.println(rs.getString("name"));
}
getString(int columnIndex) – Retrieves data from the specified column as a String.
d) List any two implicit objects in JSP. → 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:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("username"); // Fetches data from form input
}
e) State any two methods of inter-thread communication. → 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.
a) How to create a thread? → A thread in Java can be created using two methods:
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().
b) List JDBC drivers. → 1] JDBC-ODBC Bridge Driver – Connects Java applications to an ODBC
database. 2] Native-API Driver – Uses the database’s native API to connect. 3] Network Protocol
Driver – Uses a middleware server to communicate with databases. 4] Thin Driver – Directly
interacts with the database using Java networking protocols.
c) Write any two methods of HttpSession. → 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.
d) What are the applications of Spring? → Spring is used in various applications such as: 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.
b) What is ResultSet interface? List any two fields of it. → The ResultSet interface in JDBC is used
to store and manipulate the results of an SQL query. It provides methods to traverse and retrieve data
from a database. Two fields of ResultSet: 1] TYPE_FORWARD_ONLY – Allows moving forward in the
result set. 2] CONCUR_READ_ONLY – Prevents updating the result set.
c) Write a syntax of doGet(). → protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Code to handle GET request }
d] What are advantages of JSP over Servlet? → 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.
d) How to create a thread in multithreading? → A thread can be created in Java using two
methods: 1] By Extending Thread Class
class MyThread extends Thread { public void run() {
System.out.println("Thread is running");
} }
MyThread t = new MyThread();
t.start();
1. By Implementing Runnable Interface
class MyRunnable implements Runnable { public
void run() {
System.out.println("Thread is running");
}
}
Thread t = new Thread(new MyRunnable());
t.start();
a) Write any two differences between ArrayList and LinkedList.
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.
b) Give any two fields of ResultSet Interface. 1] TYPE_SCROLL_INSENSITIVE – Allows scrolling
through the result set without being affected by database changes. 2] CONCUR_UPDATABLE –
Allows modifying data in the result set
Give any two types of Servlet. → 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.
c) Write a syntax of getCookies() method in Servlet. → Cookie[] cookies request.getCookies();
This retrieves an array of cookies sent by the client in an HTTP request.
a) What is Map interface and how to implement it? → The Map interface in Java is used to store key-
value pairs where each key is unique. It does not allow duplicate keys but allows duplicate values.
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:
DatabaseMetaData dbmd = connection.getMetaData();
System.out.println(dbmd.getDatabaseProductName());
c) Give the name of directives in JSP. 1] Page Directive (<%@ page ... %>) – Defines page-specific
settings. 2] Include Directive (<%@ include ... %>) – Includes content from another file. 3] Taglib
Directive (<%@ taglib ... %>) – Defines custom tag libraries.
d) State the type of Servlet. → 1] Generic Servlet – A protocol-independent servlet. 2] HTTP Servlet
– A servlet designed for HTTP requests (doGet(), doPost()).
e) What are the thread priorities? → Thread priority values range from 1 (MIN_PRIORITY) to 10
(MAX_PRIORITY), with 5 (NORM_PRIORITY) as the default.
Higher priority threads get more CPU time compared to lower priority ones.
Example:
thread.setPriority(Thread.MAX_PRIORITY);
Q] 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. Servlet
Life Cycle Methods public class MyServlet extends HttpServlet {
public void init() { System.out.println("Servlet Initialized"); } public void
service(HttpServletRequest req, HttpServletResponse res) {
System.out.println("Request Processed"); } public void destroy() {
System.out.println("Servlet Destroyed"); } }
Diagram Representation: Loading → init() → service() (multiple times) → destroy() → Garbage
Collection updating, and retrieving data.
JDBC Steps:
1. Load the Driver – Class.forName("com.mysql.cj.jdbc.Driver");
2. Establish Connection – DriverManager.getConnection()
3. Create Statement – Statement stmt = con.createStatement();
4. Execute Query – stmt.executeQuery("SELECT * FROM Employee");
5. Process Results – Using ResultSet
6. Close Connection – con.close();
JDBC Example Program:
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) { try
{ Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDB", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Employee");
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] Loads JDBC Driver to connect Java with MySQL. 2] Connects to Database using
DriverManager.getConnection(). 3] Executes SQL Query using executeQuery(). 4] Displays
Employee Data from the database. 5] Closes Connection after execution.
b) Explain life cycle of thread. → 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.

a) Explain life cycle of JSP. → 1. JSP Compilation: 1] When a browser asks for a
JSP, the JSP engine first checks to see whether it needs to compile the page. 2] If the
page has never been compiled, or if the JSP has been modified since it was last
compiled, the JSP engine compiles the page.
2. JSP Initialization: → When a container loads a JSP it invokes the jspInit() method before servicing
any requests. If we need to perform JSP-specific initialization, override the jspInit() method
3. JSP Execution: → This phase of the JSP life cycle represents all interactions with requests until the
JSP is destroyed. Whenever, a browser requests a JSP and the page has been loaded and initialized,
the JSP engine invokes the _jspService() method in the JSP.
4. JSP Cleanup: → The destruction phase of the JSP life cycle represents when a JSP is being rem
oved from use by a container. The jspDestroy() method is the JSP equivalent of the destroy method for
servlets.
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.
Need for Synchronization: 1] If multiple threads access a shared resource (e.g., a bank account, file,
or database), data inconsistency may occur. 2] 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); }
}
}
public class SyncExample extends Thread {
Counter c;
SyncExample(Counter c) { this.c = c; } public void
run() { c.count(); }
public static void main(String[] args) {
Counter obj = new Counter(); new
SyncExample(obj).start(); new
SyncExample(obj).start();
}
}
a) Three Applications of Spring →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 largescale data and secure transactions. Example: Banking systems for loan processing.
a) Explain JDBC Architecture → JDBC (Java Database Connectivity) is an API that allows Java
applications to interact with databases. It has four main components: 1] JDBC Driver – Connects Java
applications to databases. 2] Connection – Establishes a link between Java and the database. 3]
Statement – Executes SQL queries. 4] ResultSet – Stores and retrieves query results.
JDBC works in two ways: 1] Two-tier Architecture – Java application directly connects to the database.
2] Three-tier Architecture – Uses an intermediate server between the Java application and the
database.
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.
Advantages of Spring Framework: 1] Lightweight – Uses minimal memory and is fast. 2] Modular –
Can use only needed modules instead of the entire framework. 3] Dependency Injection (DI) –
Reduces tight coupling between components. 4] Transaction Management – Simplifies database
transactions. 5] Integration Support – Works with Hibernate, JPA, Struts, etc.
Execution Process of Servlet Application → 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.
Architecture of Spring → The Spring Framework follows a layered architecture, consisting of
multiple modules that provide various functionalities: 1] Core Container – Manages beans and
dependency injection (DI). 2] AOP (Aspect-Oriented Programming) – Handles cross-cutting
concerns like logging and security. 3] Data Access Layer – Provides integration with databases
using JDBC, Hibernate, JPA, etc. 4] Web Layer – Supports MVC (Model-View-Controller)
architecture for web applications. 5] Security Module – Manages authentication and authorization. 6]
Spring Boot – Simplifies application development with built-in configurations.
This layered structure makes Spring flexible and modular.
Components of JSP (JavaServer Pages) → JSP consists of the following components: 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>.

1 )Write a JDBC program to accept details of for (char c = 'A'; c <= 'Z'; c++) {
Book (B_id, B_name, B_cost) from user & System.out.println(c); try {
display it. import java.sql.*; import Thread.sleep(2000); // 2 seconds
java.util.Scanner; public class BookDetails { } catch (InterruptedException e) {
public static void main(String[] args) throws System.out.println("Thread interrupted");
Exception { }
Scanner sc = new Scanner(System.in); } }
System.out.print("Enter ID: "); int id = sc.nextInt();
sc.nextLine(); public static void main(String[] args) {
System.out.print("Enter Name: "); String new AlphabetThread().start();
name = sc.nextLine(); }}
System.out.print("Enter Cost: "); float cost = 6)Write a java program in multithreading to
sc.nextFloat(); display all the numbers between 1 to 10. Each
Class.forName("com.mysql.cj.jdbc.Driver"); number should display after 2 seconds
Connection con = public class NumThread extends Thread {
DriverManager.getConnection("jdbc:mysql://l public void run() { for (int i = 1; i <=
ocalhost:3306/your_db", "user", "pass"); 10; i++) { System.out.println(i);
PreparedStatement ps = try { Thread.sleep(2000); } catch
con.prepareStatement("INSERT INTO books (Exception e) {}
VALUES (?, ?, ?)"); } }
ps.setInt(1, id); ps.setString(2, name); public static void main(String[] args) {
ps.setFloat(3, cost); ps.executeUpdate(); new NumThread().start();
ResultSet rs = }}
con.createStatement().executeQuery("SELE CT *
FROM books WHERE B_id=" + id);
while (rs.next()) System.out.println("ID: "
+ rs.getInt(1) + ", Name: " + rs.getString(2) +
", Cost: " + rs.getFloat(3));
con.close();
}}
2) Write a java program in multithreading to
display all the alphabets between ‘A’ to ‘Z’.
Each alphabet should display after two
seconds. public class AlphabetThread extends
Thread
{ public void run() {
3) Write a JSP script to check whether given public class ServerInfoServlet extends
number is perfect or not & display the result HttpServlet { public void
in yellow colour doGet(HttpServletRequest req,
<%@ page language="java" %> HttpServletResponse res) throws IOException {
<html> res.setContentType("text/html"); PrintWriter
<body> out = res.getWriter();
<form method="post">
Enter a number: <input type="text" String serverName = req.getServerName();
name="num"> int serverPort = req.getServerPort();
<input type="submit" value="Check"> String serverInfo =
</form> getServletContext().getServerInfo();
<%
String input = request.getParameter("num"); out.println("<html><body>");
if (input != null) { int n = out.println("<h3>Server Information:</h3>");
Integer.parseInt(input); int sum = out.println("<p><b>Server Name:</b> "
0; for (int i = 1; i < n; i++) { + serverName + "</p>");
if (n % i == 0) sum += i; out.println("<p><b>Server Port:</b> " +
} serverPort + "</p>");
String result = (sum == n) ? "Perfect out.println("<p><b>Server Version:</b> "
Number" : "Not a Perfect Number"; + serverInfo + "</p>");
%> out.println("</body></html>");
<h3 style="color:yellow;"><%= result }}
%></h3> 10)Write a java program to accept N integer
<% }%></body></html> from user store them into suitable collection
4)Write a servlet program to count the and display only even integers. import
number of times a servlet has been java.util.*; public class EvenNumbers { public
invoked [use cookies] static void main(String[] args) { Scanner sc
import java.io.*; import = new Scanner(System.in);
javax.servlet.*; List<Integer> nums = new ArrayList<>();
import javax.servlet.http.*; System.out.print("How many numbers?
"); int n = sc.nextInt(); for
public class VisitServlet extends HttpServlet { (int i = 0; i < n; i++)
public void doGet(HttpServletRequest req, nums.add(sc.nextInt());
HttpServletResponse res) throws IOException { System.out.println("Even numbers:");
res.setContentType("text/html"); nums.stream().filter(x -> x % 2 ==
int count = 1; for (Cookie c : 0).forEach(System.out::println);}}
req.getCookies() == null ? new Cookie[0] :
req.getCookies()) { if
(c.getName().equals("count")) count
= Integer.parseInt(c.getValue()) + 1;
}
res.addCookie(new Cookie("count",
String.valueOf(count)));
res.getWriter().println("<h3>You visited "
+ count + " times.</h3>");
}}
8)Write a Servlet program to get information
about the server such as name, port number
and version of server. import java.io.*; import
javax.servlet.*;
import javax.servlet.http.*;
11) Write a Java program to accept details of interface). Assume Emp table (Eno,
teacher (Tid, Tname, Tsubject), *-' store it into Ename,Esal) is already created.
database and display it' import java.sql.*; import java.sql.*; import
import java.util.*; public class TeacherDB { java.util.*; public class
public static void main(String[] args) throws UpdateSalary {
Exception { public static void main(String[] args) throws
Scanner sc = new Scanner(System.in); Exception { Scanner sc = new
System.out.print("ID: "); int id = sc.nextInt(); Scanner(System.in);
sc.nextLine(); System.out.print("Enter Employee No:
System.out.print("Name: "); String name "); int eno = sc.nextInt();
= sc.nextLine(); System.out.print("Enter New Salary: "); float
System.out.print("Subject: "); String sub sal = sc.nextFloat(); Connection
= sc.nextLine(); con=DriverManager.getConnection("jdbc:mys
Connection con = ql://localhost:3306/your_db", "user", "pass");
DriverManager.getConnection("jdbc:mysql://l PreparedStatement ps =
ocalhost:3306/your_db", "user", "pass"); con.prepareStatement("UPDATE Emp SET
PreparedStatement ps = Esal=? WHERE Eno=?");
con.prepareStatement("INSERT INTO teacher ps.setFloat(1, sal); ps.setInt(2, eno);
VALUES (?, ?, ?)"); ps.setInt(1, id); int rows = ps.executeUpdate();
ps.setString(2, name); ps.setString(3, sub); System.out.println(rows > 0 ? "Salary
ps.executeUpdate(); updated!" : "Employee not found.");
var rs =
con.createStatement().executeQuery("SELE CT * con.close();
FROM teacher WHERE Tid=" + id); while }}
(rs.next()) 14)Write a java program to accept 'N' student
System.out.println(rs.getInt(1)+" name from user, store them in Linked list
"+rs.getString(2)+" "+rs.getString(3)); collection and display in reverse order
con.close(); import java.util.*; public class ReverseStudents
}} { public static void main(String[] args) {
12) Write a JSP program to accept user Scanner sc = new Scanner(System.in);
name and greets the user according to LinkedList<String> students = new
time of system. <%@ page LinkedList<>();
import="java.util.*" %> System.out.print("How many students?
<html><body> "); int n = sc.nextInt(); sc.nextLine();
<form method="post"> Enter your
name: <input type="text" for (int i = 0; i < n; i++)
name="uname"> students.add(sc.nextLine());
<input type="submit" value="Greet"> System.out.println("Names in reverse:");
</form> ListIterator<String> it =
<% students.listIterator(students.size()); while
String name = (it.hasPrevious())
request.getParameter("uname"); if(name != System.out.println(it.previous()); }}
null && !name.isEmpty()) { int hour =
Calendar.getInstance().get(Calendar.HOUR_
OF_DAY);
String greet = (hour < 12) ? "Good Morning" :
(hour < 18) ? "Good Afternoon" :
"Good Evening";
%> <h2><%= greet %>, <%= name
%>!</h2><% } %></body></html>
13)Write a lava program'to'update the salary
of a given employee'{use prepared statement
15) Write a java program to accept details of con.close();
student (rollno, name, percentage). }}
Store it into database & display it. c) Write a JSP program to accept a number
import java.sql.*; import from user and convert it into
java.util.*; public class words (eg 123 – o/p → One Two Three).
StudentDB { <%@ page language="java"
public static void main(String[] args) throws contentType="text/html; charset=ISO-8859-1"
Exception { pageEncoding="ISO-
Scanner sc = new Scanner(System.in); 8859-1"%>
System.out.print("Roll No: "); int roll = sc.nextInt(); <%@ page import="java.util.*" %>
sc.nextLine(); <html>
System.out.print("Name: "); String name <head>
= sc.nextLine(); <title>Number to Words</title>
System.out.print("Percentage: "); float </head>
perc = sc.nextFloat(); Connection con = <body>
DriverManager.getConnection("jdbc:mysql://l <form method="post">
ocalhost:3306/your_db", "user", "pass"); Enter Number: <input type="text" name="num">
PreparedStatement ps = <input type="submit" value="Convert">
con.prepareStatement("INSERT INTO student
</form>
<%
VALUES (?, ?, ?)"); ps.setInt(1, roll);
String num = request.getParameter("num");
ps.setString(2, name); ps.setFloat(3, perc);
if (num != null && !num.isEmpty()) {
ps.executeUpdate(); ResultSet rs =
String[] words = {"Zero", "One", "Two", "Three",
con.createStatement().executeQuery("SELE
"Four", "Five", "Six", "Seven", "Eight",
CT * FROM student WHERE rollno = " + roll);
"Nine"};
while (rs.next())
out.print("Number in Words: ");
System.out.println(rs.getInt(1) + " " +
for (char c : num.toCharArray()) {
rs.getString(2) + " " + rs.getFloat(3));
out.print(words[Character.getNumericValue(c)] +
con.close(); " ");
}} }
17) Write a java program to delete the details }
of given teacher & display remaining records %>
from Teacher Table. Assume teacher table </body>
(tid, tname, subject) already created import </html>
java.sql.*; import java.util.*; public class
TeacherDelete {
public static void main(String[] args) throws
Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Enter ID to delete: "); int id
= sc.nextInt();

Connection con =
DriverManager.getConnection("jdbc:mysql://l
ocalhost:3306/your_db", "user", "pass");
con.prepareStatement("DELETE FROM Teacher
WHERE tid=?").executeUpdate(id);
var rs =
con.createStatement().executeQuery("SELE
CT * FROM Teacher");
while (rs.next())
System.out.println(rs.getInt(1)+"
"+rs.getString(2)+" "+rs.getString(3));
1] Student roll number program from user. JLabel label;
Display that details. boolean visible = true;
import java.sql.*; public BlinkingText() {
import java.util.Scanner; label = new JLabel("Blinking Text",
class StudentJDBC { JLabel.CENTER);
public static void main(String[] args) throws label.setFont(new Font("Arial", Font.BOLD,
Exception { 30));
Connection con = add(label);
DriverManager.getConnection("jdbc:mysql://local setSize(300, 200);
host:3306/college", setDefaultCloseOperation(EXIT_ON_CLOSE);
"root", "password"); setVisible(true);
Scanner sc = new Scanner(System.in); new Thread(this).start();
System.out.print("Roll No: "); int rn = sc.nextInt(); }
sc.nextLine(); public void run() {
System.out.print("Name: "); String name = try {
sc.nextLine(); while (true) {
System.out.print("Percentage: "); float perc = visible = !visible;
sc.nextFloat(); label.setVisible(visible);
con.createStatement().executeUpdate("INSERT Thread.sleep(500);
INTO student VALUES (" + rn + ", '" + name }
+ "', " + perc + ")"); } catch (InterruptedException e) {}
ResultSet rs = }
con.createStatement().executeQuery("SELECT * public static void main(String[] args) {
FROM student"); new BlinkingText();
while (rs.next()) System.out.println(rs.getInt(1) + " }
" + rs.getString(2) + " " + rs.getFloat(3)); }
sc.close(); con.close();
}
}
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>
<% if (request.getParameter("user") != null)
out.println("<h2>" +
(request.getParameter("user").equals(request.getPa
rameter("pass")) ?
"Login Successful" : "Login Failed") + "</h2>");
%>
b) Java Program using Multi-Threading to Blink
Text on Frame
This program makes text blink using Threads in a
GUI Frame.
import java.awt.*;
import javax.swing.*;
public class BlinkingText extends JFrame
implements Runnable {

You might also like