UNIT 1
What is java
Java is a high-level, object-oriented programming language developed by Sun
Microsystems (now owned by Oracle) in 1995. It is designed to be platform-independent,
secure, and robust.
Java applications are compiled into bytecode that can run on any system using the Java
Virtual Machine (JVM)
Features of java
1. Platform independent
2. OOPs based
3. Secure because provide runtime security through bytecode verification and no
pointer
4. Multithreaded
5. High performance – because of JIT compiler improves performance
# JIT compiles bytecode into machine specific code by optimizing the recurrent sections
Primitive Data Types in Java
Non primitive
1. String
2. Array
3. Classes
# In Java, strings are objects of the String class located in the [Link] package.
Example :
String name = "John"; // Static string literal
String num = "1234"
# String object is immutable.
String str = new String("Hello World"); // Heap memory
How to take input in java
Scanner sc = new Scanner([Link]);
String name = [Link]();
# Use next() for single-word input
Declaration of array in Java
1. int[] marks = new int[5];
marks[0] = 90;
2. int[] age = {12, 4, 5, 2,};
Vector
A Vector in Java is a dynamic array and is a part of the [Link] package and implements a
growable array of objects. Unlike arrays, vectors can grow or shrink dynamically as needed.
It is similar to ArrayList but synchronized, making it thread-safe.
Characteristics of Vector
1. Resizable
2. Heterogenous elements
3. Synchronized // only one thread can access at a time
4. Stores only objects ( use wrapper class for primitives)
5. Maintains insertion order
Example
import [Link];
Vector names = new Vector<>();
[Link]("Alice");
To iterate on vector
for (int num : numbers) {
[Link](num);
Class
A class in Java is a blueprint or prototype from which objects are created. It defines a
datatype by bundling data and methods that work on the data into one single unit.
Constructors of Vector
1. Vector(): Creates a default vector of the initial capacity is 10.
Vector v = new Vector();
2. Vector(int size): Creates a vector whose initial capacity is specified by size.
Vector v = new Vector(int size);
3. Vector(int size, int incr): Creates a vector whose initial capacity is specified by size and
increment is specified by incr. It specifies the number of elements to allocate each time a
vector is resized upward.
Vector v = new Vector(int size, int incr); basically 2d
4. Vector(Collection c): Creates a vector that contains the elements of collection c.
Vector v = new Vector(Collection c);
Static
In Java, we make a function (method) static when we want to call it without creating an
object of the class.
class Math{
static int add(int a, int b) {
return a + b;
public class Main {
public static void main(String[] args) {
int sum = [Link](5, 3); // No object needed!
[Link](sum);
• //Static class is also same and we can’t create objects of it only used to hold static
method and field.
• //A static object means an object created from a class, but declared as static.
It exists only once in memory and is shared across all instances of the class where
it’s defined.
Inheritance in Java
1. Hierarchical
2. Single
3. Multilevel
//Java does not support multiple inheritance because of diamond problem leading to
ambiguity.
The Diamond Problem:
• This problem occurs when a class inherits from two or more classes that share a
common ancestor.
• If the common ancestor has a method with the same name and signature, the
subclass inherits conflicting implementations of that method.
Packages
A package in Java is a group of related classes and interfaces. Packages help in organizing
the classes in a logical manner and avoid class name conflicts. Java packages are similar
to folders in a file directory.
Built-in Packages –
Provided by Java API o Examples: [Link], [Link], [Link], [Link]
Syntax to Define a Package
package mypackage; // Should be the first statement in the file public class
MyClass {
public void show() {
[Link]("Package Example");
}}
javac -d . [Link] # Compiles and creates package structure java
[Link] # Runs the program
Advantages of Using Packages
• Helps organize classes
• Avoids name conflicts
• Provides access protection
• Makes searching/locating classes easier
Exception
An exception is an unwanted or unexpected event that disrupts the normal flow of a
program. It occurs during program execution and can lead to abnormal program
termination if not handled properly.
Types of Exceptions
1. Checked Exceptions (Compile-time exceptions)
Must be either caught or declared in the method using throws. o Example: IOException,
SQLException
2. Unchecked Exceptions (Runtime exceptions)
Occur during runtime, not checked by the compiler o Example: NullPointerException,
ArithmeticException, ArrayIndexOutOfBoundsException
3. Errors
Serious problems that a program should not try to catch o Example: OutOfMemoryError,
StackOverflowError
Multithreading
Multithreading is a feature of Java that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU. Each part of such a program is called a thread.
Java supports multithreading by providing built-in support for threads via the
[Link] class and the Runnable interface.
Benefits of Multithreading:
• Efficient CPU utilization
• Simultaneous operations
• Better performance in resource-heavy programs
• Parallelism for tasks like file downloads, animations, etc.
Life Cycle of a Thread
1. New – Thread object is created
2. Runnable – Thread is ready to run
3. Running – Thread is currently executing
4. Blocked/Waiting – Thread is paused for a resource or condition
5. Terminated – Thread has completed execution
Creating a Thread in Java
Method 1: Extending the Thread class
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
} public static void main(String[] args) {
MyThread t1 = new MyThread(); [Link]();
}}
Method 2: Implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread is running..."
); } public static void main(String[] args) {
Thread t = new Thread(new MyRunnable()); [Link]();
}}
Thread Priorities:
• Range: 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY)
• Default: 5 (NORM_PRIORITY)
• Threads with higher priority get preference by scheduler
Synchronization
Used to prevent thread interference and consistency problems when multiple threads
access shared resources.
Inter-thread Communication
Allows threads to communicate using:
• wait()
• notify()
• notifyAll()
Daemon Threads
• Background threads that provide services to user threads
• Dies when all user threads die
Unit 2
An applet is a small, Java program, designed to be run within a web browser. Applets
provide interactive and dynamic content, such as animations or games, that go beyond
what static HTML can offer
Applets can respond to user actions, such as mouse input, and are used for visual
elements, games, and other dynamic features.
//Because they execute code on a user's machine, applets have raised security concerns,
leading to decreased support in modern browsers
//Applets don’t run on their own like regular Java programs. They need a web browser or a
special tool called the applet viewer or have enabled web browser like Netscape or HotJava
Example
import [Link]
public class HelloApplet extends Applet {
public void paint(Graphics g) {
[Link](“Hello, World!”, 50, 25);
}}
To run the applet, you would need to include the following HTML
code in a web page
<applet code=”[Link]” width=”300″ height=”300″> </applet>
When the web page loads, the Java applet is executed within the browser
window, and the message “Hello, World!” is displayed.
Difference between applet and application
Applet Application
A small program that runs inside a web A standalone program that runs
browser. independently on a computer.
Runs in a browser or Applet viewer. Runs using the Java Runtime Environment
(JRE).
Does not use the main() method. Uses the main(String[] args) method as
the entry point.
Typically uses AWT (Abstract Window Can use AWT, Swing, JavaFX, or no GUI
Toolkit). at all.
Used to create interactive features in web Used to build desktop, command-line, or
pages (outdated now). server-side applications.
Uses lifecycle methods like init(), start(), Does not have built-in lifecycle methods.
stop(), destroy().
Embedded in HTML and run via a browser Installed and run on the local machine.
plugin.
Drawing animations or games on a A calculator app, text editor, or server
webpage. program.
Applet Life Cycle
1. Init()
2. Start()
3. Paint()
4. Stop()
5. Destroy()
AWT (Abstract Window Toolkit)
AWT is Java’s original platform-dependent GUI toolkit.
• It is part of Java Foundation Classes (JFC) used for building (GUI).
• Provides predefined classes for creating windows, buttons, menus, scrollbars, labels,
and more.
• Resides in the [Link] package
Components
AWT provides various components such as buttons, labels, text fields, checkboxes, etc
Containers
t is a special type of component that holds another component, including other containers.
AWT provides containers like panels, frames, and dialogues to organize and group
components in the Application
Layout Manager
Layout Managers
are responsible for arranging data in the containers some of the layout managers are
BorderLayout, FlowLayout, etc.
Components
1. Button
2. Label
3. Textfields
4. TextArea
5. Checkboxes
6. Menus
7. Events
Events
An event is an object that describes a state change in a source. It can be generated as a
consequence of a person interacting with the elements in a GUI.
Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse
What is a Layout Manager
In Java AWT ,a Layout Manager is an object that controls the size and positioning of
components (like buttons, labels, text fields, etc.) inside a container such as a Frame,
Panel, or Applet.
Instead of manually specifying the location and size of each component using setBounds()
Types of Layouts
1. FlowLayout
Arranges in row left to right , wraps in next line when not enough space
2. BorderLayout
Divide areas into north, south , east , west and center, only one component can be
added per region
3. GridLayout
Arranges in matrix format, equal cells and components are resized to fill the cell
4. CardLayout
Allows to stack components on top of each other and only one is visible
5. GridbagLayout
Arranges in matrix cells and cells can have diff sizes and components can span to
multiple rows and cols
String handling
1. Concat() and + operator
2. Equals()
3. equalsIgnoreCase()
4. compareTo()
5. indexOf()
6. lastIndexOf()
7. contains()
8. replace()
9. replaceFirst()
10. replaceAll()
11. substring(start index, end index)
12. trim()
13. .length
14. valueOf()
15. toString()
Unit 3
Networking enables data exchange between different applications running on the same or
different systems. Java's [Link] package contains classes and interfaces for networking
operations, supporting both low-level (socket) and high-level (URL) communication
Example Diagram: Client-Server Communication
Socket programming
Socket programming in Java allows different programs to communicate with each other
over a network, whether they are running on the same machine or different ones.
A Client connects, sends messages to the server and the server shows them using a
socket connection. Note: A "socket" is an endpoint for sending and receiving data across a
network.
1. Client-Side Programming
• Establish a socket connection
To connect to another machine, we need a socket connection. A socket
connection means both machines know each other’s IP address and TCP
port. The [Link] class is used to create a socket. Socket socket =
new
Socket(“[Link]”, 5000) // IP and port number to run on
• Communication
To exchange data over a socket connection, streams are used for input and
output:
Input Stream: Reads data coming from the socket.
Output Stream: Sends data through the socket.
• Closing connection
The socket connection is closed explicitly once the message to the server is
sent
2. Server-Side programming
• Establish a socket connection
We need
ServerSocket: wait for incoming connections on port
Socket: the server uses this to communicate
• Communication
The getOutputStream() method is used to send data to the client.
• Close the connection
Type of socket
1. Datagram sockets
Allow processes to use the UDP. It is a two-way flow of communication or
messages. It can receive messages in a different order from the sending way and
also can receive duplicate messages
2. Stream sockets
Allows processes to use the TCP for communication,provides a sequenced,
constant or reliable, and two-way (bidirectional) flow of data. After the
establishment of connection, data can be read and written to these sockets in a
byte stream
3. Raw sockets
Provide user access to the Internet Control Message Protocol (ICMP). Only the
superusers can access the Raw Sockets
4. Sequenced packet socket
provide a reliable, connection-oriented, message-based communication service
where each packet of data is sent and received as a whole, without merging or
splitting like in TCP streams
They preserve message boundaries while still guaranteeing delivery order.
They are often implemented in operating systems using protocols like SCTP (Stream
Control Transmission Protocol).
UDP
is a connectionless protocol where data is sent as packets called datagrams without
establishing a dedicated connection.
Each packet is independent, and there is no guarantee of delivery, order, or duplication
protection. However, it is faster and more suitable for time sensitive applications.
Advantages
1. Low latency and faster communication
2. Suitable for real time apps such as live streaming and online gaming
Disadvantages
1. No reliability
2. No congestion control
Class used in UDP
• DatagramSocket
• DatagramPacket
Working of DatagramSocket
Sender Side
1. Create a DatagramSocket
2. Prepare Data
3. Create a DatagramPacket
4. Send the Packet
Receiver Side
1. Create a DatagramSocket
2. Prepare a DatagramPacket for receiving
3. Receive the packet
4. Extract Data
TCP
Is a reliable, connection-oriented protocol that ensures data is delivered correctly and in
order. It is used in most network communication scenarios, such as web browsing, file
transfers, and emails
Advantages
• Reliable communication with guaranteed delivery
• Maintains the order of data packets
• Error detection and correction
Disadvantages
• Slower than UDP due to overhead of connection management and error checking
Classes used in TCP
• ServerSocket
• Socket
Working of TCP
1. Server Creates a ServerSocket
2. Client Creates a Socket
3. I/O streams are created for communication
4. Data is sent over these Streams
5. Connection is closed
Event Handling in networking
Event is something that happens during communication like client connects to server ,msg
arrives and error occurs.
Error handling means writing code that gets triggered automatically when these events
happen.
Delegation Event Model
Event source: object that generates that event
Event object: contains info about event like its type,source and additional details like
mouse coords or key pressed.
Common event objects:
1. ActionEvent
2. MouseEvent
3. KeyEvent
4. WindowEvent
Event Listener: An interface that must be implemented by any class that wants to handle
an event
Common event listeners are:
1. ActionListener
2. MouseListener
3. KeyListener
4. WindowListener
Example event types
1. onConnect
2. onMessage
3. onDisconnect
4. onError
JDBC
It’s an API (set of interfaces & classes in [Link] package) that lets Java programs talk to
relational databases
Features
1. Platform independent and database independent
2. Supports SQL queries for both retrieving and modifying data
3. Allows stored procedures, batch processing and transactions
4. Exception handling using SQLexception
Architecture of JDBC
• Application: Any java app or servlet that communicates with data source
• The JDBC API: Allows java programs to execute SQL queries and get results
• DriverManager: Decides which driver to use based on the database you want to
connect
• JDBC drivers: Translate JDBC commands into language
JDBC Drivers
JDBC Drivers are software components that enable Java applications to interact with a
database by converting JDBC method calls into database specific calls.
Type 1: JDBC-ODBC Bridge Driver
Uses the ODBC driver to connect to the database
• Pros: Can connect to many databases if ODBC driver is available.
• Cons: Slow, needs ODBC installed, platform-dependent.
Removed in Java 8+.
Type 2: Native-API Driver (Partly Java)
Converts JDBC calls into native calls of the database’s client libraries.
• Pros: Faster than Type 1, supports database-specific features.
• Cons: Needs native libraries installed, platform-dependent
Type 3: Network Protocol Driver (Fully java with middleware)
Sends JDBC calls to a middleware server, which then talks to the database
• Pros: Platform-independent, can access multiple databases.
• Cons: Needs a middleware server, extra network hop.
Type 4: Thin Driver (Pure Java)
Converts JDBC calls directly into the database’s network protocol.
• Pros: Fastest, 100% Java, platform-independent, no extra installations.
• Cons: Database-specific (need a different driver for each database).
Establishing connection in JDBC
1. Load the Driver
2. Create Connection
3. Create Statement
4. Execute SQL Queries
5. Process Results
6. Close the Connection
JDBC-Connection Pooling
Connection pooling is a technique of reusing database connections instead of creating a
new one every time.
It stores multiple pre-created connections in a pool and gives them to programs when
needed.
Why?
• Faster
• Efficient
• Scalable
How it works?
1. At app startup, pool creates a set number of connections
2. When program needs it borrows from pool
3. When done it returns to pool
4. The same connection can be reused by other parts of program
Unit 4
HTML is a Markup Language which means you use HTML to simply "mark-up" a text
document with tags that tell a Web browser how to structure it to display
Hypertext refers to the way in which Web pages (HTML documents) are linked together.
Thus, the link available on a webpage is called Hypertext.
HTML Tags
1. <!DOCTYPE html>
Declares the document type and version of HTML
2. <html lang = “en”>
Root element of HTML document. Lang = “en” specifies the language as English
3. <head>
Contains the meta info about the document
4. <title>
Sets the title of the web page
5. <body>
Contains the visible content of the web page
Syntax of an HTML Comment:
<!--This is a comment -->
Basic Text formatting tags in HTML
1. <b> bold text
2. <strong> bold ( semantic )
3. <i> italic text
4. <em> italic ( semantic )
5. <u> (underlined text)
6. <sup> (superscript)
7. <sub> (subscript)
HTML Symbol Entities
Symbols or letters that are not present on your keyboard can be added to HTML using
entities.
HTML <hr> Tag
The <hr> element is most often displayed as a horizontal rule that is used to separate
content in an HTML page
HTML <br> tag
<br> adds single line break
Key elements of html table
<table> define the table
<tr> used for table rows
<th> used for table headings
<td> used for table cells
Basic Structure
<table border='1'>
<tr>
<th colspan = “2”>Name</th> //col or row span to span the cell to multiple cells like merge
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>27</td>
</tr>
<tr>
<td>Alice</td>
<td>37</td>
</tr>
<tr>
<td>Daisy</td>
<td>32</td>
</tr>
</table>
Html forms
HTML forms are essential for collecting user input on web pages. Whether it's a search bar,
a login screen, or a multi-field registration form. They enable users to submit data, which
can be processed, stored, or returned by a server.
HTML Forms Structure:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
Common type values include:
1. Text
2. Password
3. Email
4. Checkbox
5. Radio
6. Submit
7. Button
8. Hidden
HTML <meta> Tag
The <meta> tag defines metadata about an HTML document. Metadata is
data (information) about data.
• <meta> tags always go inside the <head> element, and are typically used
to specify character set, page description, keywords, author of the
document, and viewport settings.
• Metadata will not be displayed on the page, but is machine parsable.
• Metadata is used by browsers ,search engines (keywords), and other web services.
Example
<head>
<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="John Doe">
<meta name="viewport" content="width=device-width, initialscale=1.0">
</head>
Image Format
describes how data related to the image will be stored. Data can be stored in compressed,
Uncompressed, or vector format.
1. JPEG (.jpg, .jpeg):
Joint Photographic Experts Group is a loss-prone (lossy) format in which data is
lost to reduce the size of the image. Due to compression, some data is lost but
that loss is very less.
2. GIF (.gif):
GIF or Graphics Interchange Format files are used for web graphics. They can be
animated and are limited to only 256 colors, which can allow for transparency.
GIF files are typically small in size and are portable.
3. PNG (.png):
PNG or Portable Network Graphics files are a lossless image format. It
was designed to replace gif format as gif supported 256 colors unlike
PNG which supports 16 million colors.
CSS
CSS is a stylesheet language that describes the presentation of an HTML (or XML)
document. CSS describes how elements must be rendered on screen, on paper, or in
other media
CSS is used to define styles for your web pages, including the design, layout and
variations in display for different devices and screen sizes
3 Ways of styling
Unit 5
1. Introduction — What is a Servlet?
A Servlet is a Java class that runs on a web/application server and implements a request–
response
model to build dynamic web content.
It receives requests from clients, processes them (possibly interacting with databases),
and returns
responses. Servlets are part of the Java EE / Jakarta EE web technology stack.
Important packages: [Link].*, [Link].*
2. HTTP Servlet Basics
To create a servlet, extend the HttpServlet class and override its doGet() or doPost()
methods.
Request methods: getParameter(), getHeader(), getCookies()
Response methods: setContentType(), getWriter(), sendRedirect()
3. Servlet Lifecycle
Servlet lifecycle is managed by the container and consists of:
1. Loading and Instantiation
2. Initialization using init()
3. Request handling using service() → doGet()/doPost()
4. Destruction using destroy()
Each servlet is loaded once, then reused across requests. Cleanup happens in destroy().
4. Retrieving Information
Use HttpServletRequest to read client input:
• getParameter(name) — single form value
• getParameterValues(name) — multiple values
• getHeader(name) — request headers
• getCookies() — cookies sent by client
String username = [Link]("username");
String[] hobbies = [Link]("hobby");
String userAgent = [Link]("User-Agent");
5. Sending HTML Information
Servlets can generate HTML content dynamically and send it as a response.
Use setContentType('text/html') and getWriter() to write output.
6. Session Tracking
HTTP is stateless; servlets use various methods to maintain session state:
1. Cookies — small key/value data stored on client
2. URL Rewriting — appending session ID to URL
3. Hidden Form Fields — session ID in hidden input field
4. HttpSession API — server-managed session object
7. Database Connectivity (JDBC from Servlets)
JDBC is used for connecting servlets to databases. Common steps include:
1. Load JDBC Driver
2. Establish Connection
3. Create Statement
4. Execute query/update
5. Close all resources
Unit 6
Introducing Java Server Pages
Java Server Pages (JSP) It enables developers to embed Java code directly into HTML pages,
making it easier to create dynamic and interactive websites.
JSP separates the user interface from content generation, which enhances maintainability
and reusability of code. With JSP, web designers can work on the HTML portion while
programmers focus on the business logic.
JSP Overview
JSP is built on top of the Java Servlet API and uses the same requestresponse model.
When a JSP page is requested for the first time, it is translated into a Servlet
by the JSP engine and then compiled. This means JSP pages ultimately run
as Servlets.
Key features of JSP:
1. Simplicity – Easy to embed Java code inside HTML.
2. Platform Independence – Runs on any platform that supports Java.
3. Built-in Objects – Provides implicit objects such as request, response,
session, and application.
4. Reusability – JSP supports reusable components like custom tags and
JavaBeans.
5. Extensibility – Developers can extend JSP using libraries and
frameworks.
Setting Up the JSP Environment
The environment includes:
1. Java Development Kit (JDK) – To compile and run Java code.
2. Web Server/Servlet Container – For example, Apache Tomcat is widely
used for JSP development.
3. IDE (Optional) – Tools like Eclipse, IntelliJ IDEA, or NetBeans make
development easier.
Steps:
- Install JDK and configure environment variables (JAVA_HOME, PATH).
- Download and install Apache Tomcat server.
- Deploy JSP files into the 'webapps' directory of Tomcat.
- Start Tomcat and access JSP pages through a web browser.
Generating Dynamic Content
One of the core advantages of JSP is its ability to generate dynamic web content.
Dynamic content means the web page changes based on user inputs, session data, or
information fetched from databases.
Examples:
- Displaying user-specific content after login.
- Showing the current date and time.
- Retrieving records from a database and displaying them in an HTML table.
Dynamic content is achieved by embedding Java code into JSP using scriptlets (<% %>),
expressions (<%= %>), and declarations (<%! %>). However, the modern
approach encourages the use of JSTL (JSP Standard Tag Library) and EL (Expression
Language) to minimize scriptlet usage.
Using Custom Tag Libraries and the JSP Standard Tag Library
JSP allows developers to extend functionality by creating and using custom tag libraries.
These tags encapsulate complex logic inside simple tags that can be reused
in different JSPs.
The JSP Standard Tag Library (JSTL) is a collection of ready-to-use
tags that simplify common tasks such as:
1. Iteration and conditionals (loops, if-else).
2. Database access.
3. XML data handling.
4. Internationalization
Advantages of using JSTL and custom tags:
- Separation of business logic from presentation.
- Better readability and maintainability of code.
- Reusability across multiple JSP pages.
Processing Input and Output
JSP provides mechanisms to handle input from users and generate appropriate output.
User input is usually collected using HTML forms and processed using JSP
with the help of request and response objects.
Steps for input and output processing:
1. User submits data via an HTML form (GET or POST request).
2. JSP retrieves data using '[Link]()' method.
3. JSP processes the data (validation, business logic, database operations).
4. Output is generated dynamically and sent back to the client in the form of
HTML.
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.
Custom Tag Libraries
Custom tags are user-defined JSP tags. They provide a way to write reusable components
(like Java classes) but use them in JSP pages with an HTML-like syntax.
Benefits
• Clean separation of business logic and presentation.
• Reusable code across multiple JSP pages.
• Easy to understand (tags look like HTML).
• Reduce use of scriptlets (<% %>).
JSP Standard Tag Library (JSTL)
• JSTL is a predefined set of commonly used custom tags provided
by Java.
• It eliminates the need to write scriptlets in JSP.
• JSTL makes JSP development easier, faster, and cleaner.