Advanced Java
Advanced Java
Unit-1
Introduction to Java
Key Features of Java
Basic Syntax
Java Identifiers
Java Modifiers
Variables
Introduction to Java
Inheritance
Superclass and Subclass
Syntax
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Not Supported)
Example
Key Points
Exception Handling
Basics of Exception Handling
Syntax
Example 1: Arithmetic Exception
Example 2: ArrayIndexOutOfBoundsException
Example 3: NullPointerException
Handling Multiple Exceptions
The finally Block
Conclusion
Multithreading
Basics of Multithreading
Example 1: Creating a Thread by Extending Thread Class
Example 2: Creating a Thread by Implementing Runnable Interface
Example 3: Thread Synchronization
Conclusion
Applet Programming
Basics of Applet Programming
Example 1: Simple Applet
Unit-1
Introduction to Java
Java is a high-level, class-based, object-oriented programming language that
is designed to have as few implementation dependencies as possible. It is a
general-purpose programming language intended to let application developers
write once, run anywhere (WORA), meaning that compiled Java code can run
on all platforms that support Java without the need for recompilation.
Secure: Java does not use explicit pointers and run the programs inside the
sandbox to prevent any activities from untrusted sources. It enables to
develop virus-free, tamper-free systems/applications.
Basic Syntax
Java syntax is the set of rules defining how a Java program is written and
interpreted.
Class Names: For all class names the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first
letter should be in Upper Case.
Method Names: All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.
File Name: The name of the program file should exactly match the class
name.
public static void main(String args[]): Java program processing starts from
the main() method which is a mandatory part of every Java program.
Java Identifiers
All Java components require names. Names used for classes, variables, and
methods are called identifiers. In Java, there are several points to remember
about identifiers. They are as follows:
After the first character, identifiers can have any combination of characters.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using
modifiers. There are two categories of modifiers:
Variables
We would see following type of variables in Java:
Local Variables
Introduction to Java
Java Overview:
Features of Java:
Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP)
that allows a new class to inherit properties and behavior from an existing
class. In Java, inheritance enables code reuse and establishes relationships
between classes.
Subclass (Child Class): The class that inherits properties and methods
from another class.
Syntax
class Superclass {
// superclass members
}
Types of Inheritance
1. Single Inheritance
In single inheritance, a subclass inherits from only one superclass.
class Animal {
// Animal class members
}
2. Multilevel Inheritance
In multilevel inheritance, a subclass inherits from a superclass, and another
class inherits from this subclass.
class Animal {
// Animal class members
}
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses inherit from a single superclass.
class Animal {
// Animal class members
}
Example
// Superclass
class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.move(); // Output: Vehicle is moving
car.accelerate(); // Output: Car is accelerating
}
}
Key Points
Inheritance promotes code reuse and maintains a hierarchical structure.
throws: Keyword used to declare that a method may throw a particular type
of exception.
Syntax
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} finally {
// Code that always executes, regardless of whether an
exception occurred or not
}
message.
Example 2: ArrayIndexOutOfBoundsException
Example 3: NullPointerException
In this example, the try block contains code that may throw two different types
of exceptions ( ArrayIndexOutOfBoundsException and ArithmeticException ). Each catch
block handles a specific type of exception.
The finally block contains code that always executes, regardless of whether
an exception occurred or not. It is typically used for cleanup tasks like closing
resources (e.g., files, database connections).
Conclusion
Exception handling is crucial for writing robust and reliable Java programs. By
anticipating and handling exceptions, developers can ensure that their
applications gracefully recover from errors and continue executing smoothly.
Understanding exception handling mechanisms enables developers to write
more resilient code.
Multithreading
Multithreading is a programming concept that allows multiple threads to
execute concurrently within a single process. In Java, multithreading enables
developers to create applications that can perform multiple tasks
simultaneously, improving efficiency and responsiveness.
Basics of Multithreading
Thread: A lightweight process that executes independently within a
program.
class Counter {
private int count = 0;
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println(e);
}
In this example, two threads ( thread1 and thread2 ) increment a shared counter
( Counter object) concurrently. The synchronized keyword ensures that only one
thread can execute the increment() method at a time, preventing race conditions
and ensuring data consistency.
Conclusion
Multithreading in Java allows developers to write efficient and responsive
applications by leveraging the power of concurrency. By creating and
managing multiple threads, developers can perform tasks concurrently, making
the most out of modern multicore processors and improving overall application
performance. Understanding multithreading concepts is essential for building
scalable and high-performance Java applications.
Applet Programming
Applet programming in Java enables developers to create dynamic and
interactive content that can be embedded within web pages. Java applets
provide a platform-independent way to enhance web pages with features such
as animations, games, and interactive forms.
import java.applet.Applet;
import java.awt.Graphics;
In this example, we create a simple applet that displays the text "Hello, World!"
at coordinates (20, 20) on the applet's surface.
import java.applet.Applet;
import java.awt.Graphics;
This example demonstrates drawing basic shapes (rectangle, oval, line) using
the Graphics object provided by the paint() method.
import java.applet.Applet;
import java.awt.Graphics;
// MouseListener methods
public void mouseClicked(MouseEvent e) {
x = e.getX(); // Get X-coordinate of mouse click
y = e.getY(); // Get Y-coordinate of mouse click
repaint(); // Refresh applet
}
Example 4: Animation
import java.applet.Applet;
import java.awt.Graphics;
This example creates an animated applet where text moves horizontally across
the applet's surface.
Conclusion
Java applets provide a versatile platform for creating interactive content within
web pages. By leveraging the Applet class and its associated methods,
developers can design engaging and dynamic experiences for users directly
within their web browsers. Understanding applet programming enables
Additional Points:
Certainly! Here are some additional points that can be added to the topics we
discussed:
Inheritance:
Method Overriding: Subclasses can provide a specific implementation for a
method defined in the superclass, allowing for polymorphic behavior.
Exception Handling:
Checked vs Unchecked Exceptions: Java distinguishes between checked
exceptions (which must be caught or declared in a throws clause) and
unchecked exceptions (which do not need to be explicitly handled).
Multithreading:
Thread Pools: Instead of creating and managing individual threads,
applications can use thread pools to efficiently manage a pool of reusable
threads, reducing overhead and improving performance.
Applet Programming:
Applet Lifecycle: Understand the sequence of methods invoked during the
lifecycle of an applet, such as init() , start() , stop() , and destroy() , and
their respective purposes.
Adding these additional points can enhance the understanding and depth of
knowledge on the respective topics.
Connecting to a Server
Connecting to a server in Java typically involves network communication,
where a client application communicates with a server over a network protocol
import java.io.*;
import java.net.*;
2. Server Side:
Explanation:
The client creates a Socket object, specifying the server's address and port
number.
It then gets the output stream from the socket and sends data to the server
using a PrintWriter .
The server creates a ServerSocket object bound to a specific port and listens
for incoming connections using serverSocket.accept() .
Upon accepting a connection, it gets the input stream from the client socket
and reads data from it using a BufferedReader .
Additional Considerations:
Handling Multiple Clients: For handling multiple clients, you would typically
create a new thread for each client connection in the server code.
Implementing Servers
Implementing servers in Java involves creating applications that listen for
incoming connections from clients and handle those connections according to
the desired functionality. Here's a basic outline of how to implement a simple
server in Java using sockets:
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
The ClientHandler thread reads data from the client, processes it, and sends
a response back.
Additional Considerations:
Thread Safety: Ensure thread safety when accessing shared resources or
performing concurrent operations.
import java.io.*;
import java.net.*;
2. Open a Connection:
4. Read Response:
Additional Considerations:
Security: Sanitize user inputs and validate URL inputs to prevent security
vulnerabilities like injection attacks.
This example demonstrates the basic steps for making URL connections in
Java. Depending on your use case, you may need to customize the request
headers, handle redirects, or handle other aspects of HTTP communication.
Implementing Servers:
Thread Pooling: Instead of creating a new thread for each incoming client
connection, consider using a thread pool to limit the number of
concurrently running threads and prevent resource exhaustion.
Basic Concepts:
1. Client-Server Model:
2. Socket:
Sockets are classified into two types: client sockets and server sockets.
3. Server Socket:
Provides input and output streams for communicating with the server.
2. ServerSocket Class:
Accepts incoming client connections and creates a new socket for each
client.
Server Code:
import java.io.*;
import java.net.*;
Client Code:
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
out.println("Hello, Client!");
clientSocket.close();
} catch (IOException e) {
Conclusion:
Socket programming in Java allows applications to communicate over the
network using sockets. By understanding the concepts of sockets, Socket and
ServerSocket classes, and their usage in Java, you can develop client-server
UNIT-II
Preparing a class to be a Java Bean
Preparing a class to be a Java Bean involves adhering to a specific set of
conventions and requirements to ensure interoperability and compatibility with
various Java frameworks and tools. Here's a detailed explanation of how to
prepare a class to be a Java Bean:
Provide public setter methods (mutators) to set the values of the fields.
4. Consistency:
import java.io.Serializable;
Conclusion:
Preparing a class to be a Java Bean involves adhering to conventions such as
providing a default constructor, using getter and setter methods, and optionally
implementing the Serializable interface. By following these conventions, you
// Constructor
public Person() {
// Default constructor
}
import java.io.Serializable;
Conclusion:
By following these steps, you can create a Java Bean that encapsulates data
and behavior within a self-contained unit. Java Beans adhere to specific
Definition:
A Java Bean property is a named attribute that defines the state of a Java
Bean. Properties provide a way to access and modify the internal state of an
object in a controlled manner, while encapsulating the implementation details.
// Constructor
public Person() {
// Default constructor
}
Usage:
Benefits:
Encapsulation: Properties encapsulate the state of an object, hiding its
internal implementation details.
Access Control: Getter and setter methods provide controlled access to the
bean's state, enabling validation, security, and other logic.
By defining Java Bean properties and providing getter and setter methods, you
create reusable and modular components that facilitate the development of
robust and maintainable Java applications.
Types of beans
In Java programming, there are several types of beans, each serving a specific
purpose and adhering to particular conventions. Let's explore the common
types of beans:
1. Standard JavaBeans:
These are regular Java classes that adhere to the JavaBeans specification,
providing properties (with getter and setter methods), constructors, and
optionally implementing the Serializable interface. Standard JavaBeans are
used in various Java frameworks and tools for building reusable components.
Example:
// Constructor
public Person() {
// Default constructor
@Stateless
public class ShoppingCartBean implements ShoppingCart {
// Implementation of business logic
}
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean {
private String username;
private String password;
4. Spring Beans:
Spring Beans are components managed by the Spring Framework's Inversion
of Control (IoC) container. These beans are configured and managed by the
Spring container, and they can be wired together to form the application's
architecture.
Example:
@Component
public class UserService {
// Implementation of service methods
}
@Named
@SessionScoped
public class ShoppingCart {
// Implementation of shopping cart functionality
}
Conclusion:
These are some of the common types of beans in Java programming. Each
type serves a specific purpose and is used in different contexts, such as
building enterprise applications, web applications, or components managed by
frameworks like Spring or Java EE. Understanding these types of beans and
their usage is essential for Java developers to build robust and scalable
applications.
2. Client Affinity:
3. Lifecycle Management:
4. State Serialization:
Serializable state allows the container to store and retrieve the state of
SFSBs from secondary storage as needed.
5. Scoped Context:
import javax.ejb.Stateful;
@Stateful
public class ShoppingCartBean implements ShoppingCart {
private List<String> items = new ArrayList<>();
Conclusion:
Stateful Session Beans provide a mechanism for maintaining conversational
state between multiple method invocations for a specific client in Java EE
applications. They allow developers to build applications with stateful
interactions, such as shopping carts, wizards, or transactional workflows, by
managing the state of client sessions within the EJB container. Understanding
the characteristics and usage of Stateful Session Beans is crucial for
developing stateful and conversational Java EE applications.
2. Lightweight:
3. Concurrency:
4. Transaction Management:
5. Scoped Context:
@Stateless
public class CalculatorBean implements Calculator {
public int add(int a, int b) {
return a + b;
}
Conclusion:
Stateless Session Beans are lightweight components used in Java EE
applications for executing stateless business logic efficiently. They do not
maintain conversational state between method invocations, allowing for
scalable and concurrent processing of client requests. Understanding the
characteristics and usage of Stateless Session Beans is crucial for developing
efficient and scalable Java EE applications.
Entity Beans:
Entity beans are Enterprise JavaBeans (EJBs) used to represent persistent data
entities in a Java EE application. They typically map to tables in a relational
database and provide a way to interact with the underlying data through an
object-oriented interface. Entity beans encapsulate the data and business logic
related to a specific entity, such as a customer, product, or order.
CRUD Operations: Entity beans support Create, Read, Update, and Delete
(CRUD) operations, enabling developers to manipulate persistent data
entities using standard Java methods.
Architecture:
Entity Bean Class: Represents a persistent data entity and typically
corresponds to a database table. It contains attributes representing table
columns and methods for accessing and manipulating entity data.
Servlets:
Servlets are Java classes used to extend the functionality of web servers and
handle HTTP requests and responses. They provide a way to generate dynamic
web content, process form submissions, and interact with clients over the
HTTP protocol.
Web Application Logic: Servlets encapsulate the application logic for web-
based interactions, such as user authentication, data validation, and
business process execution.
Architecture:
Servlet Class: Represents the main logic for processing HTTP requests and
generating responses. Servlet classes extend the
javax.servlet.http.HttpServlet class and override methods like doGet() and
doPost() to handle specific types of HTTP requests.
Integration:
Entity beans and Servlets are often used together in Java EE applications to
implement web-based data management systems. Servlets handle incoming
HTTP requests, perform data processing, and invoke business logic
implemented in entity beans to interact with persistent data entities. This
integration allows developers to build robust and scalable web applications that
leverage the capabilities of both technologies.
3. destroy() :
This method is called by the servlet container to indicate that the servlet
instance is being destroyed.
This stage occurs only once during the lifecycle of the servlet.
2. Initialization:
3. Servicing Requests:
4. Destruction:
When the servlet container decides to remove the servlet instance (e.g.,
due to application shutdown or servlet reloading), it calls the destroy()
method.
The destroy() method allows the servlet to release any resources held
during its lifetime, such as closing database connections or releasing
file handles.
Lifecycle Events:
Servlet containers may provide mechanisms for registering listeners to
receive notifications about lifecycle events of servlets.
Conclusion:
The Servlet interface defines the standard protocol for building Java servlets,
which are server-side components used in Java EE web applications.
Understanding the servlet life cycle is crucial for developing servlets that
perform initialization, request processing, and resource cleanup tasks
efficiently. By implementing the Servlet interface and managing the servlet life
cycle properly, developers can build robust and scalable web applications in
Java.
Handling
Handling HTTP GET Requests:
HTTP GET requests are commonly used for retrieving data from a server. In the
context of servlets, handling HTTP GET requests typically involves extracting
information from the request (such as query parameters or path variables),
processing the request, and generating an appropriate response.
In the servlet class, override the doPost() method to handle HTTP POST
requests.
Extract data from the request body, such as form parameters or JSON
payloads, using methods provided by the HttpServletRequest object
( getReader() or getInputStream() ).
Conclusion:
Handling HTTP requests (both GET and POST) in servlets involves extracting
data from the request, processing it, and generating an appropriate response.
By overriding the doGet() and doPost() methods in a servlet class, developers
can implement custom request-handling logic to meet the requirements of their
web applications. Understanding how to handle HTTP requests effectively is
essential for building robust and interactive web applications using servlet
technology.
Session Tracking
Session tracking is a mechanism used in web development to maintain the state
of user interactions across multiple requests within a session. Sessions allow
web applications to associate data with a specific user's browsing session,
enabling features like user authentication, shopping carts, and personalized
experiences. In Java web applications, session tracking is commonly
implemented using mechanisms such as cookies, URL rewriting, and
HttpSession objects. Let's explore each of these methods:
How it works: When a user visits a website, the server sends a cookie
containing a unique session identifier. The browser stores this cookie
locally and includes it in subsequent requests to the same website. The
server uses the session identifier to retrieve session-specific data
associated with the user.
2. URL Rewriting:
URL rewriting involves appending session identifiers to URLs within a web
application. This allows the server to associate requests with specific sessions.
3. HttpSession Object:
The HttpSession object provides a server-side mechanism for tracking
sessions in Java web applications. It allows developers to store and retrieve
session-specific data.
Conclusion:
Session tracking is essential for maintaining user state and enabling
personalized interactions in web applications. In Java web development,
session tracking can be achieved using mechanisms such as cookies, URL
rewriting, and HttpSession objects. Understanding how to implement session
tracking effectively is crucial for building dynamic and interactive web
applications.
Updated: https://yashnote.notion.site/Advanced-Java-Programming-
fa0a79e50a8b4945be9f86a08b0ec425?pvs=4