The java environment – JVM, JDK & JRE
The Java Development Kit (JDK) is a cross-platformed software development environment that
offers a collection of tools and libraries necessary for developing Java-based software
applications and applets. It is a core package used in Java, along with the JVM (Java Virtual
Machine) and the JRE (Java Runtime Environment).
The Java Development Kit is an implementation of one of the Java Platform:
• Standard Edition (Java SE),
• Java Enterprise Edition (Java EE),
• Micro Edition (Java ME),
Contents of JDK
The JDK has a private Java Virtual Machine (JVM) and a few other resources necessary for the
development of a Java Application.
JDK contains:
• Java Runtime Environment (JRE),
• An interpreter/loader (Java),
• A compiler (javac),
• An archiver (jar) and many more.
The Java Runtime Environment in JDK is usually called Private Runtime because it is separated
from the regular JRE and has extra content. The Private Runtime in JDK contains a JVM and all the
class libraries present in the production environment, as well as additional libraries useful to
developers, e.g, internationalization libraries and the IDL libraries.
The JVM is the engine that runs Java bytecode. It's platform-dependent (specific to OS and
architecture) but runs the same compiled .class bytecode.
Key Responsibilities:
• Loads, verifies, and executes bytecode.
• Provides runtime environment.
• Performs garbage collection.
• Handles security and memory management.
JRE in Java
Java Runtime Environment (JRE) is an open-access software distribution that has a Java class
library, specific tools, and a separate JVM. In Java, JRE is one of the interrelated components in
the Java Development Kit (JDK). It is the most common environment available on devices for
running Java programs. Java source code is compiled and converted to Java bytecode. If you want
to run this bytecode on any platform, you need JRE. The JRE loads classes check memory access
and get system resources. JRE acts as a software layer on top of the operating system.
Components of Java JRE
The components of JRE are mentioned below:
• Integration libraries include Java Database Connectivity (JDBC)
• Java Naming, Interface Definition Language (IDL)
• Directory Interface (JNDI)
• Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP)
• Remote Method Invocation (RMI)
• Scripting
The JRE provides everything needed to run Java applications — but not to develop them.
Includes:
• JVM
• Core Java class libraries (e.g., java.lang, java.util)
• Supporting files (like property files, config files)
Use JRE when you just want to run Java programs.
It does not include development tools like the compiler.
Working of JRE
Java Development Kit (JDK) and Java Runtime Environment (JRE) both interact with each other to
create a sustainable runtime environment that enables Java-based applications to run
seamlessly on any operating system. The JRE runtime architecture consists of the following
elements as listed:
1. ClassLoader
2. ByteCode verifier
3. Interpreter
Now let us briefly about them as follows:
• ClassLoader: Java ClassLoader dynamically loads all the classes necessary to run a Java
program. Because classes are only loaded into memory whenever they are needed, the
JRE uses ClassLoader will automate this process when needed. During the initialization
of the JVM, three classLoaders are loaded:
o Bootstrap class loader
o Extensions class loader
o System class loader
• Bytecode Verifier: The bytecode checker ensures the format and precision of Java code
before passing it to the interpreter. If the code violates system integrity or access rights,
the class is considered corrupt and will not load.
• Interpreter: After loading the byte code successfully, the Java interpreter creates an
object of the Java virtual machine that allows the Java program to run natively on the
underlying machine.
How JVM Works – JVM Architecture
JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls
the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and expect it to run on any other Java-enabled system without
any adjustment. This is all possible because of JVM.
When we compile a .java file, .class files(contains byte-code) with the same class names present
in .java file are generated by the Java compiler. This .class file goes into various steps when we
run it. These steps together describe the whole JVM.
1. Class Loader Subsystem
It is mainly responsible for three activities.
• Loading
• Linking
• Initialization
Differences Between JDK, JRE and JVM
Aspect JDK JRE JVM
Used to develop Java Used to run Java
Executes Java bytecode
Purpose applications applications
JVM is OS-specific, but
Platform-dependent Platform-dependent
Platform bytecode is platform-
(OS specific) (OS specific)
Dependency independent
JRE + Development ClassLoader, JIT
JVM + Libraries (e.g.,
tools (javac, debugger, Compiler, Garbage
rt.jar)
Includes etc.) Collector
Aspect JDK JRE JVM
Running a Java
Writing and compiling Convert bytecode into
application on a
Java code native machine code
Use Case system
Object-Oriented Programming (OOP) Principles in Java
OOP is a programming paradigm based on the concept of "objects", which are instances of
classes. Java is a fully object-oriented language (except for primitive types), and it follows 4
main OOP principles:
1. Encapsulation
Definition: Wrapping data (variables) and code (methods) together into a single unit, usually a
class, and restricting direct access to some of the object’s components.
Key Points:
• Achieved using access modifiers (private, public, protected).
• Use getters and setters to control access.
Example:
class Person {
private String name; // private = encapsulated
public void setName(String name) {
this.name = name;
public String getName() {
return name;
2. Abstraction
Definition: Hiding complex implementation details and showing only the essential features of
an object.
Key Points:
• Achieved using abstract classes and interfaces.
• Helps reduce complexity and improve maintainability.
Example:
abstract class Animal {
abstract void makeSound(); // abstract method
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
3. Inheritance
Definition: The ability of one class (child/subclass) to inherit properties and behavior (methods
and fields) from another class (parent/superclass).
Key Points:
• Promotes code reusability.
• Use the extends keyword.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
class Cat extends Animal {
void meow() {
System.out.println("Meow");
4. Polymorphism
Definition: The ability of an object to take many forms. It allows you to use a single interface or
method name to represent different behaviors.
Two Types:
• Compile-time (Method Overloading)
• Runtime (Method Overriding)
Example (Runtime Polymorphism):
class Animal {
void sound() {
System.out.println("Animal sound");
class Dog extends Animal {
void sound() {
System.out.println("Bark");
Summary Table
Principle Description Achieved Using
Protects data and hides internal Private variables,
Encapsulation
implementation getters/setters
Abstraction Shows only essential features Abstract classes, interfaces
Inheritance Reuses existing code through hierarchy extends keyword
Polymorphism Same interface, different behavior Method overloading/overriding
Comparison of java with C and C++
COMPARISON C C++ Java
PARAMETER
Developed by Dennis M. Ritchie Bjarne Stroustrup James Gosling created
created the C created C++ in 1979 at Java while working for Sun
programming Bell Labs. It was Microsystems. Oracle is
language in 1972. created as a C now the owner of it.
language extension.
Programming C is a procedural Both procedural and Java is an object-oriented
model programming object-oriented programming language.
language programming are
supported by it.
Type of language As it connects the C++ is a high-level Due to the fact that Java
gaps between language. code is converted into
machine-level and machine language via a
high-level languages, compiler or interpreter,
C is a middle-level Java is a high-level
language. language.
Compilation C is not understood; it C++ cannot be Java can be interpreted as
and is just compiled. interpreted; it can only well as compiled.
Interpretation be compiled.
Memory Functions like Using the 'new' Java supports memory
Allocation malloc(), calloc(), etc. keyword, memory allocation through the
can be used to allocation is usage of the "new"
allocate memory in C accomplished in C++. keyword.
programs.
Feature C C++ Java
Procedural + Object- Pure Object-Oriented
Type Procedural
Oriented (except primitives)
Platform-dependent
Platform-independent
Platform Dependency (compiled to machine Platform-dependent
(via JVM)
code)
Feature C C++ Java
Manual (using malloc, Manual (new/delete) Automatic (Garbage
Memory Management
free) + RAII Collection)
No direct support
Pointer Support Full Full
(restricted)
Supported (with Not directly (supported
Multiple Inheritance Not applicable
classes) via interfaces)
Operator Overloading Not supported Supported Not supported
Function Overloading Not supported Supported Supported
Supported
Templates / Generics Not supported Supported (Generics)
(Templates)
Compiled to machine Compiled to machine Compiled to bytecode
Compilation
code code (JVM runs it)
Slower (due to JVM and
Speed/Performance Very Fast Fast
GC overhead)
Possible (with Built-in support (Swing,
GUI Development Not built-in
libraries) JavaFX)
Limited (via setjmp,
Exception Handling Supported Strongly supported
longjmp)
Rich (Collections, IO,
Standard Library Small Large (STL, etc.)
Networking)
System, game, and
System/embedded Web, mobile, and
Used For application
programming enterprise applications
development
Language Level Low-level Mid-level High-level
Language Fundamentals
Language fundamentals are the basic building blocks of any Java program. They include
data types, variables, operators, control structures, and how Java code is structured.
Here’s a summary of the most important language fundamentals in Java:
1. Data Types
Java is a statically-typed language, meaning each variable must have a declared type.
Primitive Data Types (8 total)
Type Size Example Description
byte 1 byte byte a = 10; Small integers
short 2 bytes short s = 200; Larger than byte
int 4 bytes int x = 1000; Commonly used integers
long 8 bytes long l = 10000L; Very large integers
float 4 bytes float f = 5.6f; Single-precision decimals
double 8 bytes double d = 5.6; Double-precision decimals
char 2 bytes char c = 'A'; Single Unicode character
boolean 1 bit boolean b = true; True or false
2. Variables
Variables are used to store data in memory.
Syntax:
int age = 25;
String name = "Alice";
Types:
• Local variables – inside methods
• Instance variables – inside classes but outside methods
• Static variables – shared across all instances
3. Operators
Java includes various operators:
Type Example Description
Arithmetic + - * / % Math operations
Type Example Description
Relational == != > < >= <= Comparison
Logical `&&
Assignment = += -= Assign and modify values
Unary ++ -- Increment and decrement
Bitwise `& ^ ~ << >>`
4. Control Structures
Used to control the flow of execution.
Conditional Statements:
if (x > 0) {
System.out.println("Positive");
} else {
System.out.println("Non-positive");
}
Switch Statement:
switch (day) {
case 1: System.out.println("Monday"); break;
default: System.out.println("Other day");
}
Loops:
// for loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
// while loop
int i = 0;
while (i < 5) {
System.out.println(i++);
}
5. Classes and Objects
Java is object-oriented — code is written inside classes, and objects are used to access
data/methods.
class Car {
String brand = "Toyota";
void honk() {
System.out.println("Beep!");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
System.out.println(myCar.brand);
myCar.honk();
}
}
6. Packages and Import Statements
Packages group related classes.
import java.util.Scanner;
7. Main Method Structure
Every Java application starts from the main method:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
1. Java Environment: The programming environment of Java consists of three
components mainly:
• JDK
• JRE
• JVM
2. Java Basic Syntax : Every programming language has its own set of rules to
declare, define and work on its components. Reading and learning about all of
them together is difficult. Therefore here is a simple task of printing “Hello World”
in Java . During this process, major components and their syntaxes are explained
clearly. Learn about printing “Hello World” in Java here: Beginning Java
programming with Hello World Example
3. Comments in Java : In a program, comments take part in making the program
become more human-readable by placing the detail of code involved and proper
use of comments makes maintenance easier and finding bugs easily. Comments
are ignored by the compiler while compiling the code. Learn about Comments in
Java here: Comments in Java
4. Data Types in Java : Each variable in Java has an associated data type. Each data
type requires different amounts of memory and has some specific operations
which can be performed over it. Learn about different data types in Java here: Data
types in Java
5. Variables in Java : A variable is the name given to a memory location. It is the
basic unit of storage in a program. Learn about Variables in Java here: Variables
in Java
6. Keywords in Java : Keywords or Reserved words are the words in a language that
are used for some internal process or represent some predefined actions. These
words are therefore not allowed to use as variable names or objects. Doing this
will result in a compile-time error. Learn about Keywords in Java here: Keywords
in Java
7. Operators in Java : Operators are the foundation of any programming language.
Thus the functionality of Java programming language is incomplete without the
use of operators. We can define operators as symbols that help us to perform
specific mathematical and logical computations on operands. In other words, we
can say that an operator operates the operands. Learn about Operators in Java
here: Operators in Java
8. Decision Making (Control Statements) in Java : Decision Making in
programming is similar to decision making in real life. In programming also we face
some situations where we want a certain block of code to be executed when some
condition is fulfilled. A programming language uses control statements to control
the flow of execution of the program based on certain conditions. These are used
to cause the flow of execution to advance and branch based on changes to the
state of a program. Learn about Decision Making in Java here: Decision Making
in Java
9. Loops in Java : Looping in programming languages is a feature which facilitates
the execution of a set of instructions/functions repeatedly while some condition
evaluates to true. Java provides three ways for executing the loops. While all the
ways provide similar basic functionality, they differ in their syntax and condition
checking time. Learn about Loops in Java here: Loops in Java
Unit-3
A Servlet is a Java class used to build web applications. It runs on a Java-enabled web
server like Apache Tomcat. The Servlet Life Cycle defines how a servlet is loaded,
initialized, handles requests, and is destroyed.
Servlet Life Cycle Stages
The life cycle of a servlet is managed by the Servlet Container (e.g., Tomcat) and
consists of 5 main steps:
1. Loading and Instantiation
• When the servlet is first requested (or on server startup if configured), the servlet
container:
o Loads the servlet class
o Creates an instance of the servlet using the no-arg constructor.
public class MyServlet extends HttpServlet {
public MyServlet() {
System.out.println("Servlet is being instantiated.");
}
}
2. Initialization (init() method)
• The servlet container calls the init(ServletConfig config) method once after
instantiation.
• This method is used for initial setup (e.g., opening database connections,
reading configuration).
public void init() throws ServletException {
System.out.println("Servlet is initialized.");
}
3. Request Handling (service() method)
• For every client request, the servlet container calls the
service(HttpServletRequest req, HttpServletResponse res) method.
• This method determines the HTTP method (GET, POST, etc.) and calls:
o doGet() for GET requests
o doPost() for POST requests, etc.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().println("Hello from GET method!");
}
4. Destruction (destroy() method)
• Called once when the servlet is being taken out of service (e.g., on server
shutdown or app undeployment).
• Used for cleanup tasks like closing DB connections, releasing resources.
public void destroy() {
System.out.println("Servlet is being destroyed.");
}
1. Loading a Servlet
The first stage of the Servlet lifecycle involves loading and initializing the Servlet. The
Servlet container performs the following operations:
• Loading: The Servlet container loads the Servlet class into memory.
• Instantiation: The container creates an instance of the Servlet using the no-
argument constructor.
The Servlet container can load the Servlet at one of the following times:
• During the initialization of the web application (if the Servlet is configured with a
zero or positive integer value in the deployment descriptor).
• When the Servlet is first requested by a client (if lazy loading is enabled).
2. Initializing a Servlet
After the Servlet is instantiated, the Servlet container initializes it by calling the
init(ServletConfig config) method. This method is called only once during the Servlet’s
life cycle.
3. Handling request
Once the Servlet is initialized, it is ready to handle client requests. The Servlet container
performs the following steps for each request:
• Create Request and Response Objects
o The container creates ServletRequest and ServletResponse objects.
o For HTTP requests, it
creates HttpServletRequest and HttpServletResponse objects.
• Invoke the service() Method
o The container calls the service(ServletRequest req, ServletResponse res)
method.
o The service() method determines the type of HTTP request (GET, POST,
PUT, DELETE, etc.) and delegates the request to the appropriate method
(doGet(), doPost(), etc).
4. Destroying a Servlet
When the Servlet container decides to remove the Servlet, it follows these steps which
are listed below
• Allow Active Threads to Complete: The container ensures that all threads
executing the service() method complete their tasks.
• Invoke the destroy() Method: The container calls the destroy() method to allow
the Servlet to release resources (e.g., closing database connections, freeing
memory).
• Release Servlet Instance: After the destroy() method is executed, the Servlet
container releases all references to the Servlet instance, making it eligible for
garbage collection
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet:
• init()
• service()
• destroy()
A simple servlet
1. Servlet Code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
// Handles GET request
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Write response
PrintWriter out = response.getWriter();
out.println("<h1>Hello, World!</h1>");
}
}
2. web.xml Configuration (Deployment Descriptor)
This is required if you're not using annotations (Java EE < Servlet 3.0):
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Servlet API
Servlets are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the webserver, process the
request, produce the response, then send a response back to the webserver. In Java, to
create web applications we use Servlets. To create Java Servlets, we need to use Servlet
API which contains all the necessary interfaces and classes. Servlet API has 2 packages
namely,
• javax.servlet
• javax.servlet.http
javax.servlet
• This package provides the number of interfaces and classes to support Generic
servlet which is protocol independent.
• These interfaces and classes describe and define the contracts between a
servlet class and the runtime environment provided by a servlet container.
Classes available in javax.servlet package:
Class Name Description
To define a generic and protocol-independent
GenericServlet
servlet.
To generate notifications about changes to the
ServletContextAttributeEvent attributes of the servlet context of a web
application.
To generate notifications about changes to the
ServletContextEvent
servlet context of a web application.
This class provides an input stream to read binary
ServletInputStream
data from a client request.
Class Name Description
This class provides an output stream for sending
ServletOutputStream
binary data to the client.
To generate notifications about changes to the
ServletRequestAttributeEvent
attributes of the servlet request in an application.
ServletRequestEvent To indicate lifecycle events for a ServletRequest.
This class provides the implementation of the
ServletRequestWrapper ServletRequest interface that can be subclassed by
developers to adapt the request to a Servlet.
This class provides the implementation of the
ServletResponseWrapper ServletResponse interface that can be subclassed
by developers to adapt the response from a Servlet.
Interfaces available in javax.servlet package:
Interface Name Description
To perform filtering tasks on either the request to
Filter a resource, or on the response from a resource,
or both.
To provide a view into the invocation chain of a
FilterChain filtered request for a resource to the developer by
the servlet container.
To pass information to a filter during initialization
FilterConfig
used by a servlet container.
Interface Name Description
It defines an object to dispatch the request and
response to any other resource, means it
RequestDispatcher
receives requests from the client and sends them
to a servlet/HTML file/JSP file on the server.
This is the main interface that defines the
methods in which all the servlets must
implement. To implement this interface, write a
Servlet
generic servlet that extends
javax.servlet.GenericServlet or an HTTP servlet
that extends javax.servlet.http.HttpServlet.
It defines an object created by a servlet container
ServletConfig at the time of servlet instantiation and to pass
information to the servlet during initialization.
It defines a set of methods that a servlet uses to
communicate with its servlet container. The
ServletContext information related to the web application
available in web.xml file is stored in
ServletContext object created by container.
The classes that implement this interface receive
ServletContextAttributeListener notifications of changes to the attribute list on
the servlet context of a web application.
The classes that implement this interface receive
ServletContextListener notifications about changes to the servlet context
of the web application they are part of.
It defines an object that is created by servlet
ServletRequest container to pass client request information to a
servlet.
Interface Name Description
To generate the notifications of request attribute
changes while the request is within the scope of
ServletRequestAttributeListener
the web application in which the listener is
registered.
To generate the notifications of requests coming
ServletRequestListener
in and out of scope in a web component.
It defines an object created by servlet container
ServletResponse to assist a servlet in sending a response to the
client.
Exceptions in javax.servlet package:
Exception Name Description
A general exception thrown by a servlet when it encounters
ServletException
difficulty.
Thrown by a servlet or filter to indicate that it is permanently
UnavailableException
or temporarily unavailable.
javax.servlet.http
• This package provides the number of interfaces and classes to support HTTP
servlet which is HTTP protocol dependent.
• These interfaces and classes describe and define the contracts between a
servlet class running under HTTP protocol and the runtime environment provided
by a servlet container.
Classes available in javax.servlet.http package:
Class Name Description
Creates a cookie object. It is a small amount of
information sent by a servlet to a Web browser,
Cookie
saved by the browser, and later sent back to the
server used for session management.
Provides an abstract class that defines methods to
HttpServlet create an HTTP suitable servlet for a web
application.
This class provides implementation of the
HttpServletRequestWrapper HttpServletRequest interface that can be
subclassed to adapt the request to a Servlet.
This class provides implementation of the
HttpServletResponseWrapper HttpServletResponse interface that can be
subclassed to adapt the response from a Servlet.
This events are either sent to an object that
implements HttpSessionBindingListener when it is
bound or unbound from a session, or to
HttpSessionBindingEvent a HttpSessionAttributeListener that has been
configured in the deployment descriptor when any
attribute is bound, unbound or replaced in a
session.
To represent event notifications for changes to
HttpSessionEvent
sessions within a web application.
Interfaces available in javax.servlet.http package:
Interface Name Description
To provide client HTTP request information for
HttpServletRequest
servlets. It extends the ServletRequest interface.
To provide HTTP-specific functionality in sending a
HttpServletResponse response to client. It extends
the ServletResponse interface.
It provides a way to identify a user across web
HttpSession application/web site pages and to store
information about that user.
Container to notify all the objects that are bound to
HttpSessionActivationListener a session that sessions will be passivated and that
session will be activated.
To get notifications of changes to the attribute lists
HttpSessionAttributeListener of sessions within this web application, this
listener interface can be implemented.
It causes an object to be notified by an
HttpSessionBindingListener HttpSessionBindingEvent object, when it is bound
to or unbound from a session.
To receive notification events related to the
HttpSessionListener changes to the list of active sessions in a web
application.
Servlet package
The Servlet package provides the essential classes and interfaces needed to create
and manage servlets in Java web applications. It is part of the Java EE (Jakarta EE)
platform.
Main Servlet Packages
Package Name Purpose
javax.servlet.* Contains the generic servlet interfaces and classes.
javax.servlet.http.* Contains HTTP-specific servlet interfaces and classes.
In newer versions (Jakarta EE 9+), these packages are renamed to:
• jakarta.servlet.*
• jakarta.servlet.http.*
Contents of javax.servlet (or jakarta.servlet) Package
Important Interfaces
Interface Description
Servlet Base interface for all servlets.
ServletConfig Provides configuration information for a servlet.
ServletContext Provides information about the web application environment.
RequestDispatcher For forwarding requests or including content.
Filter Used to perform filtering tasks like logging, security, etc.
FilterChain Passes the request/response to the next filter or resource.
Contents of javax.servlet.http (or jakarta.servlet.http) Package
Important Classes and Interfaces
Name Type Description
Base class for handling HTTP requests (extends
HttpServlet Class
GenericServlet).
Name Type Description
HttpServletRequest Interface Represents the HTTP request from the client.
HttpServletResponse Interface Used to send a response to the client.
HttpSession Interface Manages user session between multiple requests.
Cookie Class Used to create and manage cookies.
Example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h3>Hello from the servlet package!</h3>");
}
}
Reading servlet parameters
When a client (usually through an HTML form or URL) sends data to a servlet, the servlet
can read the parameters using the HttpServletRequest object.
1. From HTML Form (GET or POST)
HTML Form Example:
<form action="WelcomeServlet" method="get">
Name: <input type="text" name="username"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
2. Servlet Code to Read Parameters
Java Servlet Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Read parameters
String name = request.getParameter("username");
String age = request.getParameter("age");
// Print output
out.println("<h2>Hello, " + name + "!</h2>");
out.println("<p>Your age is: " + age + "</p>");
}
}
Understanding HTTP Methods in Servlets
HTTP provides various methods such as GET, POST, PUT, DELETE, etc. for client-server
communication. In servlets, the two most commonly used methods are GET and POST.
Here's how they work:
GET Method
• Used to request data from the server.
• Parameters are visible in the URL.
• Suitable for non-sensitive data like search queries.
POST Method
• Used to send data to the server.
• Parameters are hidden in the request body.
• Ideal for sensitive data like login credentials.
• Preferred when modifying server-side data.
Note: By default, HTML forms use the GET method if the method attribute is not
specified.
Implementation Steps
Follow these steps to handle HTTP GET and POST requests in Java Servlets:
Step 1: Setting Up Project
• Create a Dynamic Web Project
o In your IDE, create a new project and select Dynamic Web Project.
• Configure Deployment Descriptor:
o Ensure you have a web.xml file in the WEB-INF folder.
o This file is required for servlet mapping if you are not using annotations.
Step 2: Observing GET Method Behavior
HTML Form for GET Request: Let us create an HTML form that sends two numbers to
the server via the GET method. Save the below code as index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="add" method="get">
Enter num1: <input type ="text" name = "num1"><br>
Enter num2: <input type ="text" name = "num2"><br>
<input type="submit">
</form>
</body>
</html>
Servlet to Handle GET Requests: Create a servlet class "AddServel" and then request
is sent to the servlet mapped to /add. In the servlet, the doGet method processes GET
requests:
package com.LearnServlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddServlet extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException
{
int num1
= Integer.parseInt(req.getParameter("num1"));
int num2
= Integer.parseInt(req.getParameter("num2"));
int result = num1 + num2;
PrintWriter out = res.getWriter();
out.println("The result is = " + result);
}
}
Step 3: Using POST Method for Sensitive Data
To ensure parameters like passwords remain hidden, use the POST method.
Modify the Form for POST: Change the form’s method attribute to POST in index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="add" method="post">
Enter num1: <input type ="text" name = "num1"><br>
Enter num2: <input type ="text" name = "num2"><br>
<input type="submit">
</form>
</body>
</html>
Let us see what happens if we do not update the Servlet to Handle POST Requests:
package com.LearnServlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AddServlet extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws IOException
{
int num1
= Integer.parseInt(req.getParameter("num1"));
int num2
= Integer.parseInt(req.getParameter("num2"));
int result = num1 + num2;
PrintWriter out = res.getWriter();
out.println("The result is = " + result);
}
}
In Java Servlets, HTTP requests and responses are managed using the
HttpServletRequest and HttpServletResponse objects. These are passed to servlet
methods like doGet() and doPost().
1. Handling HTTP Requests
Interface: HttpServletRequest
This interface allows you to:
• Get data from the client (form fields, headers, query parameters, cookies, etc.).
• Access HTTP methods and request metadata.
Common Methods:
Method Description
getParameter(String name) Gets a form or query parameter.
getParameterValues(String Gets all values for a multi-valued parameter (e.g.,
name) checkboxes).
getHeader(String name) Gets a specific request header.
getMethod() Returns the HTTP method (GET, POST, etc.).
getRequestURI() Returns the URI of the request.
Method Description
getCookies() Returns any cookies sent by the client.
2. Handling HTTP Responses
Interface: HttpServletResponse
This interface allows you to:
• Set the response type (HTML, JSON, etc.).
• Send data back to the client.
• Redirect or send errors.
Common Methods:
Method Description
setContentType(String type) Sets the MIME type (e.g., text/html).
getWriter() Returns a PrintWriter to write response content.
sendRedirect(String location) Redirects the client to another URL.
addCookie(Cookie cookie) Adds a cookie to the response.
setStatus(int sc) Sets the HTTP status code (e.g., 200, 404).
Java server pages- introduction to java server pages
JavaServer Pages (JSP) is a server-side technology that creates dynamic web
applications. It allows developers to embed Java code directly into HTML or XML pages,
and it makes web development more efficient.
JSP is an advanced version of Servlets. It provides enhanced capabilities for building
scalable and platform-independent web pages.
How is JSP More Advantageous than Servlets?
JSP simplifies web development by combining the strengths of Java with the flexibility of
HTML. Some advantages of JSP over Servlets are listed below:
• JSP code is easier to manage than Servlets as it separates UI and business logic.
• JSP minimizes the amount of code required for web applications.
• Generate content dynamically in response to user interactions.
• It provides access to the complete range of Java APIs for robust application
development.
• JSP is suitable for applications with growing user bases.
Key Features of JSP
• It is platform-independent; we can write once, run anywhere.
• It simplifies database interactions for dynamic content.
• It contains predefined objects like request, response, session, and application,
reducing development time.
• It has built-in mechanisms for exception and error management.
• It supports custom tags and tag libraries.
JSP Architecture
JSP follows a three-layer architecture:
• Client Layer: The browser sends a request to the server.
• Web Server Layer: The server processes the request using a JSP engine.
• Database/Backend Layer: Interacts with the database and returns the response
to the client.
Differences Between JSP and Servlets
Features JSP Servlet
Code Length Jsp required less code Servlets required more code
Ease of Use Jsp is simple to use Servlet is more complex to use
Dynamic Content Easily embedded in HTML Requires HTML generation in code
Page Maintenance Easier to maintain More challenging
Steps to Create a JSP Application
JSP allows us to embed Java code within HTML pages and making it easy to create
dynamic content. Let us start with a simple exercise to convert an existing HTML file into
a JSP file.
Steps to Create a JSP
1. Take any HTML file you have previously created.
2. Change the file extension from .html to .jsp.
3. Load the new .jsp file in a browser.
When we load a JSP file for the first time:
• JSP is converted into a Java file.
• Java file is compiled into a servlet.
• Compiled servlet is loaded and executed.
Adding Dynamic Content with JSP
Here is an example to demonstrate how JSP can generate dynamic content:
hello.jsp:
<!DOCTYPE html>
<html>
<body>
Hello! The time is now <%= new java.util.Date() %>
</body>
</html>
Explanation:
• The <%= %> tags enclose a Java expression.
• new java.util.Date() expression retrieves the current date and time.
• When the JSP page is loaded in the browser, the Java expression is evaluated at
runtime, and output is embedded into the HTML.
• Each time you reload the page, it displays the current time, demonstrating how
JSP dynamically generates HTML content based on Java logic.
JSP Elements
We will learn several elements available in JSP with suitable examples. In JSP elements
can be divided into 4 different types.
• Expression
• Scriplets
• Directives
• Declarations
1. Expression
This tag is used to output any data on the generated page. These data are automatically
converted to a string and printed on the output stream.
Syntax:
<%= “Anything” %>
Note: JSP Expressions start with Syntax of JSP Scriptles are with <%=and ends with
%>. Between these, you can put anything that will convert to the String and that will be
displayed.
Example:
<%=”HelloWorld!” %>
2. Scriplets
This allows inserting any amount of valid Java code. These codes are placed in the
_jspService() method by the JSP engine.
Syntax:
<%
// Java codes
%>
Note: JSP Scriptlets begins with <% and ends %> . We can embed any amount of Java
code in the JSP Scriptlets. JSP Engine places these codes in the _jspService() method.
Example:
<%
String name = “Geek”;
out.println(“Hello, ” + name);
%>
Variables available to the JSP Scriptlets are:
• Request
• Response
• Session
• Out
3. Directives
A JSP directive starts with <%@ characters. In the directives, we can import packages,
define error-handling pages, or configure session information for the JSP page.
Syntax:
<%@ directive attribute=”value” %>
Types of Directives:
• page: It defines page settings.
• include: It includes other files.
• taglib: It declares a custom tag library.
4. Declarations
This is used for defining functions and variables to be used in the JSP.
Syntax:
<%!
//java codes
%>
A simple JSP example
1. HTML Form (index.html)
<!DOCTYPE html>
<html>
<head>
<title>JSP Input Form</title>
</head>
<body>
<h2>Enter Your Name</h2>
<form action="greeting.jsp" method="get">
Name: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
</body>
</html>
2. JSP Page (greeting.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Greeting Page</title>
</head>
<body>
<h2>Welcome Page</h2>
<%
String name = request.getParameter("username");
if (name == null || name.trim().equals("")) {
out.println("<p>Please enter your name.</p>");
} else {
out.println("<p>Hello, <b>" + name + "</b>! Welcome to JSP.</p>");
}
%>
</body>
</html>
Scripting
Scripting in JSP (JavaServer Pages)
Scripting in JSP refers to embedding Java code directly into HTML pages using special
tags. This allows the server to dynamically generate web content based on logic, user
input, database interaction, etc.
3 Main Scripting Elements in JSP
Element Syntax Purpose
Embeds Java code (e.g., loops, conditions) inside
Scriptlet <% Java code %>
HTML.
<%= Java expression Outputs the result of a Java expression directly into
Expression
%> the page.
<%! Java declaration Declares methods or variables (used across
Declaration
%> multiple requests).
1. Scriptlet Tag – <% ... %>
Executes Java statements when the page is requested.
jsp
CopyEdit
<%
String name = "John";
int age = 20;
out.println("Name: " + name + "<br>");
out.println("Age: " + age);
%>
2. Expression Tag – <%= ... %>
Evaluates and prints the result of a Java expression.
jsp
CopyEdit
<h2>Welcome, <%= "User".toUpperCase() %></h2>
This is equivalent to:
jsp
CopyEdit
<%
out.print("User".toUpperCase());
%>
3. Declaration Tag – <%! ... %>
Declares methods or class-level variables that persist between requests.
jsp
CopyEdit
<%!
int counter = 0;
public String greet(String name) {
return "Hello, " + name + "!";
}
%>
<p><%= greet("Alice") %></p>
Example Combining All Three
jsp
CopyEdit
<%@ page contentType="text/html" language="java" %>
<html>
<head><title>Scripting Example</title></head>
<body>
<%! int counter = 1; %>
<%
String user = "Student";
counter++;
%>
<p>Welcome <%= user %>!</p>
<p>You are visitor number: <%= counter %></p>
</body>
</html>
Unit-2
Basic GUI components in AWT (Abstract Window Toolkit)
What is AWT?
AWT (Abstract Window Toolkit) is Java’s original platform-dependent GUI toolkit, part
of the java.awt package. It provides classes for creating windows, buttons, text fields,
and other user interface elements.
Basic AWT GUI Components with Detailed Description
1. Frame
• A top-level window with a title bar, borders, and buttons like minimize, maximize,
and close.
• Can contain other AWT components.
Frame f = new Frame("My AWT Frame");
2. Label
• A non-editable text display component used to identify another component (like
a text field).
Label label = new Label("Enter your name:");
• Key Methods:
o setText(String text) – changes the label text.
o getText() – retrieves the current label text.
3. Button
• A push-button that performs an action when clicked.
Button b = new Button("Click Me");
• Event Listener: ActionListener
4. TextField
• Allows single-line user input.
TextField tf = new TextField(20); // 20-character wide
• Key Methods:
o setText(String) – sets the content.
o getText() – retrieves the content.
o setEchoChar(char) – useful for password fields.
5. TextArea
• A multi-line text input component.
TextArea ta = new TextArea("Write here...", 5, 30);
• Key Methods:
o append(String) – adds text to the end.
o getText() – retrieves the content.
6. Checkbox
• A box that can be checked (true) or unchecked (false).
Checkbox cb = new Checkbox("Accept Terms");
• Key Methods:
o getState() – returns boolean (checked or not).
o setState(boolean) – sets the checkbox state.
7. CheckboxGroup (used with Radio Buttons)
• Allows only one checkbox to be selected in a group (radio button behavior).
CheckboxGroup group = new CheckboxGroup();
Checkbox male = new Checkbox("Male", group, false);
Checkbox female = new Checkbox("Female", group, false);
8. Choice
• Drop-down menu for selecting one item from a list.
Choice c = new Choice();
c.add("Red");
c.add("Green");
c.add("Blue");
• Key Methods:
o getSelectedItem() – returns selected item.
o select(int index) – selects item by index.
9. List
• Displays a list of items that can be single or multiple selectable.
List l = new List(4, true); // 4 visible items, multiple selection
l.add("Java");
l.add("Python");
l.add("C++");
• Key Methods:
o getSelectedItems() – returns selected items as an array.
10. Canvas
• A blank rectangular area for drawing graphics or custom rendering.
Canvas canvas = new Canvas();
canvas.setSize(200, 200);
• Override paint(Graphics g) for custom drawing.
11. Scrollbar
• Used to navigate a large area vertically or horizontally.
Scrollbar s = new Scrollbar();
• Types: Scrollbar.HORIZONTAL, Scrollbar.VERTICAL
12. Panel
• A generic container used to group components.
Panel p = new Panel();
p.add(new Button("Inside Panel"));
• Often used inside frames or applets.
13. Dialog
• A pop-up window for user interaction (modal or modeless).
Dialog d = new Dialog(f, "This is a dialog", true);
Example: Basic AWT GUI
import java.awt.*;
import java.awt.event.*;
public class AWTExample {
public static void main(String[] args) {
Frame f = new Frame("AWT Example");
Label label = new Label("Name:");
label.setBounds(50, 50, 60, 20);
TextField tf = new TextField();
tf.setBounds(120, 50, 150, 20);
Button b = new Button("Submit");
b.setBounds(120, 100, 80, 30);
b.addActionListener(e -> System.out.println("Hello, " + tf.getText()));
f.add(label);
f.add(tf);
f.add(b);
f.setSize(400, 200);
f.setLayout(null); // Absolute positioning
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
}
}
Container classes
In Java AWT and Swing, container classes are special components that can hold and
organize other components like buttons, labels, text fields, etc. These are essential for
building structured GUI layouts.
What is a Container?
A container is a component that can contain other components (including other
containers). All container classes inherit from the java.awt.Container class.
Common Container Classes in Java AWT
1. Container (Abstract Base Class)
• Superclass for all container classes.
• Provides methods like:
o add(Component comp)
o remove(Component comp)
o setLayout(LayoutManager mgr)
2. Panel
• A generic, lightweight container used to group components together.
• Often used to subdivide a GUI window.
• Does not have a title bar, menu, or border.
Panel p = new Panel();
p.add(new Button("Button in Panel"));
Use Case: Group related controls like buttons and labels.
3. Frame
• A top-level container representing a window with a title bar, close button, etc.
• Can contain other components and containers.
Frame f = new Frame("My Frame");
f.setSize(300, 200);
f.setVisible(true);
Use Case: Main application window.
4. Window
• A bare top-level window with no borders or title bar.
• Cannot be displayed without being owned by another window (usually a Frame).
Window w = new Window(f); // f is a Frame
Not commonly used directly.
5. Dialog
• A pop-up window used for short-term interaction with the user.
• Can be modal (blocks interaction with other windows) or modeless.
Dialog d = new Dialog(f, "Dialog Box", true); // modal dialog
d.setSize(200, 100);
d.setVisible(true);
Use Case: Prompt for confirmation, input, etc.
6. Applet (AWT)
• A special container used to embed Java GUI in web browsers (legacy).
• Extends Panel.
public class MyApplet extends Applet {
public void init() {
add(new Button("Click Me"));
}
}
Layout Manager
In Java AWT, Layout Managers are responsible for arranging GUI components inside
containers such as Frame, Panel, or Dialog.
They help create flexible and platform-independent UIs by automatically managing the
size and position of components.
What is a Layout Manager?
A Layout Manager is an object that implements the LayoutManager interface (or
LayoutManager2 for advanced versions). Each container can have one layout manager
at a time.
Common Layout Managers in AWT
Below are the most commonly used layout managers in AWT:
1. FlowLayout
• Default layout manager for Panel
• Arranges components in a left-to-right flow, much like words on a page.
• When space runs out, it moves to the next line.
Panel p = new Panel();
p.setLayout(new FlowLayout());
p.add(new Button("One"));
p.add(new Button("Two"));
p.add(new Button("Three"));
Constructor Options:
new FlowLayout(); // center alignment
new FlowLayout(FlowLayout.LEFT); // left-aligned
new FlowLayout(FlowLayout.RIGHT); // right-aligned
2. BorderLayout
• Default layout manager for Frame
• Divides the container into five regions:
o NORTH, SOUTH, EAST, WEST, CENTER
Frame f = new Frame();
f.setLayout(new BorderLayout());
f.add(new Button("North"), BorderLayout.NORTH);
f.add(new Button("South"), BorderLayout.SOUTH);
f.add(new Button("East"), BorderLayout.EAST);
f.add(new Button("West"), BorderLayout.WEST);
f.add(new Button("Center"), BorderLayout.CENTER);
If you don’t specify a region, the component will default to CENTER.
3. CardLayout
• Allows you to stack components like cards, showing only one at a time.
• Good for wizards, tab pages, or step-by-step UIs.
Panel cards = new Panel();
CardLayout cl = new CardLayout();
cards.setLayout(cl);
cards.add("First", new Button("Card 1"));
cards.add("Second", new Button("Card 2"));
cl.show(cards, "Second"); // show second card
Use next(), previous(), first(), last() to navigate cards.
4. BoxLayout
• Aligns components horizontally (X_AXIS) or vertically (Y_AXIS) in a line.
• Not part of AWT directly — it’s from Swing (javax.swing.BoxLayout), but you can
use it with Panel.
Panel p = new Panel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.add(new Button("Button 1"));
p.add(new Button("Button 2"));
Difference between AWT and SWING
S.NO AWT Swing
Swing is a part of Java Foundation
Java AWT is an API to develop GUI
1. Classes and is used to create various
applications in Java
applications.
S.NO AWT Swing
The components of Java AWT are The components of Java Swing are light
2.
heavy weighted. weighted.
Java AWT has comparatively less
Java Swing has more functionality as
3. functionality as compared to
compared to AWT.
Swing.
The execution time of AWT is more The execution time of Swing is less than
4.
than Swing. AWT.
The components of Java AWT are The components of Java Swing are
5.
platform dependent. platform independent.
MVC pattern is not supported by
6. MVC pattern is supported by Swing.
AWT.
AWT provides comparatively less Swing provides more powerful
7.
powerful components. components.
AWT components require java.awt Swing components requires javax.swing
8
package package
AWT is a thin layer of code on top Swing is much larger swing also has very
9
of the operating system. much richer functionality.
Swing is also called as JFC(java
AWT stands for Abstract windows
10 Foundation classes). It is part of oracle’s
toolkit .
JFC.
Using AWT , you have to
11 Swing has them built in.
implement a lot of things yourself .
Java foundation classes-javax
Java Foundation Classes (JFC) refers to a set of features for building graphical user
interfaces (GUIs) and adding rich graphics functionality and interactivity to Java
applications. The javax package and its subpackages are integral parts of the JFC,
particularly Swing, which provides a comprehensive set of GUI components.
The JFC encompasses:
• Swing:
A GUI toolkit that provides platform-independent, lightweight components. It includes
elements like buttons (JButton), labels (JLabel), text fields (JTextField), tables (JTable),
and trees (JTree), all residing within the javax.swing package.
• Java 2D:
An API for advanced 2D graphics and imaging, handling line art, text, and images.
• Accessibility:
The Java Accessibility API enables the creation of applications that can interact with
assistive technologies.
• Drag and Drop:
Functionality for data transfer between Java and native applications, and within Java
applications.
Key packages within javax related to JFC include:
• javax.swing: Contains classes for all Swing components.
• javax.swing.event: Interfaces and classes for handling events fired by Swing
components.
• javax.swing.border: Classes for creating borders around Swing components.
• javax.swing.table: Classes and interfaces for working with tables.
• javax.swing.tree: Classes and interfaces for working with trees.
• javax.swing.text: Classes and interfaces for working with text components.
Swing is built on top of the Abstract Window Toolkit (AWT) but offers more advanced and
flexible components. It allows for the creation of visually appealing and interactive
applications that can run on various platforms without modification.
What is the MVC Design Pattern?
The Model View Controller (MVC) design pattern specifies that an application consists
of a data model, presentation information, and control information. The pattern requires
that each of these be separated into different objects.
• The MVC pattern separates the concerns of an application into three distinct
components, each responsible for a specific aspect of the application’s
functionality.
• This separation of concerns makes the application easier to maintain and
extend, as changes to one component do not require changes to the other
components.
Why use MVC Design Pattern?
The MVC (Model-View-Controller) design pattern breaks an application into three parts:
the Model (which handles data), the View (which is what users see), and the Controller
(which connects the two). This makes it easier to work on each part separately, so you
can update or fix things without messing up the whole app. It helps developers add new
features smoothly, makes testing simpler, and allows for better user interfaces. Overall,
MVC helps keep everything organized and improves the quality of the software.
Components of the MVC Design Pattern
1. Model
The Model component in the MVC (Model-View-Controller) design pattern
demonstrates the data and business logic of an application. It is responsible for
managing the application’s data, processing business rules, and responding to requests
for information from other components, such as the View and the Controller.
2. View
Displays the data from the Model to the user and sends user inputs to the Controller. It
is passive and does not directly interact with the Model. Instead, it receives data from
the Model and sends user inputs to the Controller for processing.
3. Controller
Controller acts as an intermediary between the Model and the View. It handles user
input and updates the Model accordingly and updates the View to reflect changes in the
Model. It contains application logic, such as input validation and data transformation.
Creating a Frame in Swing
In Java Swing, the JFrame class is used to create a main window (top-level frame) in a
GUI application. It serves as the container for other components like buttons, text
fields, labels, etc.
Step-by-Step: Creating a Basic Swing Frame
1. Import Swing Package
import javax.swing.*;
2. Create a JFrame Object
JFrame frame = new JFrame("My Swing Frame");
3. Set Frame Properties
frame.setSize(400, 300); // Set width and height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when closed
frame.setLayout(null); // Optional: set layout
frame.setVisible(true); // Make it visible
Full Example: Simple Swing Frame
import javax.swing.*;
public class SwingFrameExample {
public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("My First Swing Frame");
// Set size (width, height)
frame.setSize(400, 300);
// Exit the application when the frame is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Optional: Center the frame on screen
frame.setLocationRelativeTo(null);
// Make frame visible
frame.setVisible(true);
}
}
Explanation of Key Methods
Method Purpose
new JFrame(String title) Creates a frame with a title
setSize(int width, int height) Sets the dimensions of the window
setVisible(boolean flag) Shows or hides the window
setDefaultCloseOperation(int op) Defines what happens when the window is closed
setLocation(int x, int y) Sets the frame location on the screen
setLocationRelativeTo(null) Centers the frame on the screen
setLayout(LayoutManager Sets the layout manager (or null for absolute
manager) positioning)
Displaying an Image in Java Swing
In Swing, the most common way to display an image is by using a JLabel with an
ImageIcon.
Step-by-Step: Displaying an Image
1. Prepare the Image
• Make sure your image file (e.g., logo.jpg) is in the project directory or provide a
full path.
2. Use ImageIcon with JLabel
ImageIcon icon = new ImageIcon("logo.jpg"); // Load image
JLabel label = new JLabel(icon); // Display in label
Example
import javax.swing.*;
public class ImageDisplay {
public static void main(String[] args) {
JFrame frame = new JFrame("Image Example");
// Load and display image
ImageIcon icon = new ImageIcon("image.jpg"); // path to image
JLabel label = new JLabel(icon);
frame.add(label);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
JComponent Class Methods in Java Swing
The JComponent class is the base class for all Swing components, such as JButton,
JLabel, JPanel, etc. It provides core functionality like size, color, layout, rendering,
event handling, and borders.
Commonly Used JComponent Methods
Method Description
1. Visual Appearance
Method Description
setForeground(Color c) Sets the text color or foreground color
setBackground(Color c) Sets the background color
setFont(Font f) Sets the font of the component
setOpaque(boolean b) If true, fills the background with setBackground color
setBorder(Border b) Sets the border around the component
button.setForeground(Color.WHITE);
button.setBackground(Color.BLUE);
button.setFont(new Font("Arial", Font.BOLD, 16));
button.setBorder(BorderFactory.createLineBorder(Color.BLACK));
2. Size and Position
Method Description
setSize(int width, int height) Sets the component’s size
setPreferredSize(Dimension d) Suggests a preferred size for layout managers
setBounds(int x, int y, int width, int Sets position and size (used when layout is
height) null)
getWidth(), getHeight() Get current width and height
getX(), getY() Get current location
button.setBounds(50, 100, 120, 30);
panel.setPreferredSize(new Dimension(300, 200));
3. Events and Tooltips
Method Description
addMouseListener(MouseListener
Adds mouse event handling
l)
addKeyListener(KeyListener l) Adds keyboard event handling
Shows a tooltip when hovering over the
setToolTipText(String text)
component
button.setToolTipText("Click to submit");
Creating Components in Swing (Java)
In Swing, components are GUI elements like buttons, labels, text fields, checkboxes,
etc. These components are objects of classes that extend JComponent, such as
JButton, JLabel, JTextField, and more.
1. Basic Steps to Create a Component
1. Create a component
2. Set its properties (text, size, color, etc.)
3. Add it to a container (like JFrame or JPanel)
Common Swing Components
Component Class Description
Label JLabel Displays a line of text or an image
Button JButton Triggers actions when clicked
Text Field JTextField Single-line text input
Text Area JTextArea Multi-line text input
Password Field JPasswordField Text field with hidden characters
Checkbox JCheckBox Box with checkable state
Radio Button JRadioButton Selectable button in a group
Combo Box JComboBox Drop-down list of choices
List JList Scrollable list of items
Panel JPanel Container for grouping components
Example: Creating Components
import javax.swing.*;
import java.awt.*;
public class ComponentDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Component Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout()); // Simple layout
// Create components
JLabel label = new JLabel("Enter Name:");
JTextField textField = new JTextField(15);
JButton button = new JButton("Submit");
JCheckBox checkBox = new JCheckBox("Accept Terms");
JRadioButton radio1 = new JRadioButton("Male");
JRadioButton radio2 = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(radio1);
genderGroup.add(radio2);
JComboBox<String> comboBox = new JComboBox<>(new String[] {"Java", "Python",
"C++"});
// Add components to frame
frame.add(label);
frame.add(textField);
frame.add(button);
frame.add(checkBox);
frame.add(radio1);
frame.add(radio2);
frame.add(comboBox);
// Show frame
frame.setVisible(true);
}
}
More Component Features
➤ JButton
JButton button = new JButton("Click Me");
button.setToolTipText("Click to perform action");
➤ JTextField
JTextField tf = new JTextField("Default Text", 20);
➤ JTextArea
JTextArea ta = new JTextArea(5, 20); // 5 rows, 20 columns
ta.setLineWrap(true);
➤ JComboBox
String[] items = {"Item 1", "Item 2", "Item 3"};
JComboBox<String> comboBox = new JComboBox<>(items);
Event Handling in Java (AWT & Swing)
Event handling in Java GUI programming is the mechanism that allows your application
to respond to user actions, like clicking a button, typing on the keyboard, or moving the
mouse. Java uses the Event Delegation Model for handling events.
Event Delegation Model (Core Concepts)
1. Event Source: The GUI component (e.g., JButton, JTextField) that generates the
event.
2. Event Object: An instance of an Event class (e.g., ActionEvent, KeyEvent) that
contains information about the event.
3. Event Listener: An interface (e.g., ActionListener, MouseListener) that must be
implemented to handle events.
General Flow of Event Handling
component.addXXXListener(new XXXListener() {
public void methodName(EventObject e) {
// Respond to the event here
}
});
• addXXXListener() — registers a listener to the component.
• methodName() — handles the event.
Common Event Listeners and Their Events
Listener Interface Event Class Used With
ActionListener ActionEvent JButton, JMenuItem, etc.
KeyListener KeyEvent JTextField, JTextArea
MouseListener MouseEvent All components
MouseMotionListener MouseEvent Tracks mouse drag/move
WindowListener WindowEvent JFrame, JDialog
ItemListener ItemEvent JCheckBox, JComboBox
FocusListener FocusEvent All focusable components
Handling Keyboard and Mouse Events in Java (AWT/Swing)
In Java GUI programming, you can handle keyboard and mouse events using specific
listener interfaces. These interfaces are part of the java.awt.event package and are
used in both AWT and Swing applications.
Keyboard Events
Handled using the KeyListener interface.
➤ KeyListener Methods:
Method Description
keyPressed(KeyEvent e) Called when a key is pressed down
Method Description
keyReleased(KeyEvent e) Called when a key is released
keyTyped(KeyEvent e) Called when a character key is typed
Example: Keyboard Input with JTextField
import javax.swing.*;
import java.awt.event.*;
public class KeyboardExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Keyboard Event Example");
JTextField tf = new JTextField();
JLabel label = new JLabel("Press any key");
tf.setBounds(50, 50, 200, 30);
label.setBounds(50, 100, 200, 30);
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
label.setText("Pressed: " + KeyEvent.getKeyText(e.getKeyCode()));
}
public void keyTyped(KeyEvent e) {
System.out.println("Typed: " + e.getKeyChar());
}
});
frame.add(tf);
frame.add(label);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Mouse Events
Handled using:
• MouseListener: for click, press, release, enter, exit.
• MouseMotionListener: for move and drag.
➤ MouseListener Methods:
Method Description
mouseClicked(MouseEvent e) Called when mouse is clicked
mousePressed(MouseEvent e) Called when mouse is pressed
mouseReleased(MouseEvent e) Called when mouse is released
mouseEntered(MouseEvent e) Mouse entered component area
mouseExited(MouseEvent e) Mouse exited component area
➤ MouseMotionListener Methods:
Method Description
mouseMoved(MouseEvent e) Mouse moved over component
mouseDragged(MouseEvent e) Mouse dragged
Example: Mouse Click and Move
import javax.swing.*;
import java.awt.event.*;
public class MouseExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Mouse Event Example");
JLabel label = new JLabel("Move or Click");
label.setBounds(50, 50, 200, 30);
frame.add(label);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Mouse Click
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
label.setText("Clicked at (" + e.getX() + ", " + e.getY() + ")");
}
});
// Mouse Move
frame.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
label.setText("Mouse at (" + e.getX() + ", " + e.getY() + ")");
}
});
}
}
Unit-4
JDBC (Java Database Connectivity)
JDBC is an API that helps applications to communicate with databases, it allows Java
programs to connect to a database, run queries, retrieve, and manipulate data. Because
of JDBC, Java applications can easily work with different relational databases like
MySQL, Oracle, PostgreSQL, and more.
JDBC Architecture
Explanation:
• Application: It can be a Java application or servlet that communicates with a
data source.
• The JDBC API: It allows Java programs to execute SQL queries and get results
from the database. Some key components of JDBC API include
o Interfaces like Driver, ResultSet, RowSet, PreparedStatement, and
Connection that helps managing different database tasks.
o Classes like DriverManager, Types, Blob, and Clob that helps managing
database connections.
• DriverManager: It plays an important role in the JDBC architecture. It uses some
database-specific drivers to effectively connect enterprise applications to
databases.
• JDBC drivers: These drivers handle interactions between the application and the
database.
The JDBC architecture consists of two-tier and three-tier processing models to access a
database. They are as described below:
1. Two-Tier Architecture
A Java Application communicates directly with the database using a JDBC driver. It
sends queries to the database and then the result is sent back to the application. For
example, in a client/server setup, the user’s system acts as a client that communicates
with a remote database server.
Structure:
Client Application (Java) -> JDBC Driver -> Database
2. Three-Tier Architecture
In this, user queries are sent to a middle-tier services, which interacts with the
database. The database results are processed by the middle tier and then sent back to
the user.
Structure:
Client Application -> Application Server -> JDBC Driver -> Database
JDBC-ODBC Relationship in Java
JDBC (Java Database Connectivity) and ODBC (Open Database Connectivity) are
technologies used to connect Java applications to databases. They serve as bridges
between applications and data sources, but they function at different levels.
What is JDBC?
• JDBC is an API in Java that allows Java applications to interact with databases
(like MySQL, Oracle, SQL Server, etc.).
• It is part of java.sql and provides methods for querying and updating data in a
database.
What is ODBC?
• ODBC is a platform-independent standard developed by Microsoft that allows
applications to access different databases using a common set of functions.
• It requires ODBC drivers specific to each database.
JDBC-ODBC Bridge
Java used to provide a JDBC-ODBC Bridge Driver (known as Type 1 driver) that enabled
JDBC programs to access ODBC-compliant databases.
How it works:
pgsql
CopyEdit
Java App (JDBC API)
↓
JDBC-ODBC Bridge Driver (Type 1)
↓
ODBC Driver Manager
↓
ODBC Driver for specific database
↓
Database (e.g., MS Access, SQL Server)
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine rather than the
server) that translate requests from Java programs into a protocol understood by the
DBMS. These drivers are software components that implement the interfaces in the
JDBC API, allowing Java applications to interact with a database. Sun Microsystems
(now Oracle) defines four types of JDBC drivers, which are outlined below:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
1. JDBC-ODBC Bridge Driver – Type 1 Driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. Type-1 driver is also called Universal driver because it can be used to connect to
any of the databases.
Advantages
• This driver software is built-in with JDK so no need to install separately.
• It is a database independent driver.
Disadvantages
• As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
• The ODBC bridge driver is needed to be installed in individual client machines.
• Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
2. Native-API Driver – Type 2 Driver ( Partially Java Driver)
The Native API driver uses the client -side libraries of the database. This driver converts
JDBC method calls into native calls of the database API. In order to interact with
different database, this driver needs their local API, that’s why data transfer is much
more secure as compared to type-1 driver. This driver is not fully written in Java that is
why it is also called Partially Java driver.
Advantage
• Native-API driver gives better performance than JDBC-ODBC bridge driver.
• More secure compared to the type-1 driver.
Disadvantages
• Driver needs to be installed separately in individual client machines
• The Vendor client library needs to be installed on client machine.
• Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
• It is a database dependent driver.
3. Network Protocol Driver – Type 3 Driver (Fully Java Driver)
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. Here all the
database connectivity drivers are present in a single server, hence no need of individual
client-side installation.
Advantages
• Type-3 drivers are fully written in Java, hence they are portable drivers.
• No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
• Switch facility to switch over from one database to another database.
Disadvantages
• Network support is required on client machine.
• Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
4. Thin Driver – Type 4 Driver (Fully Java Driver)
Type-4 driver is also called native protocol driver. This driver interact directly with
database. It does not require any native database library, that is why it is also known as
Thin Driver.
Advantages
• Does not require any native library and Middleware server, so no client-side or
server-side installation.
• It is fully written in Java language, hence they are portable drivers.
Disadvantage
• If the database changes, a new driver may be needed.
Which Driver to use When?
• If you are accessing one type of database, such as Oracle, Sybase, or IBM, the
preferred driver type is type-4.
• If your Java application is accessing multiple types of databases at the same
time, type 3 is the preferred driver.
• Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not
available yet for your database.
• The type 1 driver is not considered a deployment-level driver, and is typically
used for development and testing purposes only.
JDBC Components
There are generally 4 main components of JDBC through which it can interact with a
database. They are as mentioned below:
1. JDBC API
It provides various methods and interfaces for easy communication with the database.
It includes two key packages
• java.sql: This package, is the part of Java Standard Edition (Java SE)
, which contains the core interfaces and classes for accessing and processing
data in relational databases. It also provides essential functionalities like
establishing connections, executing queries, and handling result sets
• javax.sql: This package is the part of Java Enterprise Edition (Java EE)
, which extends the capabilities of java.sql by offering additional features like
connection pooling, statement pooling, and data source management.
It also provides a standard to connect a database to a client application.
2. JDBC Driver Manager
Driver manager is responsible for loading the correct database-specific driver to
establish a connection with the database. It manages the available drivers and ensures
the right one is used to process user requests and interact with the database.
3. JDBC Test Suite
It is used to test the operation(such as insertion, deletion, updating) being performed by
JDBC Drivers.
4. JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server)
that convert requests from Java programs to a protocol that the DBMS can understand.
There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver (partially java driver)
3. Type-3 driver or Network Protocol driver (fully java driver)
4. Type-4 driver or Thin driver (fully java driver) – It is a widely used driver. The older
drivers like (JDBC-ODBC) bridge driver have been deprecated and no longer
supported in modern versions of Java.
JDBC Classes and Interfaces
Class/Interfaces Description
Manages JDBC drivers and establishes
DriverManager
database connections.
Class/Interfaces Description
Represents a session with a specific
Connection
database.
Statement Used to execute static SQL queries.
Precompiled SQL statement, used for
PreparedStatement
dynamic queries with parameters.
Used to execute stored procedures in the
CallableStatement
database.
Represents the result set of a query,
ResultSet
allowing navigation through the rows.
Handles SQL-related exceptions during
SQLException
database operations.
Steps for Querying the Database with JDBC
To query a database using JDBC (Java Database Connectivity), follow this standard
sequence of steps:
Step-by-Step Process:
1. Load the JDBC Driver
• The driver must be available in your project classpath.
• Modern drivers auto-register, but you can explicitly load it for compatibility.
Class.forName("com.mysql.cj.jdbc.Driver"); // For MySQL
2. Establish a Connection
• Use DriverManager.getConnection() with the correct JDBC URL, username, and
password.
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
3. Create a Statement or PreparedStatement
• Use Statement for simple queries, and PreparedStatement for parameterized
(safe) queries.
Statement stmt = con.createStatement();
// OR
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id = ?");
ps.setInt(1, 101);
4. Execute the Query
• Use executeQuery() for SELECT statements (returns a ResultSet).
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// OR
ResultSet rs = ps.executeQuery();
5. Process the ResultSet
• Loop through the result set using rs.next() and retrieve column data.
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " - " + name);
}
6. Close the Resources
• Always close ResultSet, Statement, and Connection to free resources.
rs.close();
stmt.close(); // or ps.close();
con.close();
Full Example
import java.sql.*;
public class JDBCQueryExample {
public static void main(String[] args) {
try {
// Step 1: Load driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Create connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
// Step 3: Create statement
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id
= ?");
ps.setInt(1, 101);
// Step 4: Execute query
ResultSet rs = ps.executeQuery();
// Step 5: Process result
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id"));
System.out.println("Name: " + rs.getString("name"));
}
// Step 6: Close resources
rs.close();
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Steps to Create an ODBC Data Source (Windows)
Step 1: Open ODBC Data Source Administrator
You can open it using either:
• Search method:
o Press Windows Key, type ODBC → Select:
▪ “ODBC Data Sources (32-bit)” or
▪ “ODBC Data Sources (64-bit)”
• Choose the version based on your application:
o Java 32-bit → use 32-bit ODBC
o Java 64-bit → use 64-bit ODBC
Step 2: Choose DSN Type
You’ll see three tabs:
• User DSN – Available only to the current user.
• System DSN – Available to all users on the system (recommended).
• File DSN – Stores DSN info in a .dsn file.
Choose System DSN for shared access and click Add.
Step 3: Select a Driver
From the list of installed ODBC drivers, select a driver that matches your database,
such as:
• Microsoft Access Driver (*.mdb, *.accdb)
• SQL Server
• MySQL ODBC 8.0 Driver (if installed)
• PostgreSQL Unicode(x64) (if installed)
Click Finish after selecting the appropriate driver.
Step 4: Configure the Data Source
Depending on the driver, you'll be prompted to enter:
• Data Source Name (DSN): e.g., MyAccessDB
• Description (optional)
• Database file or server name
• Authentication credentials
Click Test Connection if available to verify setup.
Step 5: Save and Use the DSN
Once created:
• You can reference this DSN in your Java code like this:
// Only works with Java 7 and earlier
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyAccessDB");
Querying and Updating Database Tables in Java Using JDBC
Java provides JDBC (Java Database Connectivity) API to perform both querying
(retrieving data) and updating (modifying data) in relational databases.
Prerequisites
Make sure:
• You have the JDBC driver for your database (e.g., MySQL, PostgreSQL).
• Your database is up and running.
• You’ve created a table (e.g., users) in your DB.
Example Table: users
id (INT) name (VARCHAR) email (VARCHAR)
1 Alice alice@mail.com
2 Bob bob@mail.com
1. Querying a Table (SELECT)
Code Example:
import java.sql.*;
public class QueryExample {
public static void main(String[] args) {
try {
// Load Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create Connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
// Create Statement
Statement stmt = con.createStatement();
// Execute Query
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// Process ResultSet
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id"));
System.out.println("Name: " + rs.getString("name"));
System.out.println("Email: " + rs.getString("email"));
}
// Close
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. Updating a Table (INSERT, UPDATE, DELETE)
Example: Insert a New Record
PreparedStatement ps = con.prepareStatement(
"INSERT INTO users (name, email) VALUES (?, ?)");
ps.setString(1, "Charlie");
ps.setString(2, "charlie@mail.com");
int result = ps.executeUpdate();
System.out.println(result + " row(s) inserted.");
Example: Update a Record
PreparedStatement ps = con.prepareStatement(
"UPDATE users SET email = ? WHERE name = ?");
ps.setString(1, "newemail@mail.com");
ps.setString(2, "Alice");
int result = ps.executeUpdate();
System.out.println(result + " row(s) updated.");
Example: Delete a Record
PreparedStatement ps = con.prepareStatement(
"DELETE FROM users WHERE name = ?");
ps.setString(1, "Bob");
int result = ps.executeUpdate();
System.out.println(result + " row(s) deleted.");
Passing Parameters to a SQL Statement in JDBC
In JDBC, parameters are passed to SQL statements using the PreparedStatement
interface. This allows you to safely and efficiently insert user inputs or variables into
SQL queries.
Why Use PreparedStatement Instead of Statement?
• Prevents SQL Injection attacks.
• Improves performance (statements are precompiled).
• Makes code cleaner and more maintainable.
Syntax for Using Parameters
1. Use ? as a placeholder for each parameter in your SQL query.
2. Use methods like .setString(), .setInt(), .setDouble() to assign values to each ?.
Example: Inserting Data with Parameters
import java.sql.*;
public class InsertWithParameters {
public static void main(String[] args) {
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to the database
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
// Create the SQL query with placeholders
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
// Create PreparedStatement
PreparedStatement ps = con.prepareStatement(sql);
// Pass parameters to the SQL query
ps.setString(1, "John");
ps.setString(2, "john@example.com");
// Execute the query
int rowsInserted = ps.executeUpdate();
System.out.println(rowsInserted + " row(s) inserted.");
// Close resources
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Common set Methods in PreparedStatement
Method Description
setString(int, String) Sets a String value
setInt(int, int) Sets an Integer value
setDouble(int, double) Sets a Double value
setDate(int, java.sql.Date) Sets a SQL date
setBoolean(int, boolean) Sets a Boolean value
setFloat(int, float) Sets a Float value
The first parameter of each method is the position of the ? in the SQL string (starting
from 1).
Example: Update Query with Parameters
String sql = "UPDATE users SET email = ? WHERE id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "newemail@example.com");
ps.setInt(2, 101);
ps.executeUpdate();