0% found this document useful (0 votes)
3 views30 pages

Java Sem2 Qb

The document is a question bank on advanced Java topics, covering key concepts such as garbage collection, interfaces, inner classes, constructors, method overloading and overriding, packages, inheritance, Java utility and collection frameworks, and servlets. Each section includes definitions, features, examples, and explanations of how these concepts are implemented in Java. It serves as a comprehensive guide for understanding and applying advanced Java programming techniques.

Uploaded by

Sainath Powar
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)
3 views30 pages

Java Sem2 Qb

The document is a question bank on advanced Java topics, covering key concepts such as garbage collection, interfaces, inner classes, constructors, method overloading and overriding, packages, inheritance, Java utility and collection frameworks, and servlets. Each section includes definitions, features, examples, and explanations of how these concepts are implemented in Java. It serves as a comprehensive guide for understanding and applying advanced Java programming techniques.

Uploaded by

Sainath Powar
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

ADVANCE JAVA QUESTION BANK

1. Write a note on garbage collection in java


Garbage Collection (GC) in Java is a process by which the Java Virtual Machine (JVM)
automatically identifies and removes objects that are no longer in use to free up memory and
improve performance.
• Features of Java -
✓ Automatic Memory Management: Java programmers do not need to explicitly
deallocate memory. The JVM does this automatically.
✓ Heap Memory: Objects are stored in the heap memory.
✓ Garbage Collector: The garbage collector is a background process that runs periodically
to identify and remove unused objects.
• How Does It Work?
Java uses a technique known as "tracing garbage collection", particularly the Mark and
Sweep method:
✓ Mark Phase: The JVM traverses the object graph and marks all reachable (in-use)
objects.
✓ Sweep Phase: All unmarked objects are considered garbage and are removed from
memory.
• Importance:
✓ Prevents memory leaks.
✓ Improves application performance.
✓ Reduces the need for manual memory handling.
Java's garbage collection makes programming easier and safer by automatically managing
memory and removing unused objects.
• Methods and Keywords:
✓ [Link](): Suggests that the JVM performs garbage collection, but it is not
guaranteed.
✓ finalize(): Method called before an object is garbage collected (deprecated in newer
Java versions).
• An object becomes eligible for Garbage Collection when:
✓ It is no longer referenced by any variable.
✓ Its reference is explicitly set to null.
✓ The variable goes out of scope.
✓ The parent object is garbage collected.
Garbage Collection in Java is an automatic mechanism that keeps memory usage in check by
removing unused objects. It improves performance, prevents memory leaks, and simplifies
development.

2. Define interface and explain how implement interface with example in java.
OR Write a note on Interface.
In Java, an interface is a blueprint of a class. It is a reference type similar to a class that can
contain only constants, method signatures, default methods, static methods, and nested
types. Interfaces cannot contain instance fields or constructors, and methods are implicitly
public and abstract (unless marked as default or static).
• Features of Interface:
✓ Used to achieve abstraction and multiple inheritance in Java.
✓ All methods in an interface are public and abstract by default (Java 8 onwards allows
default and static methods).
✓ A class implements an interface using the implements keyword.
✓ A class must provide implementations for all methods declared in the interface.
• Syntax of Interface:
interface InterfaceName {
void method1();
default void method2() {
[Link]("Default method");
}
static void method3() {
[Link]("Static method");
}
}
✓ All variables in interfaces are public, static, and final by default.
✓ All methods (except default/static) are public and abstract.
• Why use Interfaces?
✓ To achieve abstraction (hiding implementation details).
✓ To achieve multiple inheritance (a class can implement multiple interfaces).
✓ To define a contract for classes to follow.
• Implementing an Interface in Java:
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Output: Dog barks
}
}
In Java, we use the implements keyword to make a class follow a contract defined by an
interface. This allows the class to inherit the abstract methods of an interface and provide
their own implementation.

3. What is java inner classes?


In Java, inner classes are classes that are defined within another class. They help logically
group classes that are only used in one place and can access members (even private) of the
outer class.
• Features of Java Inner Classes:
✓ Encapsulation: Inner classes help group logically related classes, improving
encapsulation.
✓ Access to Outer Class Members: They can access private members of the outer class.
✓ Improved Readability: Keeps code clean and easy to manage when classes are tightly
coupled.
✓ Helps in Event Handling: Especially useful in GUI programming (like with Java Swing or
AWT).
✓ Can be Private, Protected, or Static: You can control the visibility of inner classes just
like normal class members.
• Uses of Inner Classes in Java:
✓ To logically group classes that are only used in one place (e.g., a helper class).
✓ Event handling in GUI frameworks like Swing and Android (anonymous inner classes
are common).
✓ Creating more readable and maintainable code by putting small classes inside the outer
class.
✓ Hiding implementation details of a class from the outside world.
✓ Callbacks and Listeners: Frequently used in frameworks for creating event listeners.
• There are four types of inner classes in Java:
1. Non-static (Member) Inner Class
2. Static Nested Class
3. Local Inner Class (inside a method)
4. Anonymous Inner Class
➢ Member Inner Class (Non-static) - Defined inside another class, behaves like an
instance member.
➢ Static Nested Class - Defined inside a class with static keyword.
➢ Local Inner Class - Defined inside a method of the outer class.
➢ Anonymous Inner Class - A class without a name, used for one-time use (usually for
interfaces or abstract classes).
Java inner classes provide a powerful way to logically group classes that are only used in one
place, improving encapsulation and code readability.

4. Define constructor and explain default and Parameterised constructor in java


A constructor in Java is a special method that is used to initialize objects. It is called
automatically when an object of a class is created. The name of the constructor is same as
the class name, and it does not have a return type, not even void.
class ClassName {
ClassName() {
// constructor body
}
}
• Characteristics of a Constructor:
✓ The constructor has the same name as the class.
✓ It doesn’t have a return type, not even void.
✓ It is automatically invoked at the time of object creation.
✓ It can be overloaded (i.e., multiple constructors in the same class).
✓ Types of Constructors in Java

1. Default Constructor:
A default constructor is the constructor without any parameters. It is either created
explicitly by the programmer or implicitly by Java if no constructors are defined in the class.
class Bike {
Bike() {
[Link]("Bike is created");
}

public static void main(String args[]) {


Bike b = new Bike(); // Calls default constructor
}
}
If no constructor is defined in a class, Java automatically provides a no-argument default
constructor.
2. Parameterized Constructor:
A parameterized constructor is a constructor that accepts arguments. It allows you to pass
values to the object during creation.
class Employee {
String name;
int id;
Employee(String n, int i) {
name = n;
id = i;
}
void display() {
[Link]("Name: " + name + ", ID: " + id);
}
public static void main(String[] args) {
Employee emp1 = new Employee("John", 101);
[Link]();
}
}

5. What is method overloading and overriding in java.


OR Difference between method overloading and overriding in java.
1. Method Overloading (Compile-time Polymorphism)
Definition: Method Overloading means defining multiple methods with the same name but
with different parameter lists in the same class.
• Rules:
✓ Same method name.
✓ Different number, type, or order of parameters.
✓ Return type can be different, but cannot be the only difference.
• Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](2, 3));
[Link]([Link](2.5, 3.5));
[Link]([Link](1, 2, 3));
}
}
2. Method Overriding (Run-time Polymorphism)
Definition: Method Overriding means redefining a parent class method in a subclass with the
same method name, return type, and parameters.
• Rules:
✓ Same method signature (name + parameters).
✓ Occurs in inheritance (between parent and child class).
✓ The method in the child class overrides the parent class method.
• Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}

• Differences Between Overloading and Overriding:

Features Method Overloading Method Overriding


Definition Same method name Same method signature in
different parameters subclass
Type of polymorphism Compile time Run time
Inheritance required Inheritance is not required Inheritance is required
Class involved Same class Parent and child class
Purpose Code flexibility Modify and extend parent
class behavior

7. Define package and explain built in and user defined package with example.
A package in Java is a namespace that organizes a set of related classes and interfaces.
Conceptually, you can think of packages as being similar to different folders on your
computer. It helps in:
✓ Avoiding name conflicts.
✓ Controlling access.
✓ Making it easier to locate and use classes.
✓ Organizing files within projects
• Types of Packages:
1. Built-in Packages
2. User-defined Packages
▪ Built-in Packages:
Java provides many built-in packages as part of the Java API. These packages contain
predefined classes and interfaces.
✓ [Link] – contains fundamental classes like String, Math, Integer, etc.
✓ [Link] – contains utility classes like ArrayList, HashMap, Date, etc.
✓ [Link] – classes for input and output, e.g., BufferedReader, FileWriter, etc.
➢ Example Code (Using Built-in Package):
import [Link];
public class BuiltInPackageExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link](list);
}
}
▪ User-defined Packages:
These are packages created by the programmer to group related classes and maintain code
organization.
➢ Steps to Create and Use User-defined Package:
1. Create a Package:
package mypackage;
public class MyClass {
public void display() {
[Link]("This is a user-defined package.");
}
}
2. Save the file as [Link] inside a folder named mypackage.
3. Compile:
javac -d . [Link]
4. Use in Another Class:
import [Link];
public class TestPackage {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}
Packages in Java play a vital role in code management and reusability. While built-in
packages provide ready-to-use functionalities, user-defined packages help developers
modularize their own code effectively.

8. Define inheritance and explain single, multilevel and hierarchical inheritance with
example.
Inheritance in Java is one of the core concepts of object-oriented programming. It allows a
class to inherit fields and methods from another class.
• Syntax:
class Parent {
// fields and methods
}
class Child extends Parent {
// additional fields and methods
}
1. Single-level inheritance :In single-level inheritance, a child class inherits properties and
behaviors (fields and methods) from one parent class only.
✓ Syntax:
class Parent {
// parent class members
}
class Child extends Parent {
// child class members
}
✓ Example:
class Vehicle {
void start() {
[Link]("Vehicle is starting...");
}
}
class Car extends Vehicle {
void drive() {
[Link]("Car is driving...");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
[Link]();
[Link]();
}
}

2. Multilevel inheritance:In multilevel inheritance, a class inherits from a derived class.


✓ Syntax:
class GrandParent {
// base class members
}
class Parent extends GrandParent {
// derived from GrandParent
}
class Child extends Parent {
// derived from Parent
}
✓ Example:
class Vehicle {
void display() {
[Link]("This is a vehicle.");
}
}
class Car extends Vehicle {
void showCar() {
[Link]("This is a car.");
}
}
class SportsCar extends Car {
void showSportsCar() {
[Link]("This is a sports car.");
}
}
public class Main {
public static void main(String[] args) {
SportsCar sc = new SportsCar();
[Link]();
[Link]();
[Link]();
}
}

3. Hierarchical Inheritance : Hierarchical Inheritance in Java occurs when multiple classes


inherit from a single parent class.
✓ Example:
class Vehicle {
void display() {
[Link]("This is a vehicle.");
}
}
class Car extends Vehicle {
void showCar() {
[Link]("This is a car.");
}
}
class Bike extends Vehicle {
void showBike() {
[Link]("This is a bike.");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
[Link]();
[Link]();
Bike b = new Bike();
[Link]();
[Link]();
}
}

9. Write a note on java utility and collection


• Java Utility Package ([Link])
The [Link] package is one of the core utility packages in Java that contains various classes
and interfaces which help in performing a wide range of functionalities such as:
✓ Date and Time operations (Date, Calendar)
✓ Data structures (ArrayList, HashMap, HashSet, etc.)
✓ Event handling
✓ Random number generation (Random)
✓ String manipulation utilities (StringTokenizer)
✓ Legacy collection classes (Vector, Hashtable)
It serves as a backbone for performing everyday programming tasks more easily and
efficiently.

• Java Collection Framework


The Collection Framework is a part of the [Link] package and provides standardized
architecture to store, retrieve, and manipulate groups of objects. It includes:
• Key Interfaces:
✓ Collection
✓ List (e.g., ArrayList, LinkedList)
✓ Set (e.g., HashSet, TreeSet)
✓ Map (e.g., HashMap, TreeMap)
✓ Queue (e.g., PriorityQueue, LinkedList)
• Features:
✓ Dynamic resizing of data structures
✓ Type safety with generics
✓ Built-in algorithms like sorting, searching (using Collections class)
✓ Thread-safe collections (e.g., ConcurrentHashMap, CopyOnWriteArrayList)
The [Link] package and Collection Framework simplify data handling in Java by providing a
powerful, reusable set of tools that help developers focus more on application logic rather
than reinventing data structures.

10. What is servlet and what are advantages of servlet


A Servlet is a Java program that runs on a server and handles requests and responses
in a web application. It acts as a middle layer between client requests (usually from a web
browser) and server responses (usually HTML pages or data).
Servlets are a part of Java EE (Enterprise Edition) and are used to build dynamic web
applications.
• How Does a Servlet Work?
1. Client (browser) sends a request to the server.
2. Web server forwards the request to the servlet.
3. Servlet processes the request and generates a response (usually HTML or JSON).
4. Response is sent back to the client.
• Advantages of Servlet:
1. Platform Independent: Written in Java, so it runs on any platform with a compatible JVM.
2. Efficient and Scalable: Servlets are managed by a servlet container (like Tomcat) and can
handle multiple requests using multithreading.
3. Robust and Secure: Java provides built-in security and exception handling features.
4. Reusable and Maintainable: Code is modular and reusable; maintenance is easier.
5. Better Performance than CGI: Unlike CGI (Common Gateway Interface), servlets use
threads rather than processes, which makes them faster.
6. Integration with Java Technologies: Easily integrates with JDBC, EJB, and other Java APIs.
7. Session Management: Supports session tracking using cookies and HTTP sessions.

11. Write a note on servlet and CGI


➢ Servlet:
✓ A Servlet is a Java program that runs on a web server and handles requests and
responses.
✓ It is used to create dynamic web content.
✓ Servlets are part of the Java EE (Jakarta EE) platform and run inside a servlet
container like Apache Tomcat.
✓ They are more efficient than CGI because they use threads instead of creating a new
process for each request.
• Benefits of servlets:
✓ Platform-independent (Java-based)
✓ Fast and scalable
✓ Easily integrated with Java technologies
✓ Common classes used: HttpServlet, HttpServletRequest, HttpServletResponse.
➢ CGI (Common Gateway Interface):
✓ CGI is a standard protocol used to generate dynamic web content.
✓ It allows web servers to execute external programs or scripts (e.g., written in Perl,
Python, or C) and send the output to the client.
✓ Each request spawns a new process, which can be resource-intensive.
✓ CGI was widely used in the early web but has performance limitations.
✓ Suitable for simple, small-scale web applications.
❖ Comparison:
12. Explain life cycle of servlet
OR Explain the life of servlet and the purpose of each phase in the life cycle.
The life cycle of a Servlet is the process from its creation to its destruction. It is defined
by the Servlet API and managed by a Servlet container like Apache Tomcat. The servlet
life cycle consists of five main stages:
1. Loading and Instantiation
✓ Done by the Servlet container (e.g., Tomcat) when the servlet is first requested or
during server startup.
✓ The servlet class is loaded, and an object is created using the default constructor.
2. Initialization – init()
✓ Called once after instantiation.
✓ Used to initialize resources like DB connections, config settings, etc.
3. Request Processing – service()
✓ Called each time a client request is received.
✓ Delegates to doGet(), doPost(), etc., based on the HTTP method.
✓ Core logic of the servlet resides here.
4. Destruction – destroy()
✓ Called once when the servlet is being removed from memory.
✓ Used to clean up resources and perform shutdown operations.
5. Garbage Collection
✓ After destroy(), the servlet object is eligible for garbage collection by the JVM.

13. Define generic servlet and http servlet.


➢ Generic Servlet is a basic servlet class in Java that can be used with any type of
protocol, not just HTTP. It is like a general template. You only need to write code in
the service() method to handle client requests. It is not used much in real web
development.
• A protocol-independent, abstract class from [Link] package.
• Can be used with any protocol (not just HTTP).
• Requires overriding the service() method to handle client requests.
• Rarely used in real-world web development.
• Example Use: Custom server protocols (non-HTTP), educational/demo purposes.

➢ Http Servlet is a special type of servlet made for handling HTTP requests (like from a
browser). It has built-in methods like doGet() and doPost() to handle different types
of web requests. This is the most commonly used servlet in web applications.
• A subclass of GenericServlet from [Link] package.
• Specifically designed to handle HTTP requests.
• Provides methods like doGet(), doPost(), doPut(), and doDelete().
• Most commonly used in web applications.
• Example Use: Websites, REST APIs, form handling, etc.

14. What is jdbc and explain following typ1, typ2, typ3, typ4.
OR Write a note on JDBC Driver.
JDBC (Java Database Connectivity) is an API (Application Programming Interface) provided
by Java to connect and interact with relational databases like MySQL, Oracle, PostgreSQL,
etc. It allows Java applications to perform database operations such as connecting to a
database, executing SQL queries, and retrieving results.
• Types of JDBC Drivers
JDBC drivers are used to connect a Java application to the database. There are four types of
JDBC drivers:
1. Type 1: JDBC-ODBC Bridge Driver
✓ Uses ODBC (Open Database Connectivity) to connect to the database.
✓ Converts JDBC calls into ODBC calls and then to database calls.
✓ Requires ODBC driver installed on the client machine.
✓ Easy to use for testing.
✓ Slow and platform-dependent. Not suitable for production.
2. Type 2: Native-API Driver
✓ Uses native database libraries (written in C/C++).
✓ JDBC calls are converted to native API calls of the database.
✓ Faster than Type 1.
✓ Platform-dependent; requires native DB libraries on client machine.
3. Type 3: Network Protocol Driver (Middleware Driver)
✓ JDBC calls are sent to a middleware server, which then communicates with the
database.
✓ The middleware translates JDBC requests to DB-specific protocol.
✓ Platform-independent; suitable for internet applications.
✓ Requires separate middleware server.
4. Type 4: Thin Driver (Pure Java Driver)
✓ Pure Java driver that directly connects to the database using DB-specific protocol.
✓ No native code or middleware required.
✓ Fastest, platform-independent, widely used in modern apps.
✓ Each database needs its own Type 4 driver.

15. Write a note on [Link] interface


b. Prepared statement interface
c. Callibal statement interface
In JDBC, Statement interfaces are used to execute SQL queries against a database. There are
three main types:
1. Statement Interface
✓ The Statement interface is used to execute static SQL queries that are hard-coded and
do not change. It is suitable for simple and quick SQL executions.
✓ Part of [Link] package.
✓ Methods: execute(), executeQuery(), executeUpdate().
✓ Not efficient for repeated or dynamic queries.
✓ Example:
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM users");
2. PreparedStatement Interface
✓ The PreparedStatement interface is used to execute parameterized SQL queries. It is
precompiled, which makes it faster and safer, especially against SQL injection.
✓ Allows placeholders (?) for parameters.
✓ Better performance for repeated queries.
✓ Prevents SQL injection.
✓ Example:
PreparedStatement pstmt = [Link]("SELECT * FROM users WHERE id
= ?");
[Link](1, 5);
ResultSet rs = [Link]();
3. CallableStatement Interface
✓ The CallableStatement interface is used to call stored procedures in the database. It
supports IN, OUT, and INOUT parameters.
✓ Used when business logic is stored in the database.
✓ Allows execution of complex operations via stored procedures.
✓ Example:
CallableStatement cstmt = [Link]("{call getUser(?)}");
[Link](1, 5);
ResultSet rs = [Link]();

16. Explain different transaction management methods in java.


Transaction management in Java ensures that a group of operations either complete
successfully as a unit or none of them take effect — maintaining data consistency. Java
provides different ways to manage transactions, mainly through JDBC and frameworks like
Spring.
In Java, transaction management ensures that multiple database operations are executed as
a single unit, maintaining data consistency. There are different types of transaction
management:
1. JDBC Transaction Management:
✓ Manual control using JDBC.
✓ Disable auto-commit (setAutoCommit(false)), then use commit() or rollback().
✓ Suitable for simple applications.
2. Programmatic Transaction Management (Spring):
✓ Manually manage transactions using TransactionTemplate or
PlatformTransactionManager.
✓ Provides fine-grained control.
3. Declarative Transaction Management (Spring):
✓ Uses annotations like @Transactional to define transaction boundaries.
✓ Easy to use and widely used in enterprise applications.
4. JTA (Java Transaction API):
✓ Used for managing distributed transactions across multiple resources or databases.
✓ Typically used in Java EE applications with application servers.

17. Explain resultset metadata interface.


The ResultSetMetaData interface in Java is used to get information about the columns of a
ResultSet object, such as column name, type, number of columns, etc. It is part of the
[Link] package and is very useful when you don't know the structure of the table in
advance (like in dynamic queries).
1. getColumnCount() – Returns the number of columns in the ResultSet.
2. getColumnName(int column) – Returns the name of the specified column.
3. getColumnTypeName(int column) – Returns the data type name of the column (e.g.,
VARCHAR, INT).
4. isNullable(int column) – Checks if the column can accept null values.
5. isAutoIncrement(int column) – Checks if the column is auto-incremented.
ResultSetMetaData is mainly used in dynamic applications, report generators, or tools
where the structure of the database is not fixed or known beforehand.
• Example:
ResultSet rs = [Link]("SELECT * FROM users");
ResultSetMetaData rsmd = [Link]();
int columnCount = [Link]();
for(int i = 1; i <= columnCount; i++) {
[Link]("Column " + i + ": " + [Link](i));
}

18. Explain steps of jdbc connections in detail.


OR Explain how to insert records in a table using JDBC application.
JDBC (Java Database Connectivity) is a Java API that enables Java programs to connect to
and interact with databases using SQL. It allows operations like connecting to a database,
executing queries, and handling results.
1. Import packages
2. Load driver
3. Connect to DB
4. Create statement
5. Execute query
6. Process results
7. Close connection
1. Import JDBC Package : Import [Link].* to use JDBC classes and interfaces.
2. Load JDBC Driver : Use [Link]("driver_class_name") to load the database driver.
3. Establish Connection : Use [Link](url, username, password) to
connect to the database.
4. Create Statement : Use [Link]() or prepareStatement() to create a
SQL statement.
5. Execute Query : Use executeQuery() for SELECT and executeUpdate() for INSERT, UPDATE,
DELETE.
6. Process Result : Use ResultSet to read and handle the query output.
7. Close Connection : Close ResultSet, Statement, and Connection to free resources.
• Example:
import [Link];
import [Link];
import [Link];
public class SimpleInsertExample {
public static void main(String[] args) {
try {
Connection con = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password");
Statement stmt = [Link]();
String query = "INSERT INTO students (id, name, age) VALUES (1, 'Alice', 20)";
int rows = [Link](query);
if (rows > 0) {
[Link]("Record inserted successfully!");
}
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
19. Explain stored procedure in detail.
A stored procedure is a named group of SQL statements that perform a particular task and
is stored in the database. It can accept parameters, perform operations, and return results.
• Features:
1. Modularity: Write once, use multiple times.
2. Performance: Precompiled, so faster than executing raw SQL queries.
3. Security: Permissions can be controlled at the procedure level.
4. Maintainability: Centralized code that's easier to manage and update.
5. Reusability: Can be called by multiple programs/applications.
• Types of Parameters:
1. IN – Input parameter (default)
2. OUT – Output parameter
3. INOUT – Both input and output
• Advantages:
✓ Reduces code duplication.
✓ Enhances security (users can be restricted from direct access to tables).
✓ Supports complex business logic.
✓ Easy to debug and maintain.
• Disadvantages:
✓ Database dependent (not portable between DBMSs).
✓ Harder to version-control and manage compared to application code.
✓ Can increase server load if not written efficiently.
A stored procedure is a set of SQL statements that are saved and stored in the database. It is
a reusable, precompiled block of code that can be executed repeatedly without rewriting
the SQL commands every time.

20. Define cookies advantages and disadvantages in java.


OR What is cookie? Explain it with one example.
OR Write a note on cookie.
A cookie in Java is an object used to store user information across multiple HTTP requests. It
is commonly used for session tracking, personalization, and user preferences.
• Example (creating a cookie):
Cookie cookie = new Cookie("username", "John");
[Link](60*60*24); // 1 day
[Link](cookie);
• Advantages of Cookies:
1. Simplicity : Easy to implement and use in Java servlets.
2. Persistence : Can persist data across multiple sessions (if not expired).
3. Automatic Management : Browsers automatically send cookies with each request to
the server.
4. No Server Resource Required : Stored on the client-side, so server memory is not
used.
5. Tracking User Activity : Useful for tracking login status, shopping cart, preferences,
etc.
• Disadvantages of Cookies:
1. Limited Data Storage : Size limit (~4KB per cookie) and total number of cookies per
domain.
2. Security Risk : Cookies can be modified or stolen (via XSS or packet sniffing) if not
secured properly.
3. Client-Side Dependency : If the user disables cookies in the browser, they won’t work.
4. Privacy Concerns : Users may consider cookies as a privacy invasion, especially third-
party cookies.
5. No Structured Data : Only simple text values are supported, not complex data
structures.
• Example :
import [Link].*;
import [Link].*;
import [Link].*;
public class SetCookieServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
[Link]("text/html");
Cookie userCookie = new Cookie("username", "JohnDoe");
[Link](60*60);
[Link](userCookie);
PrintWriter out = [Link]();
[Link]("<h2>Cookie has been set!</h2>");
}
}
Cookies are small pieces of information that a web server sends to a client and are stored on
the client side. In Java, cookies are managed through the [Link] class.

21. Enlist different methods of cookies


1. Cookie(String name, String value)
✓ Constructor to create a new cookie with a name and value.
2. getName()
✓ Returns the name of the cookie.
✓ String name = [Link]();
3. getValue()
✓ Returns the value of the cookie.
✓ String value = [Link]();
4. setValue(String value)
✓ Sets/updates the value of the cookie.
✓ [Link]("newValue");
5. setMaxAge(int expiry)
✓ Sets the lifetime (in seconds) of the cookie:
✓ 0 → persists for that number of seconds
✓ 0 → deletes the cookie
✓ < 0 → cookie is temporary (deleted when browser closes)
6. getMaxAge()
✓ Returns the maximum age (expiry time) of the cookie.
7. setPath(String path)
✓ Defines the URL path the cookie is valid for.
8. getPath()
✓ Returns the path the cookie is valid for.
9. setDomain(String domain)
✓ Specifies the domain for which the cookie is valid.
10. getDomain()
✓ Returns the domain of the cookie.
11. setSecure(boolean flag)
✓ If set to true, cookie will only be sent over secure (HTTPS) connections.
12. getSecure()
✓ Returns true if the cookie is marked as secure.
13. setHttpOnly(boolean isHttpOnly)
✓ Marks the cookie as HTTP-only, making it inaccessible to JavaScript (helps prevent
XSS).
14. isHttpOnly()
✓ Returns whether the cookie is HTTP-only.

22. Discuss the concept of polymorphism in java and it's implementation using method
overloading.
Polymorphism in Java is one of the core concepts of Object-Oriented Programming (OOP). In
Java, polymorphism allows objects to take many forms, a single interface can be used with
different underlying forms (data types or classes).
Types of Polymorphism in Java:
1. Compile-time polymorphism (Static Binding)
2. Runtime polymorphism (Dynamic Binding)
• Implementation of polymorphism using method overloading
Polymorphism through method overloading is implemented at compile-time, where the
compiler determines which version of the method to call based on the method signature
(i.e., number, type, or order of parameters). This is known as compile-time polymorphism or
static binding.
public class AreaCalculator {
public int area(int side) {
return side * side;
}
public int area(int length, int width) {
return length * width;
}
public double area(double radius) {
return 3.14159 * radius * radius;
}

public static void main(String[] args) {


AreaCalculator calc = new AreaCalculator();
[Link]("Area of square: " + [Link](5));
[Link]("Area of rectangle: " + [Link](4, 6));
[Link]("Area of circle: " + [Link](3.5));
}
}
All methods have the same name area, but different parameter types or counts. This is
method overloading — a classic implementation of polymorphism.

[Link] the concept of java byte code and it's significance in java programming. How
does java byte code facilitate platform independence and portability of java application?
• Java byte code :
✓ When you write a Java program, you save it in a file with a .java extension. This
is your source code—the code you wrote.
✓ But computers can't understand Java directly. So, Java uses a compiler (javac)
to convert your code into something called bytecode. This bytecode is saved in
a .class file.
✓ Bytecode is not machine code, but a special set of instructions that can be
understood by the Java Virtual Machine (JVM).
• Byte code significance in java programming :
✓ Works Everywhere: Bytecode can run on any device or operating system
(Windows, Mac, Linux, etc.)—as long as that device has a JVM installed. That’s
why Java is called platform-independent.
✓ Write Once, Run Anywhere: You only need to write and compile your Java
program once. After that, it can run on any computer with a JVM—no need to
change the code.
✓ Portable: You can take your Java program (bytecode file) and run it anywhere
without changing anything. This makes it very easy to share and reuse
programs.
• Portability and independence :
✓ When you write Java code and compile it, it becomes bytecode.
✓ This bytecode can run on any device that has a Java Virtual Machine (JVM).
✓ Since JVMs are available for all operating systems (Windows, macOS, Linux,
Android, etc.), your Java program can run anywhere.
✓ Different computers speak different "languages" (machine code).
✓ Bytecode acts like a common language for all.
✓ The JVM on each computer acts like a translator—it understands bytecode and
converts it into the native machine code for that system.

24. What is RMI? Explain RMI architecture.


OR Discuss the steps involved in creating and executing an RMI application.
RMI (Remote Method Invocation) is a Java API that allows an object to invoke methods on an
object running in another Java Virtual Machine (JVM), possibly on a different physical
machine.
• RMI Architecture
RMI architecture consists of the following layers:
1. Stub and Skeleton Layer
✓ Stub (Client-side proxy): Acts as a gateway for the client. It forwards the request to the
remote object (on the server side).
✓ Skeleton (Server-side proxy): Receives requests from the stub, unpacks the parameters,
and invokes the method on the actual remote object.
2. Remote Reference Layer
✓ Manages references made by the client to the remote server objects.
✓ It handles the creation and management of the remote object references.
3. Transport Layer
✓ Handles the actual communication between the client and server JVMs.
✓ It is based on TCP/IP connections and manages the connection setup, request
transmission, and response return.
• RMI Working Process
1. The client calls a method on the stub.
2. The stub packs the parameters and forwards the request to the remote JVM.
3. The transport layer sends this request to the server.
4. The server-side skeleton unpacks the request and invokes the method on the actual remote
object.
5. The result is sent back through the same layers to the client.

• Steps to Create and Execute an RMI Application:


1. Define a remote interface that extends [Link] and declares remote methods.
2. Implement the remote interface in a class that extends UnicastRemoteObject.
3. Create an RMI server that binds the remote object to the RMI registry.
4. Create an RMI client that looks up the remote object and invokes methods.
5. Compile all the classes involved in the RMI application.
6. Start the RMI registry using the rmiregistry command.
7. Run the server to bind the remote object.
8. Run the client to interact with the remote object.
These steps will help you create and execute a basic RMI application for remote method
invocation.

25. What is Script let, Expression and Declaration in JSP?


A script let in JSP is a block of Java code embedded within the JSP page using <% ... %>, that
allows embedding arbitrary Java code inside a JSP file, which is inserted into the _jspService()
method of the servlet generated from the JSP.
✓ Syntax:
<%
// Java code here
%>
✓ Example:
<%
int a = 10;
int b = 20;
int sum = a + b;
[Link]("Sum is: " + sum);
%>
✓ Purpose: To insert Java code that is executed every time the page is requested.
• Expression
✓ Syntax: <%= expression %>
✓ Purpose: To output the result of a Java expression directly to the client (i.e., it is
evaluated and inserted into the HTML).
✓ Example:
<%= 5 + 10 %>
Output: 15
• Declaration
✓ Syntax: <%! declaration %>
✓ Purpose: To declare methods or variables that are available to the entire JSP
page.
✓ Example:
<%!
int square(int x) {
return x * x;
}
%>
Then you can use it in a script let or expression: <%= square(5) %>

26. Write simple steps to create servlet with one example.


➢ Steps to Create a Servlet:
1. Create a Java Servlet class that extends HttpServlet.
2. Override the doGet() or doPost() method.
3. Compile the servlet and place the .class file in the WEB-INF/classes directory.
4. Configure the servlet in the [Link] file (deployment descriptor) or use @WebServlet
annotation.
5. Deploy the application on a servlet container (e.g., Apache Tomcat).
6. Access the servlet using a web browser via URL mapping.
➢ Example :
import [Link].*;
import [Link].*;
import [Link].*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello, this is a simple servlet!</h1>");
}
}
26. Discuss about the super keyword in Java with an example.
In Java, the super keyword is used to refer to the immediate parent class of a subclass.
• It serves three main purposes:
1. Accessing parent class constructor : You can use super() to call the parent class constructor
from a child class.
2. Accessing parent class method : If a method is overridden in the subclass,
[Link]() can call the parent class version.
3. Accessing parent class field : If a field is hidden in the subclass (e.g., by having the same
name), [Link] accesses the parent class version.
• Example:
class Animal {
String name = "Animal";
void display() {
[Link]("This is an animal.");
}
}

class Dog extends Animal {


String name = "Dog";
void showName() {
[Link]("Name in child class: " + name);
[Link]("Name in parent class: " + [Link]); // accessing parent class field
}
void display() {
[Link](); // calling parent class method
[Link]("This is a dog.");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}

27. Give the differences between Abstract Class and Interface.


✓ We use abstract classes when you want to share code among several closely related
classes.
Ex: abstract class Animal {}
✓ We use interfaces when you want to define a role that other classes can play, regardless
of where they are in the class hierarchy.
Ex: Interface Flyable {}
28. What is JSP Explain JSP architecture with diagram.
JSP (JavaServer Pages) is a server-side technology used for developing dynamic web pages
based on HTML, XML, or other document types. JSP allows embedding Java code directly into
HTML using special tags.
It is part of the Java EE platform and runs on the server side, typically within a Servlet
container like Apache Tomcat.
• JSP Architecture
1. Client (Browser)
✓ The user sends an HTTP request (usually by clicking a link or submitting a form).
✓ This request is directed to a .jsp file on the server.
2. Web Server (Servlet Container)
✓ The web server (e.g., Apache Tomcat) receives the request.
3. JSP Engine
✓ The JSP engine translates the .jsp file into a Java Servlet.
✓ JSP is now treated like a normal servlet.
4. Java Compiler
✓ The converted Servlet file is compiled into a .class file (Java bytecode).
5. Servlet Loaded & Executed
✓ The Servlet (from the JSP) is loaded and executed.
✓ The service() method handles the request.
6. Response to Client
✓ The generated HTML is sent back to the client browser as the HTTP response.

29. What is ORM? Explain Hibernate architecture.


ORM (Object-Relational Mapping) is a technique that allows developers to interact with
relational databases using object-oriented programming languages. It maps database tables
to objects and their relationships, simplifying database interactions and reducing the need
for manual SQL queries.
Hibernate is one of the most popular ORM frameworks for Java. Its architecture is
designed to facilitate object-relational mapping and provides the following key components:
• Hibernate Architecture:
1. SessionFactory: A factory for creating Session objects, responsible for initializing the
connection and configuration.
2. Session: Manages the lifecycle of database operations, including CRUD operations. It is not
thread-safe.
3. Transaction: Handles transaction management (commit/rollback).
4. Configuration: Reads Hibernate configuration and setup for database connection.
5. Mapping Files/Annotations: Define the relationship between Java objects and database
tables.
6. Persistent Objects: Java objects that are managed by Hibernate and persisted to the
database.
7. HQL (Hibernate Query Language): Object-oriented query language to perform database
operations.
8. Criteria API: A programmatic way to create database queries.
Hibernate abstracts complex database operations, making it easier to work with databases in
a Java application.

30. What is spring Framework? Write important features and advantages of spring
framework.
OR What is spring Framework? Write important features and benefits in application
development
Spring Framework is a comprehensive, open-source framework for building Java-based
enterprise applications. It simplifies Java development by providing services like dependency
injection, aspect-oriented programming, and transaction management.
• Features:
1. Dependency Injection (DI): Manages object creation and dependency relationships,
promoting loose coupling.
2. Aspect-Oriented Programming (AOP): Separates cross-cutting concerns like logging and
security from business logic.
3. Spring MVC: A flexible framework for building web applications.
4. Transaction Management: Supports both declarative and programmatic transaction
management.
5. Spring Boot: Simplifies application setup and configuration with embedded servers and
starter templates.
6. Security: Provides a comprehensive security framework for authentication and
authorization.
• Advantages/ benefits:
1. Loose Coupling: Promotes modular, flexible, and maintainable code.
2. Easy Testing: DI makes unit testing easier by injecting dependencies.
3. Comprehensive: Covers web development, data access, security, and more.
4. Integration: Easily integrates with other frameworks like Hibernate and JPA.
5. Scalability: Suitable for both small and large applications.
6. Declarative Configuration: Reduces boilerplate code with annotations and configuration
files.
Spring makes Java development more efficient, maintainable, and scalable.

31. Explain how do you create a new database using JDBC application.
To create a new database using JDBC:
1. Set up JDBC Driver: Include the appropriate JDBC driver in your project (e.g., MySQL,
PostgreSQL).
2. Establish Connection: Connect to the database server (not a specific database) using
[Link]().
Connection conn = [Link]("jdbc:mysql://localhost:3306/", "root",
"password");
3. Create Database: Use a Statement object to execute the SQL command CREATE DATABASE.
Statement stmt = [Link]();
[Link]("CREATE DATABASE myNewDatabase");
4. Close Connection: Always close the connection after the operation.
[Link]();
This process allows you to create a new database programmatically using JDBC.

32. Discuss some key points of Java Bean with an example.


OR Write a note on java beans.
A JavaBean is a Java class that follows specific conventions to make it easy to use in different
frameworks. Key points include:
1. Private Fields: Fields are private to promote encapsulation.
2. No-argument Constructor: It must have a default constructor to allow easy instantiation.
3. Serializable: It implements the Serializable interface for object persistence.
4. Getter and Setter Methods: Public methods to get (retrieve) and set (modify) the values of
private fields.
• Example:
public class Person implements Serializable {
private String name;
private int age;
public Person() {}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
[Link] = age;
}
}
This Person class follows JavaBean conventions, making it easy to use in various tools and
frameworks.
JavaBeans are often used in frameworks like JSP (JavaServer Pages) and Java EE (Enterprise
Edition) for easy data management and manipulation.

33. Describe the lifecycle of a session in JSP. Explain how a session is created maintained
and destroyed.
A session in JSP is used to maintain user-specific data across multiple requests. The session
lifecycle involves
• Lifecycle of a Session in JSP:
1. Session Creation:
Starts when a user visits a JSP page for the first time.
JSP automatically creates an HttpSession object.
2. Session Identification:
A unique session ID is assigned and sent to the client via a cookie or URL rewriting.
3. Session Use/Maintenance:
Data is stored using [Link]() and retrieved with [Link]().
4. Session Timeout:
If the user is inactive for a default period (e.g., 30 minutes), the session expires automatically.
5. Session Destruction:
Happens automatically (timeout) or manually using [Link]().
This process ensures that user data is maintained across multiple requests during a visit.
✓ Session Creation:
A session is created automatically when a client accesses a JSP page for the first time.
✓ Session Maintenance:
The session is maintained using a unique session ID, stored in:
Cookies (default)
URL rewriting (if cookies are disabled)
✓ Session Destruction:
A session is destroyed in two ways:
a) Automatically: After a timeout period of inactivity (default is 30 minutes).
b) Manually:
Using [Link]() method: [Link]();
This session management ensures personalized and secure interaction with users across
multiple pages.

34. Discuss the advantages and disadvantages of using Hibernate as an ORM framework
compared to JDBC.
Hibernate and JDBC are both used for database interaction in Java applications, but they
follow different approaches. JDBC is a low-level API for interacting with databases using SQL
directly, while Hibernate is an Object-Relational Mapping (ORM) framework that abstracts
the database interaction by mapping Java classes to database tables.
Here are the advantages and disadvantages of using Hibernate compared to JDBC:
• advantages of Hibernate over JDBC:
1. Reduces boilerplate code.
2. Uses object-oriented approach (ORM).
3. Supports database independence.
4. Provides HQL for easier queries.
5. Handles automatic table mapping.
6. Offers caching for better performance.
7. Simplifies transaction management
8. Supports lazy loading and batching.
9. Enables schema auto-generation.
• disadvantages of Hibernate compared to JDBC:
1. Steeper learning curve.
2. More memory and performance overhead.
3. Less control over generated SQL.
4. Harder to debug and optimize queries.
5. Slower startup due to configuration.
6. Larger application size.
7. Complex for advanced or legacy mappings.

35. Write a short note on following


a) Session b) Struts c) JSF d) Garbage collector
1. Session
A session is a server-side mechanism used to store user-specific data across multiple HTTP
requests. Since HTTP is stateless, sessions help maintain user state like login status or
shopping cart contents. When a user connects, a session is created with a unique ID, usually
stored in a cookie on the client. Data is stored on the server and accessed using methods like
setAttribute() and getAttribute(). Sessions are temporary and expire after a period of
inactivity. Secure session handling involves using HTTPS, regenerating session IDs, and
avoiding sensitive data storage. Sessions are managed in most frameworks including Java,
PHP, and Python. They improve user experience by preserving state. Efficient session
management is crucial in high-traffic applications. Proper session handling enhances both
performance and security.
2. Struts
Struts is an open-source web application framework for developing Java EE applications using
the Model-View-Controller (MVC) design pattern. It separates the application into Model
(data), View (UI), and Controller (logic), making code easier to manage and test. The core of
Struts is the ActionServlet, which routes user requests to specific Action classes. It supports
JSP for views and integrates with technologies like JDBC, Hibernate, and Spring. Struts
provides built-in validation and error-handling mechanisms. Configuration is handled via XML
files, allowing flexible application control. It improves scalability by organizing code into
modules. Although newer frameworks have emerged, Struts remains foundational in
enterprise Java development. It simplifies complex application workflows and promotes
reusable code. Struts laid the groundwork for modern Java MVC frameworks.
3. JSF (Java Server Faces)
JSF is a Java-based web framework designed to build component-based user interfaces for
server-side applications. It is part of Java EE and follows the MVC architecture. JSF simplifies
web UI development by using reusable UI components like forms, buttons, and data tables.
It supports managed beans for business logic and [Link] for navigation and
configuration. JSF handles input validation, event processing, and page navigation
automatically. It integrates easily with tools like AJAX and Facelets for dynamic interfaces.
Developers can use annotations for simpler configuration. JSF manages session and request
scopes to maintain state across user actions. It promotes rapid development of Java-based
web apps. Though less popular today, JSF remains a standard in enterprise-level applications.
4. Garbage Collector
The Garbage Collector (GC) in Java is a process that automatically frees memory by destroying
objects no longer in use. It runs in the background, improving memory management and
preventing memory leaks. Java developers don’t need to manually deallocate memory like in
C/C++. The GC identifies unreachable objects and reclaims their memory. Java uses several
algorithms like Mark and Sweep, Generational GC, and G1 GC. Objects are divided into Young,
Old, and Permanent generations for efficient collection. The GC enhances performance by
optimizing memory usage. However, improper object references can delay collection.
Developers can suggest garbage collection with [Link](), but the JVM decides when to
execute it. The GC is a key feature of Java's robustness and portability.

You might also like