0% found this document useful (0 votes)
9 views28 pages

Advanced Java Concepts Explained

The document covers various advanced Java topics including JDBC methods for database connections, multithreading concepts like sleep() and yield(), servlet functionalities, JSP, Hibernate ORM, and socket programming. It explains the use of different statements in JDBC, the thread life cycle, and the architecture of Hibernate. Additionally, it discusses networking in Java and the use of cookies and the Runnable interface.

Uploaded by

Sahej Kadam
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)
9 views28 pages

Advanced Java Concepts Explained

The document covers various advanced Java topics including JDBC methods for database connections, multithreading concepts like sleep() and yield(), servlet functionalities, JSP, Hibernate ORM, and socket programming. It explains the use of different statements in JDBC, the thread life cycle, and the architecture of Hibernate. Additionally, it discusses networking in Java and the use of cookies and the Runnable interface.

Uploaded by

Sahej Kadam
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

ADVANCED JAVA

1) 2 methods of connection interface.

When working with JDBC (Java Database Connectivity), the Connection interface provides several
methods for managing database connections. Two commonly used methods are:

1. createStatement(): Creates a Statement object for executing SQL queries.


o Syntax: Statement stmt = [Link]();
o Example:

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

Statement stmt = [Link]();

ResultSet rs = [Link]("SELECT * FROM employees");

2. prepareStatement(String sql): Creates a PreparedStatement for executing precompiled SQL queries,


which is more efficient and prevents SQL injection.
o Syntax: PreparedStatement pstmt = [Link](sql);
o Example:

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

String sql = "INSERT INTO employees (name, age) VALUES (?, ?)";

PreparedStatement pstmt = [Link](sql);

[Link](1, "John");

[Link](2, 30);

[Link]();

2) Sleep() method in multithreading.

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);

Key Features of sleep() Method:

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().

3) Method to set the thread priority.

You can set the priority of a thread using the setPriority(int newPriority) method from the Thread class.

Syntax: [Link](int priority);


Where priority is an integer between Thread.MIN_PRIORITY (1) and Thread.MAX_PRIORITY (10).

4) 2 classes used in socket programming.


1. Socket (Client-Side)

Used to create a client socket that connects to a server.

Establishes a connection with the server using IP Address and Port Number.

Allows sending and receiving data.

Example Usage:

Socket socket = new Socket("localhost", 5000)

2. ServerSocket (Server-Side)

 Used to create a server that listens for incoming client connections.

 Accepts client requests and returns a Socket object for communication.

Example Usage:

ServerSocket serverSocket = new ServerSocket(5000); // Server listens on port 5000

Socket clientSocket = [Link]();

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.

How IP Addresses Work?

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.

6) doGet () method of servlet

The doGet() method is part of the HttpServlet class and is used to handle HTTP GET requests in Java
Servlets.

Syntax of doGet()

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException

 HttpServletRequest request → Contains request data (parameters, headers, etc.).


 HttpServletResponse response → Used to send a response back to the client.
 Throws ServletException, IOException → Handles servlet and input/output exceptions
When to Use doGet()?

 When you want to retrieve data without modifying the server state.
 For search engines, form submissions (without sensitive data), API calls, etc.

7) Parameters of service() method of servlet.

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

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException

Parameters of service() Method:

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

a. Represents the server's response to the client.


b. Used to send HTML, JSON, or other data formats back to the client.
c. Methods like setContentType(), getWriter(), and sendRedirect() help generate responses.

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.

Key Features of JSP


Mixes Java with HTML – Java code is embedded inside HTML using special tags.
Simplifies Servlet Development – Unlike servlets, JSP doesn’t require writing a lot of Java code for UI.
Faster Development – Supports built-in objects (request, response, session, etc.) to reduce boilerplate
code.
Reusable Components – Can use JSP tags, JavaBeans, and Custom Tags for modular development.
Basic JSP Syntax
simple JSP file has a .jsp extension and contains a mix of HTML and Java.

Example: Basic JSP Page

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>


<html>
<head><title>Welcome to JSP</title></head>
<body>
<h2>Hello, Welcome to JSP!</h2>
<p>Current Date & Time: <%= new [Link]() %></p>
</body>
</html>
9) Hibernate

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.

Why Use Hibernate?

Eliminates JDBC Boilerplate Code – No need to write repetitive SQL queries.


Automatic Table Mapping – Maps Java classes to database tables.
Supports Multiple Databases – Works with MySQL, PostgreSQL, Oracle, etc.
Caching Mechanism – Improves performance by reducing database hits.
HQL (Hibernate Query Language) – Similar to SQL but database-independent.

How Hibernate Works?

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.

10) getConnection method

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

11) Use of cookies

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.

Session Management – Track logged-in users.


User Preferences – Store language, theme, etc.
Shopping Carts – Keep items in the cart even after page refresh.
Analytics & Tracking – Track user activity.

12) Use of Runnable interface

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.

Why Use Runnable?


Avoids Multiple Inheritance Issues – Java does not support multiple inheritance, so using Runnable allows
a class to extend another class while still implementing threading.
Better Resource Sharing – Multiple threads can share the same object, making Runnable more memory-
efficient.
Encapsulation & Reusability – The thread logic is kept separate from thread execution, making the code
more modular.

13) Thread priority.

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.

Thread Priority Range

Java assigns priority values from 1 to 10:

Constant Priority Value Description


Thread.MIN_PRIORITY 1 Lowest priority
Thread.NORM_PRIORITY 5 Default priority
Thread.MAX_PRIORITY 10 Highest priority

14) Use of HQL

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.

Why Use HQL?

Database Independent – Works with different databases without modification.


Uses Entity Objects – Queries use class names & field names instead of table & column names.
Supports Relationships – Easily fetches data using associations (OneToMany, ManyToOne, etc.).
Better Performance – Optimized caching and lazy loading mechanisms.

15) Directives in JSP

JSP directives provide global settings and configurations for a JSP page. They control the processing of
the JSP by the JSP container.

Syntax: <%@ directive_name attribute="value" %>

There are three types of directives in JSP:


Directive Description
Defines page-level settings (import classes, session management, etc.)
page
<%@ page attribute="value" %>

Includes another file at compile time


include
<%@ include file="[Link]" %>
Directive Description
Declares a tag library for custom JSP tags
taglib
<%@ taglib uri="uri" prefix="prefix" %>

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)

Java networking supports TCP, UDP, and Web communication.


Socket programming allows building client-server applications.
URL and IP utilities help in fetching web data.
UDP is faster but less reliable than TCP.

17) Method for creating connection

To create a database connection in Java, we use the getConnection() method of the DriverManager class
from the [Link] package.

Syntax of getConnection()

Connection con = [Link](URL, Username, Password);

The getConnection() method has multiple overloaded versions:

Method Description

Connects using only the JDBC URL (authentication


getConnection(String url)
handled externally).

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.

18) yield ( ) method

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.

Syntax of yield(): public static native void yield();

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 currently executing thread pauses and moves to a "Runnable" state.


 The CPU scheduler may or may not give execution control to another thread.
 If no other thread is available, the same thread continues execution

19) Use of socket class

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]

Works with: ServerSocket (on the server side)

Syntax of Socket Class

Socket socket = new Socket(String host, int port);

host: IP address or hostname of the server.

port: The port number on which the server is listening.

Key Uses of Socket Class

Use Case Description

Client-Server Communication Connects a client to a server over TCP.

Data Transmission Enables sending and receiving data streams.

Remote Method Invocation (RMI) Used in distributed computing.

Chat Applications Supports real-time communication.

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.

Steps to Create a Servlet

1. Extend the HttpServlet class.


2. Override the doGet() or doPost() method.
3. Deploy on a Servlet container like Apache Tomcat.

Where are Servlets Used?

Web Applications (Login systems, E-commerce)


REST APIs (Backend services)
Data Processing (Form submissions, file uploads)
Enterprise Applications
4 Marks-

Q.1) What is statement? Explain the types of statements in JDBC.

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.

Types of Statements in JDBC

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]();

Q.2) Explain thread life cycle with diagram.

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).

Thread Life Cycle States


Java provides the following thread states as defined in the [Link] enumeration:

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.");

Q.3) Explain Architecture of Hibernate.

Hibernate is a Java-based ORM (Object-Relational Mapping) framework that simplifies database


interactions by mapping Java objects to database tables. It provides a way to develop database-
independent applications.

The Hibernate architecture consists of several components that work together to manage database
operations efficiently.
Key Components of Hibernate Architecture:

1. Hibernate Configuration ([Link] or [Link])


 This file contains database connection settings and Hibernate properties. Example ([Link])

2. SessionFactory

A singleton object that creates Session instances.


It is thread-safe and should be created once per application.
Example:
SessionFactory factory = new Configuration().configure().buildSessionFactory();
3. Session
Represents a single unit of work (similar to a database connection). It is not thread-safe.
Used to save, update, delete, and retrieve objects.
Example:
Session session = [Link]();
4. Transaction
Ensures ACID properties (Atomicity, Consistency, Isolation, Durability). Each database operation should be
part of a transaction.
Example:
Transaction tx = [Link]();
[Link](myObject);
[Link]();

5. Query (HQL & Native SQL)


Native SQL:
SQLQuery query = [Link]("SELECT * FROM employee");
List<Object[]> result = [Link]();
6. Hibernate Mapping (Entity Classes & Annotations)
Mapping Java classes to database tables using annotations or XML.

7. JDBC & Database


Hibernate internally uses JDBC for database interaction. It generates SQL queries automatically.

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.

Key Methods of ResultSet Interface:

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.

[Link] Data Methods (Getting Column Values)

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.

[Link] Data Methods

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.

[Link] the ResultSet

void close() Closes the ResultSet and releases database resources.

Q.5)Explain JSP life cycle with diagram.

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.

Phases of JSP Life Cycle

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.

JSP File (.jsp) Translation to Java Compilation to .class Class loading

_jspService() jspInit() Instantiation


jspDestroy()
(Handles request)
(Draw it straight)

Q.6) What are the states of the object in hibernate?

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:

Session session = [Link]();


Transaction tx = [Link]();
Employee emp = new Employee(); // Transient state
[Link](101);
[Link]("John Doe");
[Link](emp); // Now in Persistent state
[Link]();
[Link]();

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.

Different Ways of Session Tracking in Servlets

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);

Advantages: Simple to implement Persistent across multiple sessions


Disadvantages: Some users disable cookies in their browsers Security concerns

2. Hidden Form Fields


 Data is stored in hidden fields within an HTML form and passed to the next request when the form is
submitted.
 Useful when session data should be maintained only between form submissions.

Example:
<form action="NextServlet" method="post">
<input type="hidden" name="user" value="JohnDoe">
<input type="submit" value="Submit"> </form>

Advantages: Simple and does not require cookies


Disadvantages: Works only with form submissions Data is visible in the page source

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>");

Advantages: Works even if cookies are disabled


Disadvantages: Exposes session data in the URL Requires modification of every URL

4. HttpSession (Most Common)


 The HttpSession interface stores session-related data on the server.
 Each user gets a unique session ID.

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.

How to Set Thread Priorities in Java:

1. Using setPriority(int priority) Method


The setPriority() method of the Thread class is used to change the priority of a thread.
Example:
[Link](Thread.MIN_PRIORITY); // Priority = 1
[Link](Thread.NORM_PRIORITY);
2. Getting Thread Priority
You can get the priority of a thread using the getPriority() method.
[Link]("Thread priority: " + [Link]().getPriority());

Q.9) Connection interface.

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:

1. Load the JDBC Driver using [Link]().


2. Establish the connection using [Link](URL, username, password).
3. Check if the connection is successful.
4. Close the connection using [Link]().

Important Methods in Connection Interface:

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();

How to Use Runnable Interface


There are two main steps to use Runnable:

1. Implement the Runnable interface.


2. Override the run() method to define the thread task.
3. Create a Thread object and pass the Runnable instance.

Q.11) Thread synchronization.

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.

Ways to Achieve Synchronization in Java:

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++;
}
}

Benefits: Ensures only one thread modifies count at a time.

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.

3. Static Synchronization: If a method is static, synchronization must be done on the class-level.


class Counter {
static int count = 0;
static synchronized void increment() { // Static synchronized method
count++;
}
}

Use case: When threads operate on shared static data.

Q.12) Explain in details directives in JSP

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.

Types of Directives in JSP

1. page Directive → Defines page-level settings.


2. include Directive → Includes another JSP file at compile time.
3. taglib Directive → Uses custom tag libraries.

1. page Directive: The page directive provides global settings related to the JSP page, such as:

 Importing Java classes


 Defining error pages
 Managing session behavior
 Setting content type and language

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;

synchronized void produce() {


try {
[Link]("Producing...");
flag = true;
notify(); // Notify the waiting thread
wait(); // Release lock and wait
} catch (InterruptedException e) {
[Link]();
}
}

synchronized void consume() {


try {
while (!flag) wait(); // Wait until producer produces
[Link]("Consuming...");
flag = false;
notify(); // Notify the producer thread
} catch (InterruptedException e) {
[Link]();
}
}
}

public class InterThreadExample {


public static void main(String[] args) {
SharedResource resource = new SharedResource();

new Thread(resource::produce).start();
new Thread(resource::consume).start();
}
}

Output:
Producing...
Consuming...
Q.14) Differentiate between statement and prepared statement interface

Q.15) Explain methods of serversocket class with syntax.

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:

Key Methods of the ServerSocket Class:

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()

 Description: Closes the server socket, releasing all associated resources.


 Syntax: public void close() throws IOException

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()

 Description: Indicates whether the server socket has been closed.


 Syntax: public boolean isClosed()

Q.16) What is the difference between execute ( ), executeQuery ( ) and executeupdate ( )?

JDBC provides three methods to execute SQL queries:

 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).

Q.17) Explain methods of socket class with example.

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);

String msg = [Link]();


[Link]("Client: " + msg);
[Link]("Hello Client!");

[Link]();
[Link]();
}
}

Client code:

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

public class Client {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));

[Link]("Hello Server!");
[Link]("Server: " + [Link]());

[Link]();
}
}
Output:
Server Output:
Client: Hello Server!
Client Output:
Server: Hello Client!

Q.18) Write advantages and disadvantages of spring.

Advantages of Spring Framework

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

1. Complex Configuration – XML or annotation-based configuration can be complex and time-consuming.


2. Steep Learning Curve – Requires understanding multiple modules like Spring MVC, Spring Boot, and
Spring Security.
3. Performance Overhead – The use of dependency injection and reflection can slightly impact
performance.
4. Difficult Debugging – Due to complex configurations, debugging can sometimes be challenging.
5. Not Suitable for Small Projects – Overhead of configuration and dependencies may be excessive for
small applications.
6. Memory Consumption – Can consume more memory compared to simpler frameworks due to its
additional features.

Q.19) Explain JSP tags with example

JSP (JavaServer Pages) provides various tags to simplify the development of dynamic web pages. These
tags help embed Java code inside an HTML page.

Types of JSP Tags:

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.

Tag Description Example


Includes another JSP file at
<jsp:include> <jsp:include page="[Link]"/>
runtime.
Forwards the request to another
<jsp:forward> <jsp:forward page="[Link]"/>
resource.
Tag Description Example
Creates and initializes a
<jsp:useBean> <jsp:useBean id="user" class="[Link]"/>
JavaBean.
<jsp:setProperty name="user" property="name"
<jsp:setProperty> Sets a property in a JavaBean.
value="John"/>
<jsp:getProperty> Gets a property from a JavaBean. <jsp:getProperty name="user" property="name"/>

Example: Using JSP Tags

<%@ page language="java" contentType="text/html; charset=UTF-8" %>


<html>
<head>
<title>JSP Tags Example</title>
</head>
<body>

<%! String siteName = "My Website"; %>

<%
String message = "Welcome to JSP!";
%>

<h1><%= message %></h1>


<p>Website: <%= siteName %></p>

<jsp:include page="[Link]"/>

</body>
</html>

Q.20) What are the advantages and disadvantages of multithreading?

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.

Q.21) Run Method

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.

Syntax of run() Method:


public void run() {
// Task to be executed by the thread
}
Aspect Details
Purpose Defines the task a thread will execute.
Where it belongs Part of Runnable interface and Thread class.
Execution Runs when start() is called.
Incorrect Usage Calling run() directly does not create a new thread.
1 Extending Thread class
Implementation Methods
2 Implementing Runnable interface

Q.22) Statement Interface

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:

 It is used to execute static SQL queries.


 It does not accept parameters.
 It is created using a Connection object.

To use the Statement interface, follow these steps:

1 Load and Register the JDBC Driver


[Link]("[Link]");

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");

5 Close the Connection


[Link]();

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:

 It processes client requests (like a browser request) and generates responses.


 It runs on a Java web server (e.g., Tomcat, Jetty).
 It provides methods like doGet(), doPost(), etc., to handle HTTP methods.

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.

[Link] (User Input Form)

<form action="[Link]" method="post">


Name: <input type="text" name="name" required><br>
Age: <input type="number" name="age" required><br>
<input type="submit" value="Check Eligibility">
</form>

[Link] (Eligibility Check Logic)

<%
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%'")) {

int deleted = [Link]();


[Link](deleted + " record(s) deleted.");

} catch (Exception e) {
[Link]();
}
}
}

3. Write servlet program to accept two numbers from user and print addition of that in blue colour.

[Link] (User Input Form)

<form action="AddServlet" method="post">


Number 1: <input type="number" name="num1" required><br>
Number 2: <input type="number" name="num2" required><br>
<input type="submit" value="Add">
</form>
[Link] (Servlet to Process Addition)

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].*;

public class FetchEmployees {


public static void main(String[] args) {
try (Connection con = [Link]("jdbc:mysql://localhost:3306/yourDB", "root",
"password");
PreparedStatement ps = [Link]("SELECT eno, ename, department, sal FROM
employees WHERE department = 'Computer Application'");
ResultSet rs = [Link]()) {

while ([Link]()) {
[Link]([Link]("eno") + " | " + [Link]("ename") + " | " +
[Link]("department") + " | " + [Link]("sal"));
}
} catch (Exception e) {
[Link]();
}
}
}

5. Write a java program to count number of records in a table.

import [Link].*;

public class CountRecords {


public static void main(String[] args) {
try (Connection con = [Link]("jdbc:mysql://localhost:3306/yourDB", "root",
"password");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT COUNT(*) FROM employees")) {

if ([Link]()) {
[Link]("Total Records: " + [Link](1));
}
} catch (Exception e) {
[Link]();
}
}
}

6. Write a java program in to print from 100 to 1. (use sleep() method)

public class Countdown {


public static void main(String[] args) {
for (int i = 100; i >= 1; i--) {
[Link](i);
try {
[Link](500); // Pause for 500 milliseconds (0.5 seconds)
} catch (InterruptedException e) {
[Link]();
}
}
}
}

7. Write a java program to create table student with attributes Rno, Sname, Per

import [Link].*;

public class CreateTable {


public static void main(String[] args) {
try (Connection con = [Link]("jdbc:mysql://localhost:3306/yourDB", "root",
"password");
Statement stmt = [Link]()) {

String sql = "CREATE TABLE student (" +


"Rno INT PRIMARY KEY, " +
"Sname VARCHAR(50), " +
"Per FLOAT)";

[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]

<form action="[Link]" method="post">


Enter Your Name: <input type="text" name="username" required>
<input type="submit" value="Greet Me">
</form>

[Link]

<% String name = [Link]("username"); %>


<h2>Hello, <%= name %>! Welcome to our website.</h2>

9. Write a java program to display IP address of a machine.


import [Link].*;

public class IPAddress {


public static void main(String[] args) {
try {
InetAddress ip = [Link](); // Get local IP address
[Link]("IP Address: " + [Link]());
} catch (Exception e) {
[Link]();
}
}
}

Output:

IP Address: [Link]

You might also like