Advanced Java Concepts Explained
Advanced Java Concepts Explained
When working with JDBC (Java Database Connectivity), the Connection interface provides several
methods for managing database connections. Two commonly used methods are:
String sql = "INSERT INTO employees (name, age) VALUES (?, ?)";
[Link](1, "John");
[Link](2, 30);
[Link]();
The sleep() method in Java is used to pause the execution of a thread for a specified amount of time. It
belongs to the Thread class.
Syntax: [Link](milliseconds);
1. Pauses Execution: Temporarily stops the current thread but does not release the lock.
2. Checked Exception: It throws InterruptedException, which must be handled using try-catch.
3. Does Not Affect Other Threads: Only the thread that calls sleep() is paused; others continue execution.
4. Can Be Interrupted: Another thread can wake up a sleeping thread using interrupt().
You can set the priority of a thread using the setPriority(int newPriority) method from the Thread class.
Establishes a connection with the server using IP Address and Port Number.
Example Usage:
2. ServerSocket (Server-Side)
Example Usage:
5) IP address.
An IP (Internet Protocol) Address is a unique numerical label assigned to each device (computer, server,
smartphone, etc.) connected to a network. It helps in identifying and locating devices for communication
over the internet or a local network.
1. When you open a website, your device sends a request to a DNS server to get the IP address of the
website.
2. The DNS server translates the domain name (e.g., [Link]) into an IP address (e.g., [Link]).
3. Your request is routed through the internet to the server hosting the website.
4. The server responds, and you see the website on your browser.
The doGet() method is part of the HttpServlet class and is used to handle HTTP GET requests in Java
Servlets.
Syntax of doGet()
When you want to retrieve data without modifying the server state.
For search engines, form submissions (without sensitive data), API calls, etc.
The service() method in Java Servlets is responsible for handling incoming HTTP requests and generating
responses. It is defined in the HttpServlet class and is automatically called by the servlet container (e.g.,
Tomcat) whenever a request is received.
Method Signature
a) HttpServletRequest request
b) Represents the client's HTTP request.
c) Contains request headers, parameters, cookies, and session data.
d) Methods like getParameter(), getHeader(), getSession() help retrieve request information.
HttpServletResponse response
8) JSP
JSP (JavaServer Pages) is a server-side technology used to create dynamic web pages in Java. It allows
developers to write HTML and Java code together, making web development easier compared to servlets.
Hibernate is a powerful ORM (Object-Relational Mapping) framework for Java that simplifies database
interaction. It allows Java objects to be mapped to database tables, enabling database operations using
Java objects instead of SQL queries.
1. Java objects (POJOs) are mapped to database tables using Hibernate configuration.
2. Hibernate automatically generates SQL queries based on Java object operations.
3. Saves, retrieves, updates, and deletes data without writing SQL manually.
The getConnection() method in JDBC (Java Database Connectivity) is used to establish a connection
between a Java application and a database. It is a static method of the DriverManager class.
Syntax
public static Connection getConnection(String url, String user, String password) throws SQLException
Parameters
url → The database URL (e.g., MySQL, PostgreSQL, Oracle, etc.).
user → The username for the database.
password → The password for the database
A cookie is a small piece of data stored in a user's browser to track user activity and preferences. In Java
web applications, cookies help manage user sessions, authentication, and personalization.
Runnable is a functional interface in Java used for creating threads. It provides a way to define a thread’s
execution logic without extending the Thread class.
Thread priority in Java determines the order in which threads are scheduled for execution. Higher priority
threads get more CPU time than lower priority threads, but thread execution is ultimately controlled by
the JVM and OS scheduler.
HQL (Hibernate Query Language) is an object-oriented query language used in Hibernate to interact with
databases. It is similar to SQL but works with Hibernate entities (objects) instead of database tables.
JSP directives provide global settings and configurations for a JSP page. They control the processing of
the JSP by the JSP container.
16) Networking
Networking in Java allows communication between two or more devices over a network. Java provides a
rich set of APIs in the [Link] package to develop network applications such as:
Client-Server Applications
Socket Programming
URL Handling (Web Communication)
Datagram Communication (UDP)
To create a database connection in Java, we use the getConnection() method of the DriverManager class
from the [Link] package.
Syntax of getConnection()
Method Description
getConnection(String url, String user, String Connects using a JDBC URL, username, and
password) password.
getConnection(String url, Properties properties) Uses Properties object for flexible configurations.
The yield() method in Java temporarily pauses the execution of the current thread, allowing other threads
of the same or higher priority to execute. It is part of the Thread class.
It is a static method.
It belongs to the Thread class ([Link]).
It does not guarantee that another thread will run, just suggests to the scheduler.
How yield() Works
The Socket class in Java is used for client-side communication in network programming. It allows a
client to connect to a server over TCP (Transmission Control Protocol).
Package: [Link]
20) Servlet
A Servlet is a Java program that runs on a web server and handles client requests (usually from a web
browser) and generates dynamic web content. It is part of Java EE (Jakarta EE) and is used to create web
applications.
Servlets work on the server-side and extend the functionality of web servers.
In JDBC (Java Database Connectivity), a Statement is an interface used to execute SQL queries against a
database. It is part of the [Link] package and provides methods to send SQL commands to the database
and process the results.
1. Statement ([Link])
o This is used to execute static SQL queries (queries that do not change at runtime).
o It is best suited for one-time execution.
o It does not support parameterized queries.
o Example:
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM employees");
2. PreparedStatement ([Link])
o Used for precompiled SQL queries with parameters.
o Supports parameterized queries, preventing SQL injection attacks.
o It is more efficient because the SQL query is compiled only once.
o Example:
String sql = "SELECT * FROM employees WHERE department = ?";
PreparedStatement pstmt = [Link](sql);
[Link](1, "IT");
ResultSet rs = [Link]();
3. CallableStatement ([Link])
o Used to execute stored procedures in the database.
o Allows passing IN, OUT, and INOUT parameters.
o Example:
CallableStatement cstmt = [Link]("{call getEmployeeDetails(?)}");
[Link](1, 101);
ResultSet rs = [Link]();
In Java, a thread goes through several states from its creation to termination. These states define the
thread life cycle and are managed by the JVM (Java Virtual Machine).
1. New (Created)
o The thread is created but not started yet.
o Created using Thread class but not invoked using start().
o Example:
Thread t = new Thread();
2. Runnable
o The thread is ready to run but waiting for CPU time.
o Moves to this state after calling start().
o The thread scheduler decides when to run it.
o Example: [Link]();
3. Running
o The thread is executing its task.
o Moves from Runnable → Running when the scheduler assigns CPU.
o Example:
public void run() {
[Link]("Thread is running...");
}
4. Blocked
o The thread is waiting for a resource (like a locked object).
o Moves to this state when trying to access a synchronized block locked by another thread.
New (Thread created)
o Example:
synchronized(obj) {
// Critical section Runnable (Thread ready to run)
}
5. Waiting
o The thread is waiting indefinitely until another thread notifies it. Running (Thread execu ng)
o Can be resumed using notify().
o Example:
synchronized (this) { Waiting
Blocked TimedWaiting
wait(); // Thread goes into waiting state
}
6. Timed Waiting
Terminated (Thread execu on finished)
o The thread is waiting for a specific time.
o Moves to this state using sleep(time), wait(time), join(time), etc.
o Example:
[Link](5000); // Sleep for 5 seconds
7. Terminated (Dead)
o The thread has finished execution or was stopped.
o It cannot be restarted.
o Example: [Link]("Thread has completed execution.");
The Hibernate architecture consists of several components that work together to manage database
operations efficiently.
Key Components of Hibernate Architecture:
2. SessionFactory
Configuration
SessionFactory
Session Transaction
JDBC
Database
Q.4) What is Result set interface in JDBC? Explain methods in Resultset interface.
The ResultSet interface in JDBC (Java Database Connectivity) represents the table of data retrieved from
a database query. It is part of the [Link] package and is used to iterate through and process the results
of a SQL query executed using a Statement or PreparedStatement. A ResultSet object maintains a cursor
pointing to its current row of data. Initially, the cursor is positioned before the first row, and it must be
moved forward using the .next() method to access data.
The ResultSet interface provides various methods for navigating, retrieving, and updating data.
1. Navigation Methods (Moving the Cursor)
Method Description
boolean next() Moves the cursor to the next row. Returns false if there are no more rows.
boolean Moves the cursor to the previous row (works only in TYPE_SCROLL_INSENSITIVE or
previous() TYPE_SCROLL_SENSITIVE result sets).
boolean first() Moves the cursor to the first row.
boolean last() Moves the cursor to the last row.
These methods fetch values from the current row. Each column can be accessed using its column index
(starting from 1) or column name.
Method Description
int getInt(int columnIndex) Retrieves an int value from the specified column.
String getString(String columnName) Retrieves a String value from the column with the given name.
ResultSet can be updatable if created with CONCUR_UPDATABLE. These methods allow updating data
within the ResultSet itself.
Method Description
void updateInt(int columnIndex, int value) Updates an int value in the specified column.
void updateString(String columnName, String value) Updates a String value.
void updateRow() Updates the current row in the database.
void deleteRow() Deletes the current row from the database.
void insertRow() Inserts a new row.
JSP (JavaServer Pages) is a server-side technology used for creating dynamic web pages in Java. It
allows developers to embed Java code inside HTML using special tags (<% %>). JSP is an extension of
Servlets and is used to generate dynamic content, such as retrieving data from databases, handling user
requests, and displaying dynamic web content.
The JSP (JavaServer Pages) life cycle defines the process of how a JSP page is created, executed, and
destroyed by the Java EE web container (Tomcat, JBoss, etc.). It consists of several phases from
translation to destruction.
1. Translation Phase: The JSP file (.jsp) is converted into a Servlet (.java file) by the web container. The JSP
page is checked for syntax errors.
2. Compilation Phase :The translated JSP Servlet (.java) file is compiled into a bytecode class (.class file).
3. Class Loading Phase: The compiled servlet class is loaded into memory by the web container.
4. Instantiation Phase: An instance of the JSP servlet is created.
5. Initialization Phase (jspInit()) : The container calls the jspInit() method once, before handling requests. It
is used for initialization code, such as database connection setup.
6. Request Processing Phase (_jspService()): The container calls _jspService(HttpServletRequest,
HttpServletResponse) for each user request. This method dynamically generates responses by executing
the JSP script.
7. Destruction Phase (jspDestroy()) : When the JSP servlet is no longer needed, the container calls
jspDestroy(). It is used to release resources, such as closing database connections.
In Hibernate, an object (or entity) can exist in three different states during its lifecycle. These states
determine how the object interacts with the database.
1. Transient State: An object is in the transient state if it is created using the new keyword but is not
associated with a Hibernate Session. It is not yet saved in the database. Hibernate does not track changes
to transient objects. The object exists only in memory, and if the application ends, it will be lost
Example:
Employee emp = new Employee(); // Transient state
[Link](101);
[Link]("John Doe");
3. Persistent State: An object is in the persistent state when it is associated with a Hibernate Session.
Hibernate tracks the object's changes and automatically synchronizes them with the database.
Changes to a persistent object are saved automatically. Even after save(), as long as the session is
open, Hibernate tracks changes to the object.
Example:
3. Detached State: An object enters the detached state when the Hibernate Session is closed. It exists in
memory but is no longer tracked by Hibernate. Any modifications to the object will not be saved
automatically. To update a detached object, it must be re-attached using [Link](emp);.
Example:
[Link](); // Object is now detached
[Link]("Updated Name"); // Changes will not be reflected in the DB
Q7) What is session tracking? What are the different ways of session tracking in servlet.
Session Tracking is a mechanism used in Servlets to maintain state (data) between multiple requests
from the same client. HTTP is stateless, meaning each request is independent and does not remember
previous interactions. Session tracking helps retain user-specific data across multiple requests.
1. Cookies
Cookies are small pieces of data stored in the user's browser.
The server sends a cookie with a response, and the browser sends it back with each request.
Used for persistent session tracking.
Example:
Cookie userCookie = new Cookie("username", "JohnDoe");
[Link](3600); // 1 hour
[Link](userCookie);
Example:
<form action="NextServlet" method="post">
<input type="hidden" name="user" value="JohnDoe">
<input type="submit" value="Submit"> </form>
3. URL Rewriting
The session ID is appended to the URL when sending requests.
The server extracts the session ID from the URL to track the session.
Example:
String encodedURL = [Link]("[Link]?user=JohnDoe");
[Link]("<a href='" + encodedURL + "'>Go to Dashboard</a>");
Example:
HttpSession session = [Link]();
[Link]("username", "JohnDoe");
Advantages: Secure (data is stored on the server) Can store complex objects
Disadvantages: Requires more server memory Needs manual session management
Q.8) What is thread Priority? How to set the thread priorities?
Thread priority in Java determines the importance of a thread relative to other threads. The Java Thread
Scheduler uses priorities to decide which thread to execute next, but the actual scheduling depends on
the operating system.
Each thread has a priority, which is an integer value between 1 and 10:
Thread.MIN_PRIORITY = 1 (Lowest priority)
Thread.NORM_PRIORITY = 5 (Default priority)
Thread.MAX_PRIORITY = 10 (Highest priority)
Higher priority threads get more CPU time, but it does not guarantee execution order.
The Connection interface in JDBC (Java Database Connectivity) is used to establish a connection between
a Java application and a database. It is part of the [Link] package and provides methods to interact with
the database, such as executing SQL queries and managing transactions.
Steps:
Method Description
createStatement() Creates a Statement object to execute SQL queries.
prepareStatement(String sql) Creates a PreparedStatement for executing parameterized queries.
commit() Commits the current transaction (used when auto-commit is disabled).
rollback() Rolls back the transaction to the last commit.
setAutoCommit(boolean status) Enables or disables auto-commit mode (default is true).
close() Closes the database connection.
Q.10) Runnable interface.
The Runnable interface in Java is used to create and manage threads. It provides a way to define a task
that can be executed by a thread. Runnable Interface is part of [Link] package. It is implemented by a
class to execute multi-threaded operations. Runnable is the preferred way to create threads in Java. It
allows separation of task definition and execution. [Link](milliseconds) pauses execution for the
given time. Use [Link]().getName() to get the thread name.
It contains a single method:
public void run();
Thread synchronization in Java is a technique used to prevent multiple threads from accessing shared
resources simultaneously, which can cause data inconsistency or race conditions. In a multi-threaded
environment, multiple threads can access the same shared resource (e.g., a file, a bank account balance,
or a database). If two or more threads try to modify it at the same time, it may lead to unexpected results.
1. Synchronized Method: A method can be marked synchronized so that only one thread can access it at a
time.
class Counter {
int count = 0;
synchronized void increment() { // Synchronized method
count++;
}
}
2. Synchronized Block: Instead of synchronizing the entire method, we can synchronize only a critical
section.
class Counter {
int count = 0;
void increment() {
synchronized (this) { // Synchronized block
count++;
}
}
}
Benefits: Synchronizes only necessary code, improving performance. Allows other methods of the same
object to run simultaneously.
In JSP, directives are used to provide global information about the JSP page to the JSP container. They
define page settings, import Java classes, and include files at translation time.
1. page Directive: The page directive provides global settings related to the JSP page, such as:
Syntax:
<%@ page attribute="value" %>
[Link] Directive: The include directive is used to include another JSP file at translation time. It merges
the included file's content into the current page before execution.
Syntax:
<%@ include file="[Link]" %>
Key Points:
The included file is compiled along with the main JSP file.
Useful for including static content (e.g., headers, footers, navigation bars).
Better performance than <jsp:include> for static content.
If the included file is modified, the JSP must be recompiled.
[Link] Directive: The taglib directive is used to define and use custom JSP tags from a tag library (e.g.,
JSTL - JSP Standard Tag Library).
Syntax:
<%@ taglib uri="URI" prefix="prefix" %>
Key Points:
Taglib is required when using JSTL (JSP Standard Tag Library).
It allows reusability of custom tag functionalities.
prefix is a short name for the tag library (c in the example)
Q.13) Explain inter thread communication with an example.
Inter-thread communication in Java allows multiple threads to communicate with each other while
accessing shared resources. This helps in avoiding race conditions and ensuring proper synchronization.
Java provides three methods from the Object class for inter-thread communication:
1. wait() – Makes the current thread wait until another thread notifies it.
2. notify() – Wakes up one waiting thread.
3. notifyAll() – Wakes up all waiting threads.
Example:
class SharedResource {
private boolean flag = false;
new Thread(resource::produce).start();
new Thread(resource::consume).start();
}
}
Output:
Producing...
Consuming...
Q.14) Differentiate between statement and prepared statement interface
The ServerSocket class in Java (in the [Link] package) is used to create a server that listens for
incoming client connection requests on a specified port. Here’s an overview of some of its key methods
along with their syntax and brief explanations:
1. accept()
Description: Waits (blocks) until a client connects and then returns a new Socket object to
communicate with the client.
Syntax: public Socket accept() throws IOException
2. close()
3. getInetAddress()
Description: Returns the local IP address to which this server socket is bound.
Syntax: public InetAddress getInetAddress()
4. getLocalPort()
Description: Returns the port number on which the server socket is listening.
Syntax: public int getLocalPort()
5. getLocalSocketAddress()
Description: Retrieves the local socket address (combining the IP address and port) that this server
socket is bound to.
Syntax: public SocketAddress getLocalSocketAddress()
6. isBound()
Description: Checks if the server socket is bound to an address.
Syntax: public boolean isBound()
7. isClosed()
execute() → Used for both DDL & DML queries (when query type is unknown).
executeQuery() → Used for SELECT queries (returns a ResultSet).
executeUpdate() → Used for INSERT, UPDATE, DELETE, and DDL queries (returns an integer count).
The Socket class in Java (part of the [Link] package) is used for client-side communication in a client-
server architecture. It allows a client to establish a connection to a server and exchange data.
Example:
Server Code:
import [Link].*;
import [Link].*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5000);
Socket socket = [Link]();
BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
[Link]();
[Link]();
}
}
Client code:
import [Link].*;
import [Link].*;
[Link]("Hello Server!");
[Link]("Server: " + [Link]());
[Link]();
}
}
Output:
Server Output:
Client: Hello Server!
Client Output:
Server: Hello Client!
1. Lightweight – Spring is lightweight due to its modular design, which allows developers to use only the
required components.
2. Transaction Management – Provides a powerful abstraction for transaction handling across different
databases.
3. Integration with Other Frameworks – Easily integrates with Hibernate, JPA, Struts, etc.
4. Modular Architecture – Developers can use only necessary modules instead of loading the entire
framework.
5. Spring Boot (Simplified Configuration) – Spring Boot makes application setup and deployment easier
with auto-configuration.
6. Security – Spring Security provides authentication and authorization features.
7. Large Community Support – Well-documented and supported by an active developer community.
Disadvantages of Spring Framework
JSP (JavaServer Pages) provides various tags to simplify the development of dynamic web pages. These
tags help embed Java code inside an HTML page.
1 Directive Tags (<%@ ... %>): Used to provide global information about the JSP page. Types: page, include,
taglib.
Example (Page Directive)
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
Example (Include Directive)
<%@ include file="[Link]" %>
2 Declaration Tag (<%! ... %>): Used to declare variables and methods that are accessible throughout the
JSP page.
Example
<%! int num = 10; %>
<%! String getMessage() { return "Hello JSP!"; } %>
3 Scriptlet Tag (<% ... %>): Allows writing Java code inside a JSP page.
Example
<%
int a = 5, b = 10;
int sum = a + b;
%>
Sum is: <%= sum %>
4 Expression Tag (<%= ... %>): Used to print values directly on the JSP page.
Example
<%
String name = "John";
%>
Welcome, <%= name %>!
5 JSP Action Tags: Used for built-in functionalities like including another JSP, forwarding requests, or
interacting with JavaBeans.
<%
String message = "Welcome to JSP!";
%>
<jsp:include page="[Link]"/>
</body>
</html>
Advantages of Multithreading
1. Better CPU Utilization – Multiple threads allow maximum usage of CPU by running tasks in parallel.
2. Faster Execution – Tasks that can be executed independently complete faster, improving application
performance.
3. Efficient Resource Sharing – Threads of the same process share memory and resources, reducing
overhead.
4. Improved Responsiveness – In GUI applications, background threads prevent the UI from freezing.
5. Parallel Processing – Useful in real-time applications like gaming, multimedia, and web servers.
6. Reduced Context Switching Overhead – Threads have lower context switching costs compared to
processes.
7. Simplifies Complex Tasks – Tasks like web crawling, data processing, and network communication
become more manageable.
Disadvantages of Multithreading
1. Complex Debugging – Multithreaded programs are difficult to debug due to race conditions and
deadlocks.
2. Increased Resource Consumption – Threads consume memory and CPU resources, leading to
performance issues if not managed properly.
3. Race Conditions – Multiple threads accessing shared resources without synchronization can lead to
unpredictable behavior.
4. Deadlocks – Improper synchronization can cause threads to block each other indefinitely.
5. Difficult to Implement – Writing thread-safe code requires careful handling of synchronization and
shared resources.
6. Testing Challenges – Finding concurrency-related bugs is harder than in single-threaded applications.
7. Overhead of Context Switching – Frequent switching between threads can slow down performance if
not optimized properly.
The run() method in Java is used to define the task that a thread will execute. It is part of the Runnable
interface and is overridden in a class implementing Runnable or extending Thread.
Key Points:
The run() method does not create a new thread on its own.
It is executed when the start() method of a thread is called.
If run() is called directly like a normal method, it will execute on the main thread and not create a new
thread.
The Statement interface in JDBC (Java Database Connectivity) is used to execute SQL queries against a
database. It is part of the [Link] package and is commonly used for simple SQL queries that do not
require parameters.
Key Points:
2 Establish a Connection
Connection con = [Link]("jdbc:mysql://localhost:3306/mydb", "root", "password");
3 Create a Statement
Statement stmt = [Link]();
4 Execute Queries
ResultSet rs = [Link]("SELECT * FROM users");
Feature Statement
Purpose Executes SQL queries (SELECT, INSERT, UPDATE, DELETE).
Execution Type Each query is compiled and executed separately.
Vulnerability Prone to SQL Injection.
Performance Slower due to repeated parsing and execution.
Alternative PreparedStatement (recommended for dynamic queries).
Q.23) HttpServlet
HttpServlet is a class in Java Servlet API that helps create web applications by handling HTTP requests
and responses. It extends the GenericServlet class and provides methods to handle different HTTP
request types like GET, POST, PUT, DELETE, etc.
Key Features:
Lifecycle of an HttpServlet
1 Servlet Initialization (init()): Called once when the servlet is first loaded into memory. Used for initializing
resources (e.g., database connections).
2 Request Handling (service(), doGet(), doPost()): Handles client requests and generates responses.
service() method decides which HTTP method (GET, POST, etc.) should be used.
3 Servlet Destruction (destroy()): Called once before the servlet is removed from memory. Used to
release resources (e.g., closing database connections).
4 Garbage Collection (finalize()) (Optional): Called when the servlet object is garbage collected.
Advantages of HttpServlet:
Handles HTTP requests efficiently
Provides built-in request/response management
Reusable and scalable for web applications
Can handle multiple client requests simultaneously
Concept Description
HttpServlet A Java class for handling HTTP requests in web applications.
Lifecycle init(), service(), doGet(), doPost(), destroy()
Methods doGet(), doPost(), doPut(), doDelete()
Deployment Configured via [Link] or @WebServlet annotation.
Use Cases Web pages, form processing, API endpoints, authentication.
1. Write a JSP program to accept Name & age of voter and check whether he/she is eligible for voting or
not.
<%
String name = [Link]("name");
int age = [Link]([Link]("age"));
String message = (age >= 18) ? "eligible" : "not eligible";
%>
<h3>Hello, <%= name %>! You are <span style="color:<%= (age >= 18) ? "green" : "red" %>;"><%= message
%></span> to vote.</h3>
<a href="[Link]">Go Back</a>
2. Write a JDBC program to delete the records of employees whose names are starting with ‘A’ character
import [Link].*;
public class DeleteEmployees {
public static void main(String[] args) {
try (Connection con = [Link]("jdbc:mysql://localhost:3306/yourDB", "root",
"password");
PreparedStatement ps = [Link]("DELETE FROM employees WHERE name LIKE
'A%'")) {
} catch (Exception e) {
[Link]();
}
}
}
3. Write servlet program to accept two numbers from user and print addition of that in blue colour.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
int num1 = [Link]([Link]("num1"));
int num2 = [Link]([Link]("num2"));
int sum = num1 + num2;
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h3 style='color:blue;'>Sum: " + sum + "</h3>");
}
}
4. Write a JDBC program to display the details of employees (eno, ename, department, sal) whose
department is ‘Computer Application’.
import [Link].*;
while ([Link]()) {
[Link]([Link]("eno") + " | " + [Link]("ename") + " | " +
[Link]("department") + " | " + [Link]("sal"));
}
} catch (Exception e) {
[Link]();
}
}
}
import [Link].*;
if ([Link]()) {
[Link]("Total Records: " + [Link](1));
}
} catch (Exception e) {
[Link]();
}
}
}
7. Write a java program to create table student with attributes Rno, Sname, Per
import [Link].*;
[Link](sql);
[Link]("Table 'student' created successfully.");
} catch (Exception e) {
[Link]();
}
}
}
8. Write a JSP application to accept a user name and greet the user.
[Link]
[Link]
Output:
IP Address: [Link]