Method Overloading Difference Between Overloading and
Occurs when multiple methods in the same class Overriding
have the same name but different parameters.
Parameters can differ in:
o Number of arguments Method
Method Overriding
Overloading
o Type of arguments
o Order of arguments Same class Parent and Child class
Return type alone cannot differentiate overloaded Different
Same parameters
methods. parameters
It is an example of Compile-Time Polymorphism Compile-time
Runtime binding
(Static Binding). binding
Improves code readability and reusability. Inheritance not
Inheritance required
required
Example Static Dynamic
polymorphism polymorphism
Increases Provides specific
readability implementation
Relation with Polymorphism
Polymorphism means "many forms."
Method Overloading achieves Compile-Time
Polymorphism.
Method Overriding achieves Runtime
Polymorphism.
Both allow a single method name to behave
differently in different situations.
Combined Java Program
Method Overriding
Occurs when a subclass provides its own
implementation of a method already defined
in the parent class.
Method name, return type, and parameters
must be the same.
Requires inheritance.
It is an example of Runtime Polymorphism
(Dynamic Binding).
Used to achieve specialized behavior in child
classes.
Example
1. Thread Life Cycle in Java (≈250
Words)
Introduction 2. Thread Creation Methods in Java
A thread is the smallest unit of execution within a (≈250 Words)
process. Introduction
Java supports multithreading to perform multiple Multithreading allows multiple threads to execute
tasks simultaneously. concurrently.
During execution, a thread passes through several Java provides two main ways to create threads.
states known as the Thread Life Cycle. Method 1: Extending the Thread Class
States of a Thread Create a class that extends the Thread class.
1. New State Override the run() method.
A thread is in the New state when it is created but Start the thread using the start() method.
not yet started. Example
Example: Thread t = new Thread();
2. Runnable State
After calling start(), the thread enters the Runnable
state.
It is ready to run and waits for CPU allocation.
3. Running State
The thread is actively executing its task.
The scheduler selects the thread from the Runnable
state.
4. Blocked/Waiting State
A thread enters this state when it waits for a
resource, lock, or another thread to complete.
Methods like sleep(), wait(), and join() can cause
this state.
5. Terminated (Dead) State
The thread enters this state after completing its
execution or being stopped. Advantages
Once terminated, it cannot be restarted. Simple and easy to implement.
Disadvantages
Thread Life Cycle Diagram Java does not support multiple inheritance.
Extending Thread prevents extending another class.
Method 2: Implementing Runnable Interface
Create a class that implements Runnable.
Define the run() method.
Pass the object to a Thread object and call start().
Example
Advantages
Supports multiple inheritance through interfaces.
Better for large applications.
Promotes code reusability.
3. Synchronization in Java (≈250 Words) Advantages
Introduction Prevents race conditions.
Synchronization is a mechanism used to control Maintains data consistency.
access to shared resources by multiple threads. Ensures thread safety.
It prevents data inconsistency and thread Disadvantages
interference. Increases execution time.
Synchronization ensures that only one thread Excessive synchronization may reduce
accesses a critical section at a time. performance.
Need for Synchronization
Multiple threads may access the same data Exception Handling in Java
simultaneously. Introduction
This can lead to incorrect results. Exception Handling is a mechanism used to handle
Synchronization helps maintain data integrity and runtime errors in a program.
consistency. It prevents abnormal termination and ensures
Example Without Synchronization smooth execution.
Java provides keywords such as try, catch, throw,
throws, and finally to handle exceptions.
1. try Block
The try block contains code that may generate an
exception.
It must be followed by either a catch block or a
finally block.
Example
try {
int a = 10 / 0;
}
2. catch Block
The catch block handles the exception generated in
the try block.
It prevents the program from terminating
unexpectedly.
Synchronized Method Example
try {
int a = 10 / 0;
}
catch (ArithmeticException e) {
[Link]("Division by zero not
allowed");
}
3. throw Keyword
The throw keyword is used to explicitly create and
throw an exception.
It transfers control to the nearest catch block.
Example
The synchronized keyword allows only one int age = 15;
thread to execute the method at a time. if(age < 18) {
Types of Synchronization throw new ArithmeticException("Not Eligible");
1. Method Synchronization }
Entire method is synchronized. 4. finally Block
Uses synchronized keyword with method The finally block always executes whether an
declaration. exception occurs or not.
2. Block Synchronization It is generally used for resource cleanup.
Only a specific block of code is synchronized. Example
Improves performance. try {
int a = 10 / 2;
}
catch(Exception e) {
[Link](e);
}
finally {
[Link]("Finally Block Executed");
}
Checked vs Unchecked Exceptions Out Of Memory Error Handling
Definition
Checked Exception Unchecked Exception OutOfMemoryError occurs when the Java Virtual
Machine (JVM) cannot allocate sufficient memory for
Checked at compile
Checked at runtime an object.
time
It belongs to the Error class and is generally caused
Must be handled by by excessive memory usage.
Handling is optional
programmer Example
Subclass of
Subclass of Exception
RuntimeException
Compiler gives error if
No compile-time error
not handled
Example:
Example: IOException,
ArithmeticException,
SQLException
NullPointerException
Checked Exception Example
Causes
Creating very large objects.
Memory leaks.
Infinite object creation inside loops.
Insufficient heap memory.
Handling Techniques
Use efficient data structures.
Release unused objects.
Increase JVM heap size using -Xmx.
Avoid memory leaks.
Conclusion
Exception handling improves program reliability and
prevents abrupt termination.
Unchecked Exception Example - int a = 10 / 0;
Using try, catch, throw, and finally helps manage
ArithmeticException
errors effectively.
Definition
Proper handling of ArithmeticException and
ArithmeticException occurs when an illegal
OutOfMemoryError ensures stable and robust Java
arithmetic operation is performed.
applications.
Most commonly caused by division by zero.
Example
Causes
Division by zero.
Invalid mathematical calculations.
Prevention
Validate input before calculations.
Use try-catch blocks.
JDBC (Java Database Connectivity)
Introduction
JDBC (Java Database Connectivity) is a Java API used to Database-independent.
connect Java applications with databases. 4. Type 4 Driver (Thin Driver)
It provides methods and interfaces to execute SQL Pure Java Driver.
queries and retrieve results. Direct communication with database.
JDBC enables communication between Java programs Most commonly used.
and databases such as MySQL, Oracle, SQL Server, and Example
PostgreSQL. For MySQL: [Link]("[Link]");
It is part of the Java Standard Library ([Link]
package). Executing SQL Queries Using JDBC
Step 1: Create Connection
JDBC Architecture
Components of JDBC Architecture
1. Java Application
o The client program that requests database
operations.
2. JDBC API
o Provides classes and interfaces for database
connectivity.
3. JDBC Driver Manager
o Loads and manages JDBC drivers.
o Establishes connection with the database.
Step 2: Create Statement
4. JDBC Driver
Statement stmt = [Link]();
o Converts JDBC calls into database-specific
Step 3: Execute Query
commands. Insert Query
5. Database [Link](
o Stores and manages data. "INSERT INTO student VALUES(101,'Rahul')");
JDBC Architecture Diagram
Java Application Select Query
| ResultSet rs =
V [Link]("SELECT * FROM student");
JDBC API
| Step 4: Process Result
V while([Link]()) {
Driver Manager [Link](
| [Link](1)+" "+
V [Link](2));
JDBC Driver }
|
V Step 5: Close Connection
Database [Link]();
Working of JDBC
Load JDBC Driver.
Establish connection.
Create Statement object.
Execute SQL Query.
Process Result.
Close connection.
JDBC Drivers
Definition
JDBC Driver is software that enables Java
applications to interact with databases.
Types of JDBC Drivers
1. Type 1 Driver (JDBC-ODBC Bridge)
Uses ODBC Driver.
Slow performance.
Deprecated in Java 8.
2. Type 2 Driver (Native API Driver)
Uses native database libraries. Database Connectivity Program (MySQL)
Better performance than Type 1.
3. Type 3 Driver (Network Protocol Driver)
Uses middleware server.
Java RMI (Remote Method Invocation) is a
distributed computing technology that allows a Java
program running on one machine to invoke
methods of an object located on another machine.
It enables communication between distributed
applications over a network.
RMI follows the Client-Server architecture.
Introduced in the [Link] package.
RMI Architecture
Components of RMI Architecture
1. Client
Requests services from the remote object.
Invokes methods located on a remote server.
2. Stub
Acts as a proxy for the remote object.
Receives requests from the client and forwards
them to the server.
3. Remote Reference Layer
Manages communication between client and server.
Handles method invocation and return values.
4. Skeleton (Old RMI Architecture)
Receives requests from the stub.
Passes requests to the actual remote object.
(Not required in modern Java versions.)
5. Remote Object
Contains business logic and methods that can be
called remotely.
6. RMI Registry
Stores references to remote objects.
Helps clients locate remote services.
RMI Architecture Diagram
CLIENT
|
V
STUB
|
V
Remote Reference Layer
|
V
RMI Registry
|
V
Remote Object
SERVER
Output;-
101 Rahul
102 Mohan
103 Aman
Advantages of JDBC
Platform independent.
Supports multiple databases.
Easy database connectivity.
Supports SQL operations.
Provides secure and efficient data access. Client-Server Communication in RMI
Working Process
1. Server creates a remote object.
2. Server registers the object with the RMI Registry.
3. Client searches the Registry for the remote object.
Java RMI (Remote Method Invocation) 4. Registry returns the Stub object.
Introduction 5. Client invokes methods using the Stub.
6. Request is sent to the Server. }
7. Server executes the method. catch(Exception e) {
8. Result is returned to the Client. [Link](e);
Advantages }
Supports distributed applications. }
Object-oriented communication. }
Easy method invocation across networks.
Platform independent. Explanation
Remote Method Invocation (RMI) Implementation Creates remote object.
Step 1: Create Remote Interface Registers object with RMI Registry.
import [Link].*;
Step 4: Create Client Program
public interface Hello extends Remote { import [Link].*;
String message() throws RemoteException;
} public class Client {
Explanation public static void main(String args[]) {
Interface extends Remote.
Methods throw RemoteException. try {
Hello h = (Hello)
Step 2: Implement Remote Interface [Link]("rmi://localhost/HelloService");
import [Link].*;
import [Link].*; [Link](
[Link]());
public class HelloImpl extends UnicastRemoteObject
implements Hello { } catch(Exception e) {
[Link](e);
HelloImpl() throws RemoteException { }
super(); }
} }
public String message() { Explanation
return "Welcome to Java RMI"; Looks up remote object.
} Calls remote method.
} Displays result.
Output
Explanation Server Side
Implements remote methods. Server is Running.
Extends UnicastRemoteObject. Client Side
Welcome to Java RMI
Advantages of Java RMI
Supports distributed computing.
Enables communication between remote objects.
Platform independent.
Provides object-oriented networking.
Simplifies client-server application development.
Java Servlets
Introduction
A Servlet is a Java program that runs on a web
server and handles client requests.
Servlets are used to create dynamic web
Step 3: Create Server Program applications.
They process requests from web browsers and
import [Link].*; generate responses.
The [Link] and [Link] packages
public class Server { provide servlet functionality.
public static void main(String args[]) {
try { Servlet Life Cycle
HelloImpl obj = new HelloImpl(); The life cycle of a servlet is managed by the servlet
[Link]("HelloService", obj); container (e.g., Apache Tomcat).
[Link]( Stages of Servlet Life Cycle
"Server is Running..."); 1. Loading and Instantiation
The servlet container loads the servlet class. protected void doGet(HttpServletRequest req,
An object of the servlet class is created. HttpServletResponse res) {
2. Initialization (init()) [Link]().println("GET Request");
Called only once when the servlet is loaded. }
Used to initialize resources such as database
connections. POST Example
public void init() { protected void doPost(HttpServletRequest req,
[Link]("Servlet Initialized"); HttpServletResponse res) {
} [Link]().println("POST Request");
}
3. Service (service())
Called whenever a client sends a request. Request and Response Handling in Servlets
Processes requests and generates responses Request Handling
public void service(ServletRequest req, The client sends an HTTP request to the server.
ServletResponse res) { The servlet receives the request through the
// Request Processing HttpServletRequest object.
} Request parameters can be retrieved using
getParameter().
4. Destruction (destroy()) String name =
Called once before the servlet is removed from [Link]("username");
memory.
Used to release resources. Common Methods
public void destroy() { Method Purpose
[Link]("Servlet Destroyed"); getParamete
} Retrieves form data
r()
Servlet Life Cycle Diagram Returns GET or
getMethod()
Client Request POST
| Returns request
V getHeader()
header
Loading & Instantiation getCookies() Returns cookies
|
V
init()
|
V
service()
|
V
service()
|
V
service()
|
V
Response Handling
destroy()
The servlet sends output to the client using the
Advantages
HttpServletResponse object.
Efficient resource management.
Response data is written using PrintWriter.
Faster than CGI programs.
Example
Supports multiple client requests.
PrintWriter out =
[Link]();
Difference Between GET and POST
[Link]("Welcome User");
GET Method POST Method
Used to retrieve data Used to send data Method Purpose
Data visible in URL Data hidden in request body Writes
Less secure More secure getWriter()
response
Limited data size Large amount of data can be sent
setContentTyp Sets MIME
Faster execution Slightly slower
e() type
Can be bookmarked Cannot be bookmarked
Used for searching and fetching Used for registration, login, and form sendRedirect() Redirects user
records submission addCookie() Adds cookie
GET Example
Complete Servlet Example