finaljavaQBank (1)
finaljavaQBank (1)
System.out.println("Thread is running...");
public class Main { public static void main(String[] args) { MyThread t1 = new
MyThread();
t1.start();
System.out.println("Thread is executing...");
3. sleep(ms) – Pauses the thread for the given time (milliseconds). public class
SleepExample { public static void main(String[] args) throws InterruptedException {
System.out.println("Sleeping...");
Thread.sleep(2000); // 2 seconds
System.out.println("Woke up!");
}}
System.out.println("Thread running...");
}
}
System.out.println("Thread completed");
}}
t1.start(); t2.start(); }}
i) A Servlet is a Java program that runs on a web server and handles client requests,
usually from a web browser.
ii) It is used to create dynamic web applications by processing user requests, generating
responses, and interacting with databases. iii) Key Features of Servlets:
}
v) How It Works:
Servlets are commonly used in Java web applications and are part of Java EE (Jakarta EE).
Q3) Explain the following Collection Classes ArrayList, LinkedList, HashSet, TreeSet (With
methods to add & delete elements).
ii) Fast random access (O(1) for get()) but slow insertions/deletions in the middle (O(n)).
iii) Duplicates allowed, insertion order preserved.iv) Methods to Add & Remove
Elements:
i) Stores elements as a doubly linked list (each node points to next & previous). ii) Fast
insertions & deletions (O(1) at head/tail), but slow random access (O(n)). iii) Duplicates
allowed, insertion order preserved. iv) Methods to Add & Remove Elements:
// Remove an element
list.removeLast(); // Removes last element (20)
ii) No specific order maintained.iii)Fast operations (O(1) for add, remove, contains). iv)
Methods to Add & Remove Elements:
import java.util.TreeSet; public class TreeSetExample { public static void main(String[] args)
{
Comparison Table
Each collection is useful depending on the situation.
i) A JAR file is a compressed package that contains multiple Java class files, images, and
resources.
i) A Manifest file is a special text file inside a JAR that contains metadata. ii) It specifies the
main class for executable JARs and other configurations.
Manifest-Version: 1.0
Main-Class: MyApp
A Servlet goes through three main lifecycle methods, managed by the Servlet container (e.g.,
Tomcat).
1. init() – Initialization
Example:
i) Called every time the servlet receives a request. ii) Handles both doGet() and doPost()
methods.
Example:
3. destroy() – Cleanup
Example:
System.out.println("Servlet Destroyed");
i) A cookie is a small piece of data stored in the client’s browser by a web server.
ii) It helps websites remember user preferences, session details, and authentication
information.iii) Descriptive Attributes of a Cookie:
Example: username=JohnDoe
3. path – Defines the specific URL path where the cookie is accessible.
6. HttpOnly – Prevents client-side JavaScript from accessing the cookie (for security).
Cookies help in session management, personalization, and tracking user activity while
ensuring security using attributes like secure and HttpOnly.
To connect a Java application to a PostgreSQL database using JDBC, follow these steps:
Class.forName("org.postgresql.Driver");
2. Establish the Connection
while (rs.next()) {
System.out.println(rs.getString("name"));
(Replace username with your PostgreSQL username and mydb with your database name.)
);
\dt
This ensures JDBC connectivity and helps create tables via the PostgreSQL terminal.
Q8) Which are the different types of drivers available to establish Database connection,
Explain any one in detail
JDBC drivers are used to connect Java applications to databases. There are four types:
The Type 4 driver is a pure Java driver that communicates directly with the database.
try {
// Load the PostgreSQL JDBC driver
Class.forName("org.postgresql.Driver");
// Establish Connection
);
e.printStackTrace();
Type 4 drivers are the most commonly used because they provide a direct, fast, and
platformindependent connection between Java applications and databases.
In JDBC, both Statement and PreparedStatement are used to execute SQL queries, but they
differ in performance and security.
Example:
Example:
pstmt.setInt(1, 5);
ResultSet rs = pstmt.executeQuery();
Key Differences:
Ans.
Here's an explanation of five common JSP tags: page, include, forward, useBean, and
getProperty, which are used for page directives, actions, and scripting elements.
1. page Directive:
*Purpose: The page directive provides global settings for the JSP page, such as specifying the
language (Java), content type, session management, and error page.
*Example: <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
2. include Action:
*Purpose: Includes the content of another JSP page into the current page at runtime.
*Example: <jsp:include page="header.jsp" />
3. forward Action:
*Purpose: Forwards the request and response to another JSP page, allowing for control flow
between pages.
4. useBean Action:
/>
*Purpose: Finds or creates a Java bean (a class with getter and setter methods) and makes it
available within the specified scope (page, request, session, or application). *Example:
<jsp:useBean id="user" class="com.example.User" scope="session" />
5. getProperty Action:
*Purpose: Retrieves the value of a specified property from a Java bean that was previously
created or found using <jsp:useBean>.
Ans. The Vector class implements a growable array of objects, similar to an ArrayList, but
with the key difference that Vector is synchronized, making it thread-safe, while ArrayList is
not.
1.Multi-threaded environments:
If you need a thread-safe collection, Vector is a suitable choice, but consider using
If you are working with older code that relies on Vector, you might need to use it for
compatibility.
Ans.
1.Serialization
The process of writing the state of an object to a file is called serialization, but strictly
speaking, it is the process of converting an object from java supported form into a file-
supported form or networksupported form by using fileOutputStream and
objectOutputStream classes we can implement serialization.
But we can serialize only serializable objects. An object is said to be serializable if and only if
the corresponding class implements a Serializable interface. Serializable interface is present
in java.io package, and it doesn’t contain any method and hence it is a marker interface. If
we are trying to serializable a non-serializable object then we will get Runtime Exception
saying notSerializableException.
2.Externalization
In serialization, everything is taken care of by JVM and the programmer doesn’t have any
control. In serialization, it is always possible to solve the total object to file, and it is not
possible to save part of the object which may create performance problems. To overcome
this problem we should go for externalization.
The main advantage of Externalizable over serialization is, everything is taken care of by the
programmer and JVM doesn’t have any control. Based on our requirements we can save
either the total object or part of the object which improves the performance of the system.
To provide the generalizable ability for any java object, it’s a mandate for the corresponding
class to implement a generalizable interface.
Method 1
public void writeExternal( ObjectOutput obj ) throws IOException
This method will be executed automatically at the time of serialization within this method
we have to write code to save the required variable to the file. Method 2
This method will be executed automatically at the time of deserialization. Within this
method, we have to write code to read the required variable from the file and assign it to
the current object.
Q13) What are the advantages of using Servlets over traditional CGI
Ans.advantages:
1.Efficiency:
Servlets are more efficient because they are designed to be lightweight and run within the
web server's process, while CGI scripts spawn a new process for each request, consuming
more resources.
2.Platform Independence:
Servlets are written in Java, a platform-independent language, making them portable across
different operating systems and web servers, unlike CGI scripts which are often platform-
dependent.
Servlets are designed to work seamlessly with other Java technologies like JavaServer Pages
(JSP) and Enterprise JavaBeans (EJB), enabling developers to build complex web applications
using a unified framework.
4.Rapid Development:
Servlets provide access to a rich set of Java libraries and APIs, facilitating faster development
and easier maintenance of web applications.
Servlets are designed to handle multiple requests concurrently, making them suitable for
building scalable and high-performance web applications.
6.Security:
Servlets provide a more secure environment for web applications compared to CGI, as they
are managed by the web server and can be configured with security features.
7.State Management:
Servlets can maintain state information across multiple requests, unlike CGI scripts, which
are stateless.
8.Easy Coordination:
Servlets can easily coordinate with other servlets and components within a web application,
making it easier to build complex applications.
Ans.
1.Iterator:
Purpose:
Iterators are used to traverse elements in a collection one by one, providing methods like
hasNext() to check for the next element and next() to retrieve it.
Modification:
Iterators also offer a remove() method to safely delete elements from the collection during
iteration, preventing ConcurrentModificationException.
Use Cases:
Traversing different data structures or when the type of the structure is unknown.
2.Comparator:
Purpose:
Comparators define custom sorting logic for objects, allowing you to sort collections based
on criteria other than the natural ordering.
Implementation:
A Comparator is an object with a compare() method that takes two objects as input and
returns an integer indicating their relative order.
Use Cases:
1.What it is:
Introspection is a mechanism that allows a program to examine the structure of a Java class
(or bean) at runtime, including its properties, methods, and events.
2.How it works:
Introspection uses Java's reflection API to dynamically inspect the class and its members,
enabling tools to discover and interact with the bean's capabilities.
*Visual Development Tools: Introspection is crucial for tools that allow developers to build
user interfaces or manipulate components visually, as it enables the tool to understand the
properties and methods of the bean being used.
*Dynamic Code Generation: Introspection can be used to dynamically create or modify code
based on the structure of the bean, allowing for flexible and adaptable applications.
4.Key Concepts:
*BeanInfo: A special class that provides descriptive information about a bean, including its
properties, events, and methods. Introspection uses BeanInfo to learn about a bean's
capabilities.
*Introspector Class: The java.beans.Introspector class provides a standard way for tools to
learn about the properties, events, and methods supported by a target Java Bean.
Ans.In Java web development, HTTP session tracking allows you to maintain state across
multiple HTTP requests from the same client, overcoming the stateless nature of HTTP, by
using the HttpSession interface to store and retrieve data associated with a user's session.
To create interactive web applications (where the server needs to remember user data
between requests), session tracking is crucial.
2.HttpSession:
The HttpSession interface, part of the Java Servlet API, provides a mechanism for managing
user sessions.
3.How it Works:
A.When a user makes a request, the server can create a new session or retrieve an existing
one.
B.A unique session ID is assigned to the session, which can be stored in a cookie or other
mechanisms.
C.You can store data (Java objects) in the HttpSession using setAttribute() and retrieve it
using getAttribute().
D.Multiple servlets within the same application can access the same session.
4.Session Management:
Ans.
The doGet() method is used to process HTTP GET requests. This method is typically used for
retrieving data or displaying information to the user. B.Example:
When a user types a URL in the browser and presses Enter, or when a form is submitted with
the method="GET" attribute, the doGet() method in the corresponding servlet is invoked.
C.Data Transfer:
GET requests send data as part of the URL, which is visible to the user in the address bar.
D.Security:
Because data is visible in the URL, GET requests are generally less secure than POST
requests.
The doPost() method is used to process HTTP POST requests. This method is typically used
for submitting data, creating new resources, or modifying existing ones. B.Example:
When a form is submitted with the method="POST" attribute, the doPost() method in the
corresponding servlet is invoked. C.Data Transfer:
POST requests send data in the body of the HTTP request, which is not visible in the URL.
D.Security:
Because data is not visible in the URL, POST requests are generally more secure than GET
requests.
Ans.
The Thread class represents a thread of execution, allowing programs to perform multiple
tasks concurrently. You can create threads by either extending the Thread class or
implementing the Runnable interface.
1.Key Concepts:
Threads enable concurrent execution, allowing multiple parts of a program to run seemingly
simultaneously.
C.Thread Creation:
Extending the Thread class: Create a class that extends Thread and override the run()
method, which contains the code to be executed by the thread.
D.Implementing the Runnable interface: Create a class that implements the Runnable
interface and override the run() method. Then, create a Thread object, passing an instance
of the Runnable class to its constructor.
2.Thread Methods:
A.start(): Initiates the execution of a thread, causing it to transition to the Runnable state.
-->
The procedure for creating threads based on the Runnable interface is as follows:
1. A class implements the Runnable interface, providing the run() method that will be
executed by the thread. An object of this class is a Runnable object.
3. The start() method is invoked on the Thread object created in the previous step. The
start() method returns immediately after a thread has been spawned.
4. The thread ends when the run() method ends, either by normal completion or by
throwing an uncaught exception.
Example: plaas MyRunnable implements Runnable{ public void run(){ //define run method
//thread action
MyRunnable r=new MyRunnable(); //create object Thread t =new Thread(r): //create Thread
object
A class can also extend the Thread class to create a thread. When we extend the Thread
class, we should override the run method to specify the thread action.
class MyThread extends Thread{ public void run() {//override run method.
//thread action
JSP architecture is a 3 tier architecture. It has a Client, Web Server, and Database.
The client is the web browser or application on the user side. Web Server uses a JSP Engine
i.e; a container that processes JSP. For example, Apache Tomcat has a built-in JSP Engine.
JSP Engine intercepts the request for JSP and provides the runtime environment for the
understanding and processing of JSP files.
It reads, parses, build Java Servlet, Compiles and Executes Java code, and returns the HTML
page to the client. The webserver has access to the Database. The following diagram shows
the architecture of JSP.
-->Set Interface:
Purpose:
The Set interface models the mathematical concept of a set, ensuring that each element is
unique.
Key Characteristics:
No Order: Sets do not guarantee any specific order of elements, unless the underlying
implementation provides it (e.g., LinkedHashSet maintains insertion order).
Use Cases:
Map Interface:
Purpose:
The Map interface stores data as key-value pairs, where each key is associated with a unique
value.
Key Characteristics:
Use Cases:
Create multiple Java classes that extend HttpServlet (or a suitable servlet class).
Each servlet will handle a specific part of the request processing or have a particular role.
Override the doGet() or doPost() methods (or both) in each servlet to handle HTTP requests.
Within these methods, implement the logic to process the request, potentially access data,
and perform actions.
Use the RequestDispatcher interface's forward() method to transfer the request and
response objects to another servlet.
This method is used to pass control and data to the next servlet in the chain.
Example:
/nextServlet represents the URL pattern of the next servlet in the chain.
Use the include() method of RequestDispatcher to include the content of the previous
servlet into the current servlet's response.
Example:
Use request attributes (request.setAttribute()) to pass data between servlets in the chain.
In your web.xml (or equivalent configuration file), map the URL patterns for each servlet to
the corresponding servlet classes.
Ensure that the order of servlets in the chain is correctly reflected in the mapping.
Thoroughly test the servlet chain to ensure that requests are processed correctly and data is
passed between servlets as expected.
Use debugging tools to identify and resolve any issues in the chain.
Q23) Write the steps for establishing Java Database Connectivity with PostgreSQL
-->To connect a Java application with a PostgreSQL database using JDBC, follow these steps:
1. Install PostgreSQL
Ensure PostgreSQL is installed and running on your system. You can download it from the
official site: https://www.postgresql.org/download/
https://jdbc.postgresql.org/
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
For Non-Maven Users (Manually Add JAR to Classpath):
In Java, you need to load the JDBC driver before connecting to the database.
Class.forName("org.postgresql.Driver");
// Database credentials
if (conn != null) {
} catch (SQLException e) {
e.printStackTrace();
After connecting, you can execute SQL queries using Statement or PreparedStatement.
"age INT)";
} catch (SQLException e) {
e.printStackTrace();
String insertSQL = "INSERT INTO students (name, age) VALUES (?, ?)";
} catch (SQLException e) {
e.printStackTrace();
}}
while (rs.next()) {
} catch (SQLException e) {
e.printStackTrace();
}}
-->Multitasking Multithreading
While in multithreading, many threads are created from a process through which computer
power is increased.
While in multithreading also, CPU switching is often involved between the threads.
While in multithreading also, a CPU is provided in order to execute many threads from a
process at a time.
In multitasking, processes don’t share the same resources, each process is allocated
separate resources.
Q25) Compare JSP with other similar technologies like ASP (Active Server Pages)
-->JSP ASP
1.JSP stands for Java Server Pages, which helps developers to create dynamically web
pages based on HTML, XML, or other types.
ASP stands for Active Server Pages, which is used in web development to implement
dynamic web pages.
2.JSP is a server side scripting language, which was created by Sun Micro systems. ASP
is also a server side scripting language, which was created by Microsoft.
ASP code is not compiled, because it uses VB-script, therefore it is an interpreted language.
-->Implicit objects are a set of Java objects that the JSP Container makes available to
developers on each page.
These objects may be accessed as built-in variables via scripting elements and can also be
accessed programmatically by JavaBeans and Servlets.
request: This is the object of HttpServletRequest class associated with the request. response:
This is the object of HttpServletResponse class associated with the response to the client.
config: This is the object of ServletConfig class associated with the page.
application: This is the object of ServletContext class associated with the application context.
session: This is the object of HttpSession class associated with the request.
page context: This is the object of PageContext class that encapsulates the use of server-
specific features. This object can be used to find, get or remove an attribute.
page object: The manner we use the keyword this for current object, page object is used to
refer to the current translated servlet class.
exception: The exception object represents all errors and exceptions which is accessed by
the respective jsp. The exception implicit object is of type java.lang.Throwable.
out: This is the PrintWriter object where methods like print and println help for displaying
the content to the client.
-->In Java web applications, Server Side Includes (SSI) refer to techniques used to include
reusable content (such as headers, footers, and navigation bars) dynamically in JSP
(JavaServer Pages) or Servlets before sending the response to the client.
Java does not directly support traditional SSI (<!--#include file="..." --> as in Apache), but JSP
and Servlets provide alternative approaches to achieve the same effect.
The included content is executed separately and then merged into the response.
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
</body> </html>
✅ Advantage: The included page executes independently and can contain dynamic JSP/Java
code.
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
</body> </html>
❌ Limitation: The included file cannot contain JSP declarations (<%! %>).
Defines page-level settings such as importing Java classes, setting content type, and enabling
session management.
Syntax:
<%@ page attribute="value" %>
Used to include content from another JSP or HTML file at compile time.The included file's
content is statically added to the current JSP before compilation.
Syntax:
Used to define and import custom tags or standard JSP tag libraries (JSTL).
Helps in reducing Java code inside JSP files by using tag-based expressions.
Syntax:
The JVM starts the main thread automatically when a Java program begins execution.
The main thread is responsible for executing the statements inside the main() method.
If no other threads are created, the program will end when the main thread finishes
execution.
The main thread can be paused, resumed, or terminated using methods like sleep(), yield(),
and join().It can also be renamed using setName() and retrieved using getName().
The Lock interface provides explicit locking mechanisms to ensure thread safety in
multithreaded programs.
3.ReentrantLock Class
Uses the ODBC (Open Database Connectivity) driver to connect Java applications to
databases.
Architecture:
Disadvantages:
✖ Platform-dependent
Uses a middleware server that translates JDBC calls into database-specific calls.
The middleware acts as a bridge between the Java application and the database.
A fully Java-based driver that directly communicates with the database using database-
specific network protocols.
The executeUpdate() method in JDBC is used to execute SQL statements that modify the
database, such as:
Syntax:
The Thread class in Java provides built-in methods to create and manage threads.
To create a thread, extend the Thread class and override the run() method.
try {
} catch (InterruptedException e) {
e.printStackTrace();
try {
} catch (InterruptedException e) {
e.printStackTrace();
t1.start();
t2.start();
Functional Interfaces: Interfaces with only one abstract method (e.g., Runnable,
Comparator).
✔ Tag Libraries –
3.Struts Components
(a) struts-config.xml (Configuration File)
5. Advantages of Struts
:::::Apache Maven is a build automation and project management tool used in Java. It
simplifies project compilation, dependency management, testing, and deployment. Maven
follows a convention-over-configuration approach, reducing manual setup efforts.
✔ Dependency Management –
✔ Convention-over-Configuration –
Phase
*validate
*compile
*package
*install
*deploy
Q37: Write a note on: Optional class, Collectors class, Parallel Sort ->Optional Class:
Introduced in Java 8, the Optional class is a container for a value that may or may not be
present. It helps to avoid NullPointerException and provides methods like isPresent(), get(),
and ifPresent() to handle the presence or absence of a value effectively.
Collectors Class:
Part of the java.util.stream package, the Collectors class provides various static methods for
collecting the elements of a stream into different types of collections (e.g., List, Set, Map).
Commonly used methods include toList(), toSet(), and groupingBy().
Parallel Sort:
A method introduced in Java 7, Arrays.parallelSort() sorts the specified array into ascending
order using a parallel sorting algorithm. This method uses multiple threads to achieve faster
sorting, especially for large arrays.
->Annotations:
Annotations are a form of metadata that provide information about a program but are not
part of the program itself. They do not change the action of the compiled program but can
be used for various purposes such as code analysis, generating documentation, or
controlling the behavior of frameworks (e.g., @Override, @Entity, @Transactional).
->Spring Framework:
The Spring Framework is a powerful framework for building Java applications. It provides
comprehensive infrastructure support, allowing developers to create high-performing,
reusable, and easily testable code.
Spring MVC: A module for building web applications using the MVC design pattern.
Integration: Supports various data access technologies, including JDBC, JPA, and Hibernate.
->Spring Applications:
Applications built using the Spring Framework benefit from its lightweight architecture and
modular components. They support a wide range of functionalities, including:
Spring applications are configurable through XML or Java annotations, promoting clear and
concise code.
Part of the Spring Framework, the Spring MVC (Model-View-Controller) framework helps
create web applications by separating application logic into three interconnected
components:
View: Represents the UI components and how data is presented to the user.
Controller: Handles user input and updates the model and view accordingly.
Features include:
RESTful API Support: Simplified support for building REST APIs through @RestController.
Integration with other Spring features: Like security, data access, and more.
->Components of Hibernate:
Transaction: Manages application data and ensures data integrity between the database and
application by supporting operations like commit and rollback.
Query: Facilitates data retrieval with HQL (Hibernate Query Language) or Criteria API.
Mapping: Interacts with the database tables through Java classes and annotations or XML
files.
->Struts Framework:
An open-source framework for developing Java EE web applications following the MVC
design pattern. Key features include:
Action Servlet: Central component managing requests and directing them to proper actions.
Tag Libraries: Simplifies JSP development with custom tags for form handling and data
validation.
Convention over Configuration: Reduces the amount of configuration needed and promotes
standard coding practices.
Integration: Works well with other Java frameworks and tools for web applications.
Flexibility: Various data structures (like List, Set, Map) allow for efficient data handling.
Performance: Optimized algorithms for common operations such as searching, sorting, and
manipulating data.
Interoperability: Easily works with Java and other data structures, enhancing integration.
Resizable Data Structures: Many collections can dynamically adjust their size as needed,
making them more adaptable than traditional arrays.