Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views94 pages

Web Technology

The document provides an overview of web technologies, focusing on HTML and Java. It explains HTML's structure, tags, lists, tables, forms, and styling, as well as Java's characteristics, applications, and execution process through the Java Virtual Machine (JVM). Additionally, it introduces Object-Oriented Programming (OOP) concepts such as classes, objects, encapsulation, inheritance, and abstraction.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views94 pages

Web Technology

The document provides an overview of web technologies, focusing on HTML and Java. It explains HTML's structure, tags, lists, tables, forms, and styling, as well as Java's characteristics, applications, and execution process through the Java Virtual Machine (JVM). Additionally, it introduces Object-Oriented Programming (OOP) concepts such as classes, objects, encapsulation, inheritance, and abstraction.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

Web Technology

HTML:
HTML (HyperText Markup Language) is the standard language used to create and
structure webpages. It uses elements enclosed within tags to define the structure and
content. The basic HTML document structure is:
<!DOCTYPE html>
<html>
<head>
<title>HTML Basics</title>
</head>
<body>
<h1>Welcome to HTML</h1>
<p>This is a simple HTML document.</p>
</body>
</html>
An HTML document is divided into two main parts:
• Head Section (<head>): Contains metadata, title, links to stylesheets, and scripts.
• Body Section (<body>): Contains the visible content of the webpage.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Structure</title>
</head>
<body>
<h1>Main Heading</h1>
<p>Paragraph in the body.</p>
</body>
</html>

HTML Tags:
HTML uses tags enclosed in angle brackets (< >) to define elements. Tags can be paired
(with opening and closing tags) or self-closing. Some common useful HTML tags are:
Tag Description Example
Headings (H1 largest,
<h1>-<h6> <h1>Hello</h1>
H6 smallest)
<p> Paragraph <p>This is a paragraph.</p>
<a> Hyperlink <a href="https://example.com">Link</a>
<img> Image <img src="image.jpg" alt="Sample">
<div> Division <div>This is a div</div>
<span> Inline container <span>Text</span>

HTML Lists:
HTML provides two main types of lists:
• Ordered List (<ol>): Displays items in a numbered sequence.
• Unordered List (<ul>): Displays items with bullet points.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Lists</title>
</head>
<body>
<h2>Ordered List</h2>
<ol>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ol>
<h2>Unordered List</h2>
<ul>
<li>Python</li>
<li>Java</li>
<li>C++</li>
</ul>
</body>
</html>

HTML Tables:
HTML tables are used to display data in rows and columns.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Table</title>
</head>
<body>
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
</tr>
<tr>
<td>Jane</td>
<td>30</td>
</tr>
</table>
</body>
</html>
HTML Links and its Types:
Hyperlinks (<a>) are used to navigate to other pages or resources. The different types of
links are:
Internal Link: Links within the same website. Ex. – <a href="about.html">About Us</a>
External Link: Links to external websites. Ex. – <a href="https://example.com"
target="_blank">Visit Example</a>
Anchor Link: Navigates to a specific section in the same page. Ex. –
<a href="#section1">Go to Section 1</a>
<h2 id="section1">Section 1</h2>

HTML Images:
The <img> tag is used to display images.
Example:
<img src="image.jpg" alt="Sample Image" width="300" height="200">
Attributes:
• src: Specifies the image source.
• alt: Provides alternative text for accessibility.
• width and height: Specify dimensions.

HTML Forms:
Forms collect user input using various fields.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Forms</title>
</head>
<body>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Some common input types are:
• Text: <input type="text">
• Password: <input type="password">
• Checkbox: <input type="checkbox">
• Radio: <input type="radio">
• Submit: <input type="submit">
HTML Frames:
Frames are used to divide the browser window into multiple sections.
Example:
<frameset cols="50%,50%">
<frame src="frame1.html">
<frame src="frame2.html">
</frameset>
Note: Frames are now obsolete and replaced by CSS Grid and Flexbox.

HTML Style Sheets:


Style sheets are used to apply styles to HTML elements. There are three types:
• Inline CSS: Applies styles directly to an element. Ex. – <p style="color: red;">This is
red text.</p>
• Internal CSS: Defines styles in a <style> block in the <head> section. Ex. –
<style>
body {
font-family: Arial, sans-serif;
}
</style>
• External CSS: Links to an external stylesheet. Ex. – <link rel="stylesheet"
href="styles.css">

Example: Demonstrating All Concepts of HTML


<!DOCTYPE html>
<html>
<head>
<title>HTML Basics</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
}
table {
border-collapse: collapse;
width: 50%;
margin-top: 20px;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 8px;
text-align: center;
}
</style>
</head>
<body>
<h1>Welcome to HTML Basics</h1>
<p>This page demonstrates HTML concepts.</p>
<h2>Links</h2>
<a href="https://example.com" target="_blank">Visit Example</a>
<a href="#list">Jump to List</a>
<h2>Image</h2>
<img src="image.jpg" alt="Sample Image" width="300">
<h2 id="list">Lists</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<ol>
<li>First</li>
<li>Second</li>
</ol>
<h2>Table</h2>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
</tr>
</table>
<h2>Form</h2>
<form>
<label for="username">Name:</label>
<input type="text" id="username" name="username"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Java:
Java is a high-level, class-based, object-oriented programming language designed to have
minimal implementation dependencies. It is widely used in web development, software
engineering, and mobile app development. Java applications can run on any device that
has a Java Virtual Machine (JVM), making it platform-independent. Java follows the
Object-Oriented Programming (OOP) paradigm, which allows for modularity, reusability,
and scalability. Java's syntax is easy to learn and it provides security features like bytecode
verification and a secure execution environment.
Java Applications:
• Desktop Applications: Java is used to develop standalone applications such as media
players, antivirus software, and text editors.
• Web Applications: Java-based frameworks like Spring and Hibernate are commonly
used to build secure and scalable web applications.
• Mobile Applications: Java is the core language for Android development.
• Enterprise Applications: Java is extensively used in large-scale enterprise systems like
banking applications due to its reliability and scalability.
• Embedded Systems: Java can also be found in embedded systems like SIM cards and
smart cards.

How Java Code Executes:


• Creating the Program: Java programs are written using a text editor or an Integrated
Development Environment (IDE) like IntelliJ IDEA, Eclipse, or NetBeans. The source
code is saved with a .java extension.
• Compiling the Program: The Java compiler (javac) converts the source code into
bytecode, which is stored in a .class file. This bytecode is platform-independent and
can be executed on any machine with a JVM.
• Running the Program: The JVM executes the compiled bytecode, translating it into
machine code specific to the operating system and hardware.

Java Virtual Machine (JVM):


The Java Virtual Machine (JVM) is an essential part of the Java runtime environment,
responsible for executing Java bytecode.
• Platform Independence: JVM allows Java programs to run on any platform without
modification. It translates Java bytecode (generated after compilation) into machine
code that is specific to the underlying operating system.
• Execution of Java Code: When a Java program is compiled, it is converted into
bytecode, which the JVM interprets and executes.
• Memory Management: JVM handles memory through its Garbage Collector, which
automatically manages memory by freeing up unused objects.
• Security: JVM ensures that Java applications run securely through features like
bytecode verification, preventing malicious code from being executed.
• Key Components:
➢ Class Loader: Loads the bytecode into memory.
➢ Bytecode Interpreter: Executes the bytecode.
➢ Just-In-Time (JIT) Compiler: Converts frequently used bytecode into machine code
for better performance.

Java Runtime Environment (JRE):


The Java Runtime Environment (JRE) is a crucial component that enables the execution
of Java applications. Here’s a brief overview:
• Execution of Java Programs: JRE provides the necessary libraries and resources to run
Java programs. It includes the Java Virtual Machine (JVM), which interprets and
executes Java bytecode.
• Libraries and APIs: JRE contains essential Java class libraries and APIs that provide
functionalities like input/output, networking, and user interface components
required for running Java applications.
• JVM: The JRE comes with the JVM, which makes Java platform-independent, allowing
the same Java program to run on different operating systems.
• User-Oriented: While developers use the Java Development Kit (JDK) to write and
compile Java code, end-users only need the JRE to run Java applications.
• Key Components:
➢ JVM: Executes the bytecode.
➢ Core Libraries: Provides essential functions for the application.
➢ Deployment Technologies: Includes components like Java Web Start and Java Plug-
ins.

Java Development Kit (JDK):


The Java Development Kit (JDK) is a cross-platform software development environment
essential for building Java applications and applets. It includes all the tools needed for
Java development, such as a compiler, libraries, and a private JVM. The JDK is one of the
core components of the Java ecosystem, alongside the Java Runtime Environment (JRE)
and the Java Virtual Machine (JVM). The JDK also contains a Private Runtime, which is a
version of the JRE with additional libraries and resources specifically for development.
• JDK vs JRE: While the JRE is sufficient for running Java applications, the JDK includes
additional tools needed for development, such as a compiler and debugger.
• JDK = JRE + Development Tools.
• Java Platforms: JDK implementations are available for different Java platforms,
including Java Standard Edition (SE), Java Enterprise Edition (EE) and Java Micro
Edition (ME).
• Contents of JDK:
➢ Java Runtime Environment (JRE)
➢ Compiler (javac)
➢ Interpreter/Loader (java)
➢ Archiver (jar)

Bytecode:
Bytecode in Java is an intermediate, platform-independent representation of compiled
Java code.
• Generated by the Compiler: When a Java program is compiled, the source code (.java
file) is converted into bytecode (.class file) by the Java compiler (javac).
• Platform-Independent: Bytecode is not specific to any machine architecture, making
Java programs platform-independent. It can run on any system that has a Java Virtual
Machine (JVM).
• Executed by the JVM: The JVM interprets and executes the bytecode, converting it into
machine code specific to the host operating system.
• Optimized for Efficiency: Bytecode is designed to be compact and efficient, enabling
faster execution of Java programs across different platforms.

Java Characteristics: Java has several important traits:


• Platform-independent: Java uses the "Write Once, Run Anywhere" principle, meaning
it can run on any platform with a Java Virtual Machine (JVM), making it highly portable
across operating systems.
• Object-oriented: Java emphasizes the use of objects and classes, encapsulating data
and methods to create reusable code. The main principles of object-oriented
programming are inheritance, polymorphism, encapsulation, and abstraction.
• Secure: Java provides several security features like bytecode verification, a robust
access control mechanism, and built-in cryptography APIs, making it secure for
building web applications.
• Robust: Java minimizes system crashes by managing memory through garbage
collection, strong type-checking, and exception handling, making it less error-prone.
• Multithreading: Java supports concurrent execution of multiple tasks (threads),
enhancing performance and making it suitable for high-performance applications like
game development and server-based solutions.
• Encapsulation: This is a core object-oriented concept where the internal state of an
object is hidden from the outside. Objects expose only the necessary details via
methods, which enhances data protection.
• Polymorphism: It allows one interface to be used for a general class of actions, with
specific implementations in derived classes. For example, a parent class reference can
point to a child class object.
• Inheritance: Java allows classes to inherit properties and methods from other classes,
promoting code reuse and the ability to build hierarchical relationships among
classes.
• Abstraction: It involves hiding implementation details and exposing only the essential
features of an object or method, typically through interfaces and abstract classes.

Introduction to OOPs:
Object-Oriented Programming tries to map code instructions with real-world, making the
code short and easier to understand. With the help of OOPs, we try to implement real-
world entities such as object, inheritance, abstraction, etc. It helps us to follow the DRY
(Don't Repeat Yourself) approach of programming, which in turn increases the reusability
of the code. Two most important aspects of OOPs are:

Class:
A class is a blueprint for creating objects. Classes do not consume any space in the
memory. Objects inherit methods and variables from the class. It is a logical component.
Objects:
An object is an instantiation of a class. When a class is defined, a template (info) is defined.
Every object has some address, and it occupies some space in the memory. It is a physical
entity.
Take a look at the below example to get a better understanding of objects and classes:

How to model a problem in OOPs:


We identify the following:
• Noun - Class - Employee
• Adjective - Attributes - name, age, salary, id
• Verb - Methods - getSalary(), increment()

Four pillars of Object-Oriented-Programming Language:


• Encapsulation: It is the concept of bundling data (variables) and methods (functions)
that operate on the data into a single unit called an object. It restricts direct access to
the internal state of the object, exposing only what is necessary through public
methods. The benefits of encapsulation are:
➢ Protects data from unintended interference.
➢ Enhances security by controlling how data is accessed and modified.
➢ Promotes modularity, as objects manage their own state and behavior.
• Abstraction: It simplifies complex systems by hiding unnecessary details and exposing
only the essential features. It is achieved through abstract classes and interfaces in
OOP, where implementation details are hidden from the user. The benefits of
abstraction are:
➢ Reduces complexity, making it easier to understand and manage large systems.
➢ Enhances maintainability by allowing changes in the implementation without
affecting the users of the abstraction.
• Inheritance: It allows a new class (child or subclass) to inherit properties and
methods from an existing class (parent or superclass). The child class can use or
override the inherited features, and can also introduce its own. The benefits of
inheritance are:
➢ Promotes code reuse by allowing common functionality to be defined once and
reused in multiple classes.
➢ Helps create a hierarchical relationship between classes, supporting better
organization of code.
• Polymorphism: It means "many forms" and allows objects to be treated as instances
of their parent class, enabling the same interface to be used for different underlying
forms (objects). It can be achieved through method overloading (compile-time
polymorphism) and method overriding (runtime polymorphism). The benefits of
polymorphism are:
➢ Improves flexibility and extensibility of code by allowing a single function or
operator to work with different data types or objects.
➢ Facilitates dynamic behaviour and late binding, enabling a more flexible and
reusable codebase.

Classes in Java:
A class in Java is a blueprint or template for creating objects. It defines the properties
(fields or attributes) and behaviours (methods or functions) that the objects of that class
will have. A class encapsulates data and the operations that can be performed on that
data. In Java, classes form the basic building blocks for creating reusable and modular
code. The key components of a class are:
• Fields/Attributes: These are the variables that hold the state of an object.
• Methods: These are functions defined inside a class that describe the behaviours or
actions that an object can perform.
• Constructor: A special method used to initialize objects when they are created.
Syntax of Class:
class ClassName {
// Fields (attributes)
int attribute1;
String attribute2;

// Constructor
ClassName(int attr1, String attr2) {
attribute1 = attr1;
attribute2 = attr2;
}

// Methods (behaviors)
void displayDetails() {
System.out.println("Attribute 1: " + attribute1);
System.out.println("Attribute 2: " + attribute2);
}
}
Example:
class Car {
// Fields/attributes
String make;
String model;
int year;

// Constructor to initialize the car object


Car(String carMake, String carModel, int carYear) {
make = carMake;
model = carModel;
year = carYear;
}
// Method to display car details
void displayCarDetails() {
System.out.println("Car Make: " + make);
System.out.println("Car Model: " + model);
System.out.println("Manufacturing Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car("Toyota", "Corolla", 2020);
myCar.displayCarDetails();
}
}

Constructors in Java:
A constructor in Java is a special type of method used to initialize objects. When an object
is created using the new keyword, the constructor is automatically called to set initial
values for the object's fields. Unlike regular methods, constructors:
• Have the same name as the class.
• Do not have a return type (not even void).
• Can be overloaded to create multiple versions of a constructor, each with different
parameters.
The different types of constructors are:
• Default Constructor: A constructor with no parameters. If no constructor is defined in
the class, Java provides a default constructor.
• Parameterized Constructor: A constructor that accepts parameters to initialize an
object with specific values at the time of creation.
Syntax of a Constructor:
class ClassName {
// Constructor with no parameters (default constructor)
ClassName() {
// Initialization code
}

// Constructor with parameters (parameterized constructor)


ClassName(int param1, String param2) {
// Initialization code
}
}
Exampl:
class Book {
// Fields (attributes)
String title;
String author;
int year;

// Default constructor
Book() {
title = "Unknown Title";
author = "Unknown Author";
year = 0;
}

// Parameterized constructor
Book(String bookTitle, String bookAuthor, int bookYear) {
title = bookTitle;
author = bookAuthor;
year = bookYear;
}

// Method to display book details


void displayBookDetails() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
Book book1 = new Book();
Book book2 = new Book("1984", "George Orwell", 1949);
book1.displayBookDetails();
System.out.println();
book2.displayBookDetails();
}
}

Argument Passing in Java: Java uses pass-by-value for argument passing, which means
that when a method is called, a copy of the argument's value is passed to the method.
There are two types of values that can be passed as arguments in Java:
• Primitive data types (e.g., int, char, float).
• Reference data types (e.g., objects, arrays).
Even though Java always passes by value, the behaviour is different for primitives and
references.

Passing Primitive Data Types:


When a primitive data type (such as int, float, or char) is passed to a method, the method
receives a copy of the value. Any modifications made to this value inside the method do
not affect the original value in the calling method.
Example:
public class Main {
public static void modifyValue(int num) {
num = 20; // Modifying the local copy of num
}

public static void main(String[] args) {


int x = 10;
modifyValue(x);
System.out.println(x); // Output: 10 (original value remains unchanged)
}
}

Passing Reference Data Types:


When a reference type (like an object or array) is passed to a method, the reference to the
object is passed by value. This means that the method receives a copy of the reference
(not the actual object), but since both the original reference and the copy point to the
same object in memory, changes to the object's attributes inside the method will affect
the original object.
Example:
class Person {
String name;
}

public class Main {


public static void modifyPerson(Person p) {
p.name = "Alice"; // Modifying the object's field
}

public static void main(String[] args) {


Person person = new Person();
person.name = "Bob";
modifyPerson(person);
System.out.println(person.name); // Output: Alice (the original object is modified)
}
}
Example Demonstrating the Difference b/w Passing Reference and Passing Primitive Data
Types:
class Example {
int value;
}

public class Main {


public static void modifyPrimitive(int num) {
num = 50;
}

public static void modifyObject(Example ex) {


ex.value = 50;
}

public static void main(String[] args) {


// Example with primitive data type
int x = 10;
modifyPrimitive(x);
System.out.println(x); // Output: 10 (unchanged)
// Example with reference data type (object)
Example example = new Example();
example.value = 10;
modifyObject(example);
System.out.println(example.value); // Output: 50 (modified)
}
}

Creating Our Own Java Class:


The syntax of a custom class is:
class ClassName {
// Field Attributes
// Methods
}
Example:
class Employee {
int id;
int salary;
String name;

public void printDetails() {


System.out.println("My id is " + id + " and my name is " + name);
}

public int getSalary() {


return salary;
}
}

public class Main {


public static void main(String[] args) {
System.out.println("This is our custom class");
Employee harry = new Employee(); // Instantiating a new Employee Object
Employee john = new Employee(); // Instantiating a new Employee Object

// Setting Attributes for Harry


harry.id = 12;
harry.salary = 34;
harry.name = "CodeWithHarry";

// Setting Attributes for John


john.id = 17;
john.salary = 12;
john.name = "John Khandelwal";

// Printing the Attributes


harry.printDetails();
john.printDetails();
int salary = john.getSalary();
System.out.println(salary);
}
}

Static Keyword in Java:


The static keyword in Java is used to indicate that a member (field, method, block, or
nested class) belongs to the class rather than to instances of the class. This means that
the static member can be accessed and used without creating an object of the class.
Uses of static Keyword:
• Static Variables (Class Variables): A static variable is shared among all instances of a
class. There is only one copy of the static variable, regardless of how many objects of
the class are created. This is useful for constants and data that should be shared
among all objects.
• Static Methods: A static method can be called without creating an instance of the class.
Static methods can access only static variables and static methods directly. This is
often used for utility or helper methods, such as mathematical operations
(Math.sqrt()), and methods that do not depend on instance variables.
• Static Blocks: A static block is used to initialize static variables. This block runs once
when the class is loaded into memory (before any objects are created). This is used
for complex static variable initialization.
• Static Nested Classes: A class can be defined as static inside another class. Static
nested classes do not have access to the non-static members of the outer class. It is
used when the nested class is logically associated with the outer class but does not
need access to its instance variables or methods.
Example of Static Variables and Methods:
class Calculator {
static int count = 0; // Static variable
// Constructor to increment static count
Calculator() {
count++;
}

// Static method
static void displayCount() {
System.out.println("Number of Calculator objects created: " + count);
}
}

public class Main {


public static void main(String[] args) {
Calculator calc1 = new Calculator();
Calculator calc2 = new Calculator();
// Accessing static method without creating an instance
Calculator.displayCount(); // Output: Number of Calculator objects created: 2
}
}
Example of Static Block:
class Example {
static int num;
// Static block to initialize static variable
static {
num = 100;
System.out.println("Static block executed. num = " + num);
}
}

public class Main {


public static void main(String[] args) {
// No object creation needed to execute static block
System.out.println("Value of num: " + Example.num); // Output: 100
}
}

Nested Classes:
In Java, nested classes are classes defined within another class. Nested classes can be
categorized into two types:
• Static Nested Class: A static nested class is a nested class that is declared with the
static keyword. It behaves like a static member of the outer class and can be accessed
without an instance of the outer class. Static nested classes cannot access non-static
members of the outer class directly.
Example:
class OuterClass {
int outerValue = 10;
// Static Nested Class
static class StaticNestedClass {
void display() {
System.out.println("Inside Static Nested Class");
}
}
}

public class Main {


public static void main(String[] args) {
// Accessing the Static Nested Class
OuterClass.StaticNestedClass nested = new OuterClass.StaticNestedClass();
nested.display();
}
}
• Inner Class: An inner class is a non-static nested class that has access to the non-static
members of the outer class, including private ones. It requires an instance of the outer
class to be created. Inner classes are often used when the nested class needs to work
closely with the instance of the outer class.
Example:
class OuterClass {
int outerValue = 20;
// Inner Class
class InnerClass {
void display() {
System.out.println("Outer Value: " + outerValue);
System.out.println("Inside Inner Class");
}
}
}

public class Main {


public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
}
}
Key Differences:
• Static Nested Class: Can be instantiated without an instance of the outer class, but
cannot directly access non-static members of the outer class.
• Inner Class: Requires an instance of the outer class, and has access to all members
(even private) of the outer class.

Method Overloading:
In Java, Method Overloading allows different methods to have the same name, but
different signatures where the signature can differ by the number of input parameters or
type of input parameters, or a mixture of both. Method overloading in Java is also known
as Compile-time Polymorphism, Static Polymorphism, or Early binding. In Method
overloading compared to the parent argument, the child argument will get the highest
priority.
Example:
public class Sum {
// Overloaded sum() --> This sum takes two int parameters
public int sum(int x, int y) {
return (x + y);
}

// Overloaded sum() --> This sum takes three int parameters


public int sum(int x, int y, int z) {
return (x + y + z);
}

// Overloaded sum() --> This sum takes two double parameters


public double sum(double x, double y) {
return (x + y);
}

public static void main(String args[])


{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
The different types of method overloading can be achieved by:
• Changing the Number of Parameters: In this approach, we define multiple methods
with the same name but different numbers of parameters.
Example:
class OverloadExample {
// Method with one parameter
void display(int a) {
System.out.println("Display method with one parameter: " + a);
}

// Overloaded method with two parameters


void display(int a, int b) {
System.out.println("Display method with two parameters: " + a + ", " + b);
}

public static void main(String[] args) {


OverloadExample obj = new OverloadExample();
obj.display(5); // Calls the method with one parameter
obj.display(5, 10); // Calls the method with two parameters
}
}
• Changing Data Types of the Arguments: In this approach, methods have the same
name but different parameter types.
Example:
class OverloadExample {
// Method with an integer parameter
void display(int a) {
System.out.println("Display method with int parameter: " + a);
}

// Overloaded method with a double parameter


void display(double a) {
System.out.println("Display method with double parameter: " + a);
}

public static void main(String[] args) {


OverloadExample obj = new OverloadExample();
obj.display(5); // Calls the method with int parameter
obj.display(5.5); // Calls the method with double parameter
}
}
• Changing the Order of the Parameters of Methods: In this approach, methods have the
same name and number of parameters, but the order of the parameters is different.
Example:
class OverloadExample {
// Method with int and double parameters
void display(int a, double b) {
System.out.println("Display method with int and double: " + a + ", " + b);
}

// Overloaded method with double and int parameters


void display(double a, int b) {
System.out.println("Display method with double and int: " + a + ", " + b);
}

public static void main(String[] args) {


OverloadExample obj = new OverloadExample();
obj.display(5, 10.5); // Calls the method with int and double parameters
obj.display(5.5, 10); // Calls the method with double and int parameters
}
}
Advantages of Method Overloading
• Method overloading improves the readability and reusability of the program.
• Method overloading reduces the complexity of the program.
• Using method overloading, programmers can perform a task efficiently and effectively.
• Using method overloading, it is possible to access methods performing related
functions with slightly different arguments and types.
• Objects of a class can also be initialized in different ways using the constructors.

Inheritance:
Inheritance in Java is a fundamental object-oriented programming concept that allows
one class (the subclass or derived class) to inherit properties and behaviors (fields and
methods) from another class (the superclass or base class). It helps in code reuse,
hierarchical classification, and the extension of existing code with new functionalities.
The key points of Inheritance are:
• Extends Keyword: In Java, inheritance is achieved using the extends keyword.
• Single Inheritance: Java supports single inheritance, meaning a class can inherit from
only one superclass. This avoids complexity and issues like the diamond problem seen
in multiple inheritance.
• IS-A Relationship: Inheritance establishes an "IS-A" relationship between the subclass
and superclass, meaning the subclass is a type of the superclass.
• Access to Superclass Members: Subclasses can access public and protected members
of the superclass, but private members are not accessible directly.
• Code Reusability: Inheritance enables the subclass to reuse code from the superclass,
which reduces redundancy and improves maintainability.
The different types of Inheritance in Java are:
• Single Inheritance: A subclass inherits from one superclass (as shown above).
• Multilevel Inheritance: A class inherits from a subclass, creating a chain (e.g., Animal
→ Dog → Puppy).
• Hierarchical Inheritance: Multiple classes inherit from a single superclass (e.g., both
Dog and Cat inherit from Animal).
Example of Constructor Calling without using super keyword:
// Class 1 --> Super class
class Base {
Base() {
System.out.println("Base Class Constructor Called");
}
}

// Class 2 --> Sub class


class Derived extends Base {
Derived() {
System.out.println("Derived Class Constructor Called");
}
}

class Main {
public static void main(String[] args) {
// Creating an object of sub class inside main() method
Derived d = new Derived();
// Note: Here first super class constructor will be called
// thereafter derived (sub class) constructor will be called
}
}
This will have the output as:
Base Class Constructor Called
Derived Class Constructor Called
Explanation: Here first superclass constructor will be called thereafter derived(sub-
class) constructor will be called because the constructor call is from top to bottom. And
yes, if there was any class that our Parent class is extending then the body of that class
will be executed thereafter landing up to derived classes.
But, if we want to call a parameterized constructor of the base class, then we can call it
using super (). The point to note is base class constructor call must be the first line in the
derived class constructor.
Example of Parameterized Constructor Calling using super keyword:
// Class 1 --> Super class
class Base {
int x;
// Constructor of super class
Base(int newx) {
x = newx;
}
}

// Class 2 --> Sub class


class Derived extends Base {
int y;
// Constructor of sub class
Derived(int newx, int newy) {
super(newx); // super keyword refers to super class
y = newy;
}

// Method of sub class


void Display() {
System.out.println("x = " + x + ", y = " + y);
}
}

public class Main {


public static void main(String[] args) {
// Creating object of sub class inside main() method
Derived d = new Derived(10, 20);
// Invoking method inside main() method
d.Display();
}
}

Key Rules for Method Overriding in Java


• Same Method Signature: The overriding method must have the same name, return
type, and parameter list as the method in the superclass.
• Access Modifier: The access level of the overriding method cannot be more restrictive
than the overridden method in the superclass. For instance, if the superclass method
is public, the overriding method in the subclass cannot be protected or private.
• Return Type: The return type of the overriding method must be the same as, or a
subtype of, the return type of the overridden method (known as covariant return
types).
• Cannot Override Static Methods: Static methods cannot be overridden as they belong
to the class, not instances. However, they can be redefined in the subclass, which is
known as method hiding.
• Cannot Override Final Methods: A method declared as final in the superclass cannot
be overridden by any subclass. This is because final methods are intended to remain
constant and unchangeable in behavior.
• Cannot Override Constructors: Constructors cannot be overridden as they are not
inherited by subclasses.
• Use of super Keyword: The super keyword can be used to invoke the superclass
version of an overridden method from the subclass if needed.
Abstract Class:
Java abstract class is a class that cannot be instantiated by itself, it needs to be subclassed
by another class to use its properties. An abstract class is declared using the “abstract”
keyword in its class definition. Abstract classes are a key component of OOP in Java,
allowing you to define incomplete classes that other classes can extend. It may have both
abstract and non-abstract methods (methods with bodies). An abstract is a Java modifier
applicable for classes and methods in Java but not for Variables.
The properties of Abstract Class are:
• An instance of an abstract class cannot be created. You cannot create an object of an
abstract class directly.
• Constructors are allowed.
• We can have an abstract class without any abstract method.
• There can be a final method in abstract class but any abstract method in class
(abstract class) cannot be declared as final or in simpler terms final method cannot
be abstract itself as it will yield an error: “Illegal combination of modifiers: abstract
and final”.
• We can define static methods in an abstract class.
• We can use the abstract keyword for declaring top-level classes (Outer class) as well
as inner classes as abstract.
• If a class contains at least one abstract method then compulsory should declare a class
as abstract.
• If the Child class is unable to provide implementation to all abstract methods of
the Parent class, then we should declare that Child class as abstract so that the next
level Child class should provide implementation to the remaining abstract method.
Example:
abstract class Animal {
// Abstract method (no implementation)
abstract void sound();

// Concrete method
public void sleep() {
System.out.println("Animal is sleeping");
}
}

class Dog extends Animal {


@Override void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
// Animal animal = new Animal(); // This will cause a compile-time error
Dog dog = new Dog();
dog.sound(); // Calls Dog's implementation of sound
dog.sleep(); // Calls the concrete method from Animal
}
}
Dynamic Method Dispatch:
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
• When an overridden method is called through a superclass reference, Java determines
which version(superclass/subclasses) of that method is to be executed based upon
the type of the object being referred to at the time the call occurs. Thus, this
determination is made at run time.
• At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
• A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Example of Dynamic Method Dispatch using hierarchical inheritance:
class A {
void m1() {
System.out.println("Inside A's m1 method");
}
}

class B extends A {
void m1() {
System.out.println("Inside B's m1 method");
}
}

class C extends A {
void m1() {
System.out.println("Inside C's m1 method");
}
}

class Main {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A ref; // obtain a reference of type A
ref = a; // ref refers to an A object
ref.m1(); // calling A's version of m1()
ref = b; // now ref refers to a B object
ref.m1(); // calling B's version of m1()
ref = c; // now ref refers to a C object
ref.m1(); // calling C's version of m1()
}
}

final Keyword:
The final method in Java is used as a non-access modifier applicable only to a variable,
a method, or a class. It is used to restrict a user in Java. The following are different
contexts where the final is used:

Characteristics of final keyword in Java:


In Java, the final keyword is used to indicate that a variable, method, or class cannot be
modified or extended. Here are some of its characteristics:
• Final variables: When a variable is declared with the final keyword, its value can’t be
changed, essentially, a constant. This also means that you must initialize a final
variable. If the final variable is a reference, this means that the variable cannot be re-
bound to reference another object, but the internal state of the object pointed by that
reference variable can be changed i.e. you can add or remove elements from the final
array or final collection. It is good practice to represent final variables in all uppercase,
using underscore to separate words.
Example of Final Variable:
public class Main {
public static void main(String[] args) {
final double PI = 3.14159; // Define a constant variable PI
System.out.println("Value of PI: " + PI);
}
}
Example of Reference of Final Variable:
class Main {
public static void main(String[] args) {
final StringBuilder sb = new StringBuilder("Geeks"); // Final reference variable
StringBuilder sb1 = new StringBuilder("Geeks"); // Final reference variable
// sb = sb1; // This cannot be done as we cannot reassign sb to point to a new
object
System.out.println(sb);
// changing internal state of object reference by final reference variable sb
sb.append("ForGeeks");
System.out.println(sb);
}
}
• Final methods: When a method is declared as final, it cannot be overridden by a
subclass. This is useful for methods that are part of a class’s public API and should not
be modified by subclasses.
Example:
class A {
final void m1() {
System.out.println("This is a final method.");
}
}

class B extends A {
void m1() {
// Compile-error! We can not override
System.out.println("Illegal!");
}
}
• Final classes: When a class is declared as final, it cannot be extended by a subclass i.e.,
it cannot be inherited. This is useful for classes that are intended to be used as is and
should not be modified or extended. There are two uses of a final class:
➢ One is definitely to prevent inheritance, as final classes cannot be extended. For
example, all Wrapper Classes like Integer, Float, etc. are final classes and cannot be
extended.
Example:
final class A {
// methods and fields
}
// The following class is illegal
class B extends A {
// COMPILE-ERROR! Can't subclass A
}
➢ The other use of final classes is to create an immutable class like the
predefined String class. One cannot make a class immutable without making it
final.

Packages:
Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces. Packages are used for:
• Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee.
• Making searching and usage of classes, interfaces, enumerations and annotations
easier
• Providing controlled access. Protected and default have package level access control.
A protected member is accessible by classes in the same package and its subclasses. A
default member (without any access specifier) is accessible by classes in the same
package only.
• Packages can be considered as data encapsulation (or data-hiding) as we can put
related classes into packages and simply write an import class from existing packages
and use it in our program.
There are two types of packages:
• Built-in Packages: These packages consist of a large number of classes which are a
part of Java API. Some of the commonly used built-in packages are:
➢ java.lang: Contains language support classes(e.g. classes which defines primitive
data types, math operations). This package is automatically imported.
➢ java.io: Contains classes for supporting input / output operations.
➢ java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support for Date / Time operations.
➢ java.applet: Contains classes for creating Applets.
➢ java.awt: Contain classes for implementing the components for graphical user
interfaces (like button, menus, etc).
➢ java.net: Contain classes for supporting networking operations.
• User-defined packages: These are the packages that are defined by the user. First, we
create a directory myPackage (name should be same as the name of the package).
Then create the MyClass inside the directory with the first statement being
the package names.
package myPackage;

public class MyClass {


public void getNames(String s) {
System.out.println(s);
}
}
Now we can use the MyClass class in our program.
import myPackage.MyClass;

public class PrintName {


public static void main(String args[]) {
String name = "GeeksforGeeks";
MyClass obj = new MyClass();
obj.getNames(name);
}
}

Package naming conventions:


Package names and directory structure are closely related. Packages are named in reverse
order of domain names, i.e., org.geeksforgeeks.practice. For example, in a college, the
recommended convention is college.tech.cse, college.tech.ee, college.art.history, etc.

Adding a class to a Package:


We can add more classes to a created package by using package name at the top of the
program and saving it in the package directory. We need a new java file to define a public
class, otherwise we can add the new class to an existing .java file and recompile it.

Subpackages:
Packages that are inside another package are the subpackages. These are not imported by
default; they have to be imported explicitly. Also, members of a subpackage have no access
privileges, i.e., they are considered as different package for protected and default access
specifiers.
Example:
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("Java");
System.out.println(list);
}
}

Access Modifiers / Access Control Mechanisms in Java:


Access modifiers help to restrict the scope of a class, constructor, variable, method, or
data member. It provides security, accessibility, etc to the user depending upon the access
modifier used with the element. There are four types of access modifiers available in Java:
• Default: When no access modifier is specified for a class, method, or data member – It
is said to be having the default access modifier by default. The data members, classes,
or methods that are not declared using any access modifiers i.e. having default access
modifiers are accessible only within the same package.
Example:
Program 1 having default access modifier:
package p1;

class Geek {
void display() {
System.out.println("Hello World!");
}
}
Program 2 using class from different package with default access modifier:
package p2;
import p1.*;

class GeekNew {
public static void main(String args[]) {
Geek obj = new Geek();
obj.display();
}
}
This program throws a compiler error as we are trying to access a class with default
access modifier from a different package.
• Private: The private access modifier is specified using the keyword private. The
methods or data members declared as private are accessible only within the class in
which they are declared. Any other class of the same package will not be able to
access these members. Top-level classes or interfaces cannot be declared as private
because private means “only visible within the enclosing class” and protected means
“only visible within the enclosing class and any subclasses”.
Example:
package p1;

class A {
private void display() {
System.out.println("GeeksforGeeks");
}
}

class B {
public static void main(String args[]) {
A obj = new A();
obj.display();
}
}
This program throws a compiler error as we are trying to access a class with private
access modifier from a different class.
• Protected: The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.
Example:
Program 1:
package p1;

public class A {
protected void display() {
System.out.println("GeeksforGeeks");
}
}
Program 2:
package p2;
import p1.*;

class B extends A {
public static void main(String args[]) {
B obj = new B();
obj.display();
}
}
This will give the output as “GeeksforGeeks”.
• Public: The public access modifier is specified using the keyword public. The public
access modifier has the widest scope among all other access modifiers. Classes,
methods, or data members that are declared as public are accessible from
everywhere in the program. There is no restriction on the scope of public data
members.
Example:
Program 1:
package p1;

public class A {
public void display() {
System.out.println("GeeksforGeeks");
}
}
Program 2:
package p2;
import p1.*;

class B {
public static void main(String args[]) {
A obj = new A();
obj.display();
}
}
This will give the output as “GeeksforGeeks”.
Interfaces in Java:
An interface is a blueprint of a class that contains abstract methods (methods without a
body) and static constants. Interfaces provide a way to achieve abstraction and multiple
inheritance in Java, as a class can implement multiple interfaces. It defines a set of
methods that a class must implement, without dictating how the methods should work.
This promotes a flexible and consistent way of defining functionalities, enabling different
classes to implement the same interface in diverse ways. The key features of interfaces
are:
• Abstract Methods: By default, all methods in an interface are abstract (no
implementation). Starting from Java 8, interfaces can also include default and static
methods with implementations.
• Multiple Inheritance: A class can implement multiple interfaces, allowing a form of
multiple inheritance.
• Constants: Variables in an interface are public, static, and final by default.
• Implementation: A class that implements an interface must provide concrete
implementations for all its methods. To implement the interface, we use the
implements keyword.
The uses of interfaces in Java are:
• It is used to achieve total abstraction.
• Since Java does not support multiple inheritances in the case of class, by using an
interface it can achieve multiple inheritances.
• Any class can extend only one class, but can implement multiple interfaces.
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction.
A class can extend another class, and similarly, an interface can extend another interface.
However, only a class can implement an interface, and the reverse (an interface
implementing a class) is not allowed.
Class Interface
A class is a blueprint of an object. An interface is a blueprint of a class.
In class, you can instantiate variables and In an interface, you must initialize
create an object. variables as they are final but you can’t
create an object.
A class can contain concrete (with The interface cannot contain concrete
implementation) methods (with implementation) methods.
The access specifiers used with classes In Interface only one specifier is used i.e.,
are private, protected, and public. public.
Example:
interface Drawable {
void draw(); // Abstract method
}

class Circle implements Drawable {


@Override
public void draw() {
System.out.println("Drawing a Circle");
}
}
class Rectangle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a Rectangle");
}
}

public class Main {


public static void main(String[] args) {
Drawable circle = new Circle();
Drawable rectangle = new Rectangle();
circle.draw(); // Output: Drawing a Circle
rectangle.draw(); // Output: Drawing a Rectangle
}
}

Multiple Inheritance in Java Using Interface:


In Java, multiple inheritance (a class inheriting from multiple classes) is not allowed
directly to avoid complexity and ambiguity. However, it can be achieved through
interfaces. A class can implement multiple interfaces, allowing it to inherit behaviors from
each interface.
Example:
interface Printable {
void print();
}

interface Showable {
void show();
}

class Document implements Printable, Showable {


@Override
public void print() {
System.out.println("Printing the document...");
}

@Override
public void show() {
System.out.println("Showing the document...");
}
}

public class Main {


public static void main(String[] args) {
Document doc = new Document();
doc.print(); // Output: Printing the document...
doc.show(); // Output: Showing the document...
}
}
Dynamic Method Lookup in Java:
Dynamic Method Lookup in Java is the process of determining the appropriate method
implementation to execute at runtime, based on the actual type of the object rather than
the reference type. This mechanism enables runtime polymorphism and is a key feature
of object-oriented programming in Java. In Java, when a method is invoked on an object,
the JVM uses dynamic method lookup to resolve which version of the method to call,
depending on the object's actual type (the type of the instance in memory). This is done
through a process called late binding or dynamic binding. The benefits of Dynamic
Method Lookup are:
• Polymorphism: Enables polymorphic behavior, allowing the same method to have
different implementations based on the object type.
• Flexibility: Allows for flexible and maintainable code, as new subclasses with different
method implementations can be introduced without changing existing code.
Example:
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing a circle");
}
}

class Rectangle extends Shape {


@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}

public class Main {


public static void main(String[] args) {
Shape myShape;
myShape = new Circle();
myShape.draw(); // Output: Drawing a circle
myShape = new Rectangle();
myShape.draw(); // Output: Drawing a rectangle
}
}

How Dynamic Method Lookup Works:


• When a method call is made on an object, the JVM looks at the actual type of the object,
not the reference type.
• It locates the most specific implementation of the method that matches the object type
in the inheritance hierarchy.
• The correct method is called at runtime, allowing Java to support polymorphic
behavior.

Java Exception Handling Mechanism:


Exception handling in Java is a powerful mechanism that allows a program to deal with
unexpected events (errors or exceptions) during runtime in a graceful and controlled
manner. Exceptions are problems that occur during the execution of a program (e.g.,
dividing by zero, accessing a null pointer, file not found, etc.). Without exception handling,
the program would terminate abruptly when an error occurs. The differences between
Error and Exception are as follows:
• Error: An Error indicates a serious problem that a reasonable application should not
try to catch.
• Exception: Exception indicates conditions that a reasonable application might try to
catch.

Flow of Exception Handling:


• Try block: The code that might cause an exception is placed in the try block.
• Catch block: If an exception occurs in the try block, it is caught by the corresponding
catch block, where the exception is handled.
• Finally block: This block is executed after the try and catch blocks, regardless of
whether an exception occurred or not.

Types of Exceptions:

There are two types of exceptions in Java:


• Built-in Exceptions: These are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of
important built-in exceptions in Java.
➢ ArithmeticException: It is thrown when an exceptional condition has occurred in
an arithmetic operation.
Example:
class ArithmeticException_Demo
{
public static void main(String args[]) {
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
➢ ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been
accessed with an illegal index. The index is either negative or greater than or equal
to the size of the array.
Example:
class ArrayIndexOutOfBoundsException_Demo {
public static void main(String args[]) {
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
➢ ClassNotFoundException: This Exception is raised when we try to access a class
whose definition is not found.
Example:
public class ClassNotFoundException_Demo {
public static void main(String[] args) {
try {
Class.forName("Class1"); // Class1 is not defined
}
catch (ClassNotFoundException e) {
System.out.println(e);
System.out.println("Class Not Found...");
}
}
}
➢ FileNotFoundException: This Exception is raised when a file is not accessible or
does not open.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

class FileNotFoundException_Demo {
public static void main(String args[]) {
try {
File file = new File("E://file.txt"); // Following file does not exist
FileReader fr = new FileReader(file);
}
catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
➢ IOException: It is thrown when an input-output operation failed or interrupted.
Example:
import java.io.FileInputStream;
import java.io.IOException;

public class IOException_Demo {


public static void main(String[] args) {
try {
// Attempt to open a file that doesn't exist
FileInputStream file = new FileInputStream("nonexistentfile.txt");
}
catch (IOException e) {
System.out.println("An IOException occurred: " + e.getMessage());
}
}
}
➢ InterruptedException: It is thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted.
➢ NoSuchFieldException: It is thrown when a class does not contain the field (or
variable) specified.
➢ NoSuchElementException: It is thrown when accessing an element that is not
found.
Example:
import java.util.*;

public class NoSuchElementException_Demo {


public static void main(String[] args) {
Set exampleleSet = new HashSet();
Hashtable exampleTable = new Hashtable();
exampleleSet.iterator().next(); // accessing Set
exampleTable.elements().nextElement(); // accessing Hashtable
// This throws a NoSuchElementException as there are
// no elements in Set and HashTable and we are
// trying to access elements
}
}
➢ NullPointerException: This exception is raised when referring to the members of
a null object. Null represents nothing.
Example:
class NullPointerException_Demo {
public static void main(String args[]) {
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
➢ NumberFormatException: This exception is raised when a method could not
convert a string into a numeric format.
Example:
class NumberFormatException_Demo {
public static void main(String args[]) {
try {
int num = Integer.parseInt("akki"); // "akki" is not a number
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
➢ RuntimeException: This represents an exception that occurs during runtime.
➢ StringIndexOutOfBoundsException: It is thrown by String class methods to
indicate that an index is either negative or greater than the size of the string.
Example:
class StringIndexOutOfBoundsException_Demo
{
public static void main(String args[])
{
try {
String a = "Hello"; // length is 5
char c = a.charAt(5); // accessing 6th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
➢ IllegalArgumentException: This exception will throw the error or error statement
when the method receives an argument which is not accurately fit to the given
relation or condition. It comes under the unchecked exception.
Example:
class IllegalArgumentException_Demo {
public static void print(int a) {
if (a >= 18)
System.out.println("Eligible for Voting");
else
throw new IllegalArgumentException("Not Eligible for Voting");
}

public static void main(String[] args) {


IllegalArgumentException_Demo.print(14);
}
}
➢ IllegalStateException: This exception will throw an error or error message when
the method is not accessed for the particular operation in the application. It comes
under the unchecked exception.
Example:
class IllegalStateException_Demo {
public static void print(int a, int b) {
System.out.println("Addition of Positive Integers: " + (a + b));
}

public static void main(String[] args) {


int n1 = 7, n2 = -3;
if (n1 >= 0 && n2 >= 0)
IllegalStateException_Demo.print(n1, n2);
else
throw new IllegalStateException("Either one or two numbers are not
Positive Integer");
}
}
The built-in exceptions in Java can be further classified into 2 types:
➢ Checked Exceptions: These exceptions are checked at compile-time (e.g.,
IOException, SQLException).
➢ Unchecked Exceptions: These exceptions are not checked at compile-time, but
rather at runtime (e.g., NullPointerException, ArithmeticException).
• User-Defined Exceptions: Sometimes, the built-in exceptions in Java are not able to
describe a certain situation. In such cases, the user can also create exceptions which
are called ‘user-defined Exceptions’. The following steps are followed for the creation
of a user-defined Exception:
➢ The user should create an exception class as a subclass of the Exception class. Since
all the exceptions are subclasses of the Exception class, the user should also make
his class a subclass of it. This is done as:
class MyException extends Exception
➢ User can write a default constructor in his/her own exception class.
MyException() {}
➢ User can also create a parameterized constructor with a string as a parameter.
We can use this to store exception details. We can call the superclass (Exception)
constructor from this and send the string there.
MyException(String str) {
super(str);
}
➢ To raise an exception of a user-defined type, we need to create an object to his
exception class and throw it using the throw clause.
MyException me = new MyException("Exception Details");
throw me;
Example:
class TooYoungException extends Exception {
public TooYoungException(String message) {
super(message); // Pass the message to the Exception class
}
}

public class SimpleCustomExceptionDemo {


public static void checkAge(int age) throws TooYoungException {
if (age < 18)
throw new TooYoungException("You are too young!");
else
System.out.println("You are old enough!");
}

public static void main(String[] args) {


try {
checkAge(15); // This will cause the exception to be thrown
}
catch (TooYoungException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
The benefits of Exception Handling are:
• Separation of Error-Handling Code: Helps in keeping the error-handling logic separate
from the normal logic.
• Graceful Recovery: Allows the program to recover from exceptions and continue its
execution.
• Readability and Maintainability: Makes the code easier to understand and maintain
by clearly separating error handling from regular code.

Java handles exception with these keywords:


• try and catch in Java: The try block contains a set of statements where an exception
can occur and the catch block is used to handle the uncertain condition of a try block.
A try block is always followed by a catch block, which handles the exception that
occurs in the associated try block.
Example:
public class Main {
public static void main(String[] args) {
try {
int[] numbers = { 1, 2, 3 };
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index is out of bounds!");
}
}
}
The output will be “Error: Array index is out of bounds!”.
• throw in Java: The throw keyword is used to transfer control from the try block to the
catch block.
Example:
public class Main {
public static void main(String[] args) {
checkAge(15);
}

public static void checkAge(int age) {


if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
} else {
System.out.println("Access granted - You are old enough.");
}
}
}
The output will be “Exception in thread "main" java.lang.IllegalArgumentException:
Age must be 18 or older.”
• throws in Java: The throws keyword is used for exception handling without try & catch
block. It specifies the exceptions that a method can throw to the caller and does not
handle itself.
Example:
public class Main {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static int divide(int a, int b) throws ArithmeticException {


if (b == 0) {
throw new ArithmeticException("Cannot divide by zero.");
}
return a / b;
}
}
The output will be “Error: Cannot divide by zero.”
• finally in Java: It is executed after the catch block. We use it to put some common code
to be executed irrespective of whether an exception has occurred or not when there
are multiple catch blocks.
Example:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 2;
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
finally {
System.out.println("This block is always executed.");
}
}
}

Strings in Java:
Strings are the type of objects that can store the character of values and in Java, every
character is stored in 16 bits i.e. using UTF (Unicode Transformation Format) 16-bit
encoding. A string acts the same as an array of characters in Java. There are two ways to
create a string in Java:
• String Literal: To make Java more memory efficient because no new objects are
created if it exists already in the string constant pool, string literal is used. Example:
String demostring = "GeeksforGeeks";
• Using new Keyword: In such a case, JVM will create a new string object in normal (non-
pool) heap memory and the literal “GeeksforGeeks” will be placed in the string
constant pool. The variable demostring will refer to the object in the heap (non-pool).
Example:
String demostring = new String("GeeksforGeeks");
CharSequence Interface is used for representing the sequence of Characters in Java.
Classes that are implemented using the CharSequence interface are mentioned below and
these provides much of functionality like substring, lastoccurence, firstoccurence,
concatenate, toupper, tolower etc.
• String: It is an immutable class which means a constant and cannot be changed once
created and if wish to change, we need to create an new object and even the
functionality it provides like toupper, tolower, etc all these return a new object , its not
modify the original object. It is automatically thread safe.
Example:
public class Main {
public static void main(String args[]) {
String s = "Hello";
String str = new String("World!");
System.out.print(s + " ");
System.out.print(str);
}
}
• StringBuffer: StringBuffer is a peer class of String, it is mutable in nature and it is
thread safe class, we can use it when we have multi-threaded environment and shared
object of string buffer i.e., used by multiple thread. As it is thread safe so there is extra
overhead, so it is mainly used for multithreaded program.
Example:
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println("After append: " + sb); // Output: Hello World
sb.insert(5, ",");
System.out.println("After insert: " + sb); // Output: Hello, World
sb.reverse();
System.out.println("After reverse: " + sb); // Output: dlroW ,olleH
sb.delete(0, 5);
System.out.println("After delete: " + sb); // Output: ,olleH
sb.reverse();
System.out.println("Final output: " + sb); // Output: Hello,
}
}
• StringBuilder: It represents an alternative to String and StringBuffer Class, as it
creates a mutable sequence of characters and it is not thread safe. It is used only within
the thread, so there is no extra overhead, so it is mainly used for single threaded
program.
Example:
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println("After append: " + sb); // Output: Hello World
sb.insert(5, ",");
System.out.println("After insert: " + sb); // Output: Hello, World
sb.reverse();
System.out.println("After reverse: " + sb); // Output: dlroW ,olleH
sb.delete(0, 5);
System.out.println("After delete: " + sb); // Output: ,olleH
sb.reverse();
System.out.println("Final output: " + sb); // Output: Hello,
}
}
• StringTokenizer: It is used to break a string into tokens (substrings) based on
specified delimiters. It’s a simple way to split a string without using regular
expressions.
Example:
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
String text = "Java is fun to learn";
// Create a StringTokenizer with space as the default delimiter
StringTokenizer tokenizer = new StringTokenizer(text);
// Print each token
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
• StringJoiner: It is used to concatenate a sequence of strings with a specified delimiter,
and optionally a prefix and suffix. It’s useful for building formatted strings in a clean
way.
Example:
import java.util.StringJoiner;
public class Main {
public static void main(String[] args) {
// Create a StringJoiner with comma as the delimiter, [ as prefix, and ] as suffix
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("Apple");
joiner.add("Banana");
joiner.add("Cherry");
System.out.println(joiner.toString()); // Output: [Apple, Banana, Cherry]
}
}

String Constructors in Java:


• String(byte[] byte_arr): Construct a new String by decoding the byte array. It uses the
platform’s default character set for decoding.
• String(byte[] byte_arr, Charset char_set): Construct a new String by decoding the byte
array. It uses the char_set for decoding.
• String(byte[] byte_arr, int start_index, int length): Construct a new string from
the bytes array depending on the start_index(Starting location) and length(number
of characters from starting location).
• String(byte[] byte_arr, int start_index, int length, Charset char_set): Construct a new
string from the bytes array depending on the start_index (Starting
location) and length (number of characters from starting location). Uses char_set for
decoding.
• String(char[] char_arr): Allocates a new String from the given Character array.
• String(char[] char_array, int start_index, int count): Allocates a String from a
given character array but choose count characters from the start_index.
• String(int[] uni_code_points, int offset, int count): Allocates a String from
a uni_code_array but choose count characters from the start_index.
• String(StringBuffer s_buffer): Allocates a new string from the string in s_buffer.
• String(StringBuilder s_builder): Allocates a new string from the string in s_builder.
Example:
import java.nio.charset.Charset;

class Main {
static byte[] b_arr = {71, 101, 101, 107, 115};
static Charset cs = Charset.defaultCharset();
static char[] char_arr = {'G', 'e', 'e', 'k', 's'};
static int[] uni_code = {71, 101, 101, 107, 115};
static StringBuffer s_buffer = new StringBuffer("Geeks");
static StringBuilder s_builder = new StringBuilder("Geeks");

public static void main(String[] args) {


// Method 1
String s1 = new String(b_arr);
System.out.println("Method 1: " + s1);
System.out.println();

// Method 2
String s2 = new String(b_arr, cs);
System.out.println("Method 2: " + s2);
System.out.println();

// This is alternative way for Method 2


String s3 = new String(b_arr, Charset.forName("US-ASCII"));
System.out.println("Method 2 Alternative: " + s3);
System.out.println();

// Method 3
String s4 = new String(b_arr, 1, 3);
System.out.println("Method 3: " + s4);
System.out.println();

// Method 4
String s5 = new String(b_arr, 1, 3, cs);
System.out.println("Method 4: " + s5);
System.out.println();

// This is alternative way for Method 4


String s6 = new String(b_arr, 1, 4, Charset.forName("US-ASCII"));
System.out.println("Method 4 Alternative: " + s6);
System.out.println();

// Method 5
String s7 = new String(char_arr);
System.out.println("Method 5: " + s7);
System.out.println();

// Method 6
String s8 = new String(char_arr, 1, 3);
System.out.println("Method 6: " + s8);
System.out.println();

// Method 7
String s9 = new String(uni_code, 1, 3);
System.out.println("Method 7: " + s9);
System.out.println();

// Method 8
String s10 = new String(s_buffer);
System.out.println("Method 8: " + s10);
System.out.println();

// Method 9
String s11 = s_builder.toString();
System.out.println("Method 9: " + s11);
System.out.println();
}
}
String Operations in Java:
• Concatenation (+ operator or concat method): Concatenation joins two strings
together.
Example:
String greeting = "Hello, " + "World!";
System.out.println(greeting); // Output: Hello, World!
String str = "Java";
str = str.concat(" Programming");
System.out.println(str); // Output: Java Programming
• Finding Length (length method): The length method returns the number of characters
in a string.
Example:
String str = "Hello";
System.out.println(str.length()); // Output: 5
• Accessing Characters (charAt method): You can access a specific character at a given
index using charAt.
Example:
String str = "Java";
System.out.println(str.charAt(1)); // Output: 'a'
• Converting to Upper and Lower Case (toUpperCase and toLowerCase methods):
These methods change the case of characters in a string.
Example:
String str = "Java Programming";
System.out.println(str.toUpperCase()); // Output: JAVA PROGRAMMING
System.out.println(str.toLowerCase()); // Output: java programming
• Trimming Whitespaces (trim method): The trim method removes leading and trailing
whitespaces.
Example:
String str = " Hello World! ";
System.out.println(str.trim()); // Output: Hello World!
• Substring (substring method): The substring method extracts part of a string, starting
from a specific index.
Example:
String str = "Hello World!";
System.out.println(str.substring(6)); // Output: World!
System.out.println(str.substring(0, 5)); // Output: Hello
• Modifying a String or Replacing Characters (replace, replaceAll and replaceFirst
method): This method replaces all occurrences of a specified character or substring.
replaceFirst() method replaces the first occurrence of a substring.
Example:
String str = "banana";
System.out.println(str.replace('a', 'o')); // Output: bonono
System.out.println(str.replace("ban", "fan")); // Output: fanana
String str = "apple banana apple";
System.out.println(str.replaceFirst("apple", "orange")); // Output: orange banana
apple
• Checking Equality (equals, equalsIgnoreCase and compare methods): The equals
method checks if two strings are exactly the same, considering case, while
equalsIgnoreCase ignores case. compare method compares two strings
lexicographically (dictionary order). Returns 0 if they are equal, a positive number if
the first string is greater, and a negative number if it’s lesser.
Example:
String str1 = "Java";
String str2 = "java";
System.out.println(str1.equals(str2)); // Output: false
System.out.println(str1.equalsIgnoreCase(str2)); // Output: true
String str1 = "Apple";
String str2 = "Banana";
System.out.println(str1.compareTo(str2)); // Output: negative value (str1 < str2)
• Finding the Index of a Character or Substring (indexOf, lastIndexOf and contains
method): indexOf method returns the index of the first occurrence of a specified
character or substring. lastIndexOf() method returns the index of the last occurrence
of a specified character or substring. contains method checks if a string contains a
particular substring.
Example:
String str = "Hello World";
System.out.println(str.indexOf("o")); // Output: 4
System.out.println(str.indexOf("World")); // Output: 6
System.out.println(str.indexOf("Java")); // Output: -1 (not found)
String str = "Hello World";
System.out.println(str.lastIndexOf("o")); // Output: 7
String str = "Learning Java";
System.out.println(str.contains("Java")); // Output: true
• Splitting a String (split method): The split method divides a string based on a specified
delimiter and returns an array of substrings.
Example:
String str = "apple,banana,grape";
String[] fruits = str.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
/* Output:
apple
banana
grape */
• toString() Method: The toString() method in Java is used to convert an object to its
string representation. Every class in Java inherits the toString() method from the
Object class, and it’s common to override this method for custom objects to provide
meaningful output.
Example:
class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}

Person person = new Person("Alice", 25);


System.out.println(person.toString()); // Output: Person{name='Alice', age=25}
• valueOf() Method: String.valueOf() is a static method used to convert other data types
(like integers, floats, characters, booleans, etc.) into their string representations. It can
also be used to handle null values gracefully, as it converts null to the string "null"
rather than causing a NullPointerException.
Example:
int number = 100;
String strNumber = String.valueOf(number);
System.out.println(strNumber); // Output: "100"
System.out.println(strNumber + 20); // Output: "10020" (string concatenation)
boolean flag = true;
String strFlag = String.valueOf(flag);
System.out.println(strFlag); // Output: "true"
String str = String.valueOf(null); // Output: "null"
System.out.println(str);

StringBuffer Operations in Java:


• append(): This operation adds text or other types of data to the end of the existing
StringBuffer content.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World!");
System.out.println(sb); // Output: Hello World!
• length(): This operation returns the number of characters currently in the
StringBuffer.
Example:
StringBuffer sb = new StringBuffer("Hello");
System.out.println(sb.length()); // Output: 5
• capacity(): This operation returns the current capacity (allocated size) of the
StringBuffer. This is different from length, as capacity can be greater than the current
length.
Example:
StringBuffer sb = new StringBuffer("Hello");
System.out.println(sb.capacity()); // Output: Default capacity is 16 + length of
string (21 here)
• charAt(): This operation returns the character at a specific index.
Example:
StringBuffer sb = new StringBuffer("Hello");
System.out.println(sb.charAt(1)); // Output: 'e'
• delete(): This operation removes a sequence of characters from the StringBuffer
starting from a specified index up to, but not including, an end index.
Example:
StringBuffer sb = new StringBuffer("Hello World");
sb.delete(5, 11);
System.out.println(sb); // Output: Hello
• deleteCharAt(): This operation deletes a character at the specified index.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.deleteCharAt(4);
System.out.println(sb); // Output: Hell
• ensureCapacity(): This operation ensures that the capacity is at least equal to the
specified minimum. If the current capacity is less than the specified minimum, it
increases it.
Example:
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // Output: 16 (default capacity)
sb.ensureCapacity(50);
System.out.println(sb.capacity()); // Output: 50
• insert(): This operation inserts text or other types of data at a specified index in the
StringBuffer.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World");
System.out.println(sb); // Output: Hello World
• reverse(): This operation reverses the characters in the StringBuffer.
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH
• replace(): This operation replaces characters from a start index to an end index with
the specified string.
Example:
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb); // Output: Hello Java

Java IO Stream:
Java I/O (Input and Output) is used to process the input and produce the output. Java uses
the concept of a stream to make I/O operations fast. The Java IO API is placed in the java.io
package. This package comprises almost all classes that a user requires to perform input
and output (I/O) in Java. The Java IO package focuses on input and output to files, network
streams, etc. However, the Java IO package does not include classes to open network
sockets which are essential for network communication. The java.io package generally
involves reading basic information from a source and writing it to a destination.
In the programming world, a stream can be described as a series of data. It is known as a
stream because it is similar to a stream of water that continues to flow. Java IO streams
are flows of data that a user can either read from or write to. Like an array, a stream has
no concept of indexing the read or write data. A stream is attached to a data origin or a
data target.
Java Streams uses two primary streams to read and write the data. These are:
• InputStream: An input stream is used to read the data from a source in a Java
application. Data can be anything, a file, an array, a peripheral device, or a socket. In
Java, the class java.io.InputStream is the base class for all Java IO input streams.

The methods of Java IO InputStreams are:


➢ read(): The read() method is used to read the next byte of data from the Input
Stream. The value byte is passed on a scale of 0 to 255. If no byte is free because
the end of the stream has arrived, the value -1 is passed.
➢ mark(int arg): The mark(int arg) method is used to mark the current position of
the input stream. It sets read to limit, i.e., the maximum number of bytes that can
be read before the mark position becomes invalid.
➢ reset(): The reset() method is invoked by mark() method. It changes the position
of the input stream back to the marked position.
➢ close(): The close() method is used to close the input stream and releases system
resources associated with this stream to Garbage Collector.
➢ read(byte [] arg): The read(byte [] arg) method is used to read the number of bytes
of arg.length from the input stream to the buffer array arg. The bytes read
by read() method are returned as an int. If the length is zero, then no bytes are
read, and 0 is returned unless there is an effort to read at least one byte.
➢ skip(long arg): The skip(long arg) method is used to skip and discard arg bytes in
the input stream.
➢ markSupported(): The markSupported() method tests if the inputStream
supports the mark and reset methods. The markSupported method of Java IO
InputStream yields false by default.
Example:
import java.io.*;

public class InputStreamExample {


public static void main(String[] args) throws Exception {
InputStream input = null;
try {
input = new FileInputStream("Text.txt");
// read() method - reading and printing Characters one by one
System.out.println("Char - " + (char) input.read());
System.out.println("Char - " + (char) input.read());
input.mark(0); // mark() - read limiting the 'input' input stream
input.skip(1); // skip() - it results in skipping of 'e' in Ge'e'ksforGeeks
System.out.println("skip() method comes to play");
System.out.println("mark() method comes to play");
System.out.println("Char - " + (char) input.read());
System.out.println("Char - " + (char) input.read());
boolean check = input.markSupported();
if (input.markSupported()) {
input.reset(); // reset() method - repositioning the stream to marked
positions
System.out.println("reset() invoked");
System.out.println("Char - " + (char) input.read());
System.out.println("Char - " + (char) input.read());
} else
System.out.println("reset() method not supported.");
System.out.println("input.markSupported() supported reset() - " + check);

} catch (Exception e) {
e.printStackTrace(); // in case of I/O error
} finally {
if (input != null) {
input.close(); // close() - closing the file and releasing resources
}
}
}
}
Output:
• OutputStream: An output stream is used to write data (a file, an array, a peripheral
device, or a socket) to a destination. In Java, the class java.io.OutputStream is the base
class for all Java IO output streams.

The methods of Java IO OutputStreams are:


➢ flush(): The flush() method is used for flushing the outputStream This method
forces the buffered output bytes to be written out.
➢ close(): The close() method is used to close the outputStream and to release the
system resources affiliated with the stream.
➢ write(int b): The write(int b) method is used to write the specified byte to the
outputStream.
➢ write(byte [] b): The write(byte [] b) method is used to write bytes of length
b.length from the specified byte array to the outputStream.
Example:
import java.io.*;

public class OutputStreamExample {


public static void main(String args[]) throws Exception {
OutputStream output = new FileOutputStream("file.txt");
byte b[] = { 65, 66, 67, 68, 69, 70 };
output.write(b); // illustrating write(byte[] b) method
output.flush(); // illustrating flush() method
// illustrating write(int b) method
for (int i = 71; i < 75; i++) {
output.write(i);
}
output.flush();
output.close(); // close the stream
}
}
Output: ABCDEFGHIJ
The Streams in Java IO are of the following types:

• Byte Streams: Java byte streams are the ones that are used to implement the input and
output of 8-bit bytes. Several classes are affiliated with byte streams in Java. However,
the most generally practiced classes are FileInputStream and FileOutputStream. The
different classes of Byte Streams are:
➢ InputStream: This is an abstract class that defines stream input.
➢ FileInputStream: This is used to reads from a file.
➢ DataInputStream: It contains a method for reading java standard datatypes.
➢ BufferedInputStream: It is used for Buffered Input Stream.
➢ PrintStream: This class comprises the commonly used print() and println()
methods.
➢ OutputStream: This is an abstract class that describes stream output.
➢ FileOutputStream: This class is used to write to a file.
➢ DataOutputStream: This contains a method for writing java standard data types.
➢ BufferedOutputStream: This is used for Buffered Output Stream.
• Character Streams: Java Character streams are the ones that are used to implement
the input and output for 16-bit Unicode. Several classes are associated with character
streams in Java, but the most commonly used classes are FileReader and FileWriter.
Internally, the FileReader class uses FileInputStream and the FileWriter class uses
FileOutputStream. Nevertheless, the significant contrast is that FileReader and
FileWriter read and write two bytes, respectively. The different classes of Character
Streams are:
➢ Reader: This is an abstract class that defines character stream input.
➢ Writer: This is an abstract class that defines character stream output.
➢ FileReader: This is an input stream that reads from the file.
➢ FileWriter: This is used to the output stream that writes to the file.
➢ BufferedReader: It is used to handle buffered input streams.
➢ BufferedWriter: This is used to handle buffered output streams.
➢ InputStreamReader: This input stream is used to translate the byte to the
character.
➢ OutputStreamReader: This output stream is used to translate characters to bytes.
➢ PrintWriter: This contains the most used print() and println() methods.
• Standard Streams – All the programming languages assist standard I/O, where the
user’s program can take input from a keyboard and then produce an output on the
computer screen. Just like C and C++ have three standard streams, STDIN, STDOUT,
and STDERR, Java also provides the following three standard streams:

➢ Standard Input – The Standard Input class is used to accept input data to the user’s
program. Usually, a keyboard is utilized as a standard input stream and described
as System.in.
➢ Standard Output – This class is used to output the data generated by the user’s
program, and usually, a computer screen is used for standard output stream and
described as System.out.
➢ Standard Error – The Standard error class is used to output the data having an
error that is generated by the user’s program. Normally, a computer screen is
utilized for standard error stream and described as System.err.
Example:
import java.util.*;

public class StandardStreamsExample {


public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of A : ");
int a = sc.nextInt();
System.out.println("Value of A is : " + a);
System.out.print("Enter the value of B : ");
int b = sc.nextInt();
System.out.println("Value of B is : " + b);
System.out.println("Result of division A/B is : " + (a / b));
sc.close();
} catch (Exception ex) {
System.err.print("Exception message : " + ex.getMessage());
}
}
}
Output:

Java IO File:
The Java IO File class is Java’s description of a file or pathname of a directory. Since file
and directory names have distinctive arrangements on various platforms, a naive string
is not sufficient to describe them. The File class comprises various approaches for
operating with the pathname, removing and renaming files, generating new directories,
arranging the contents of a list, and managing numerous general properties of files and
directories. The characteristics of Java IO File are:
• Java IO File is an ideal illustration of files and pathnames of directories.
• A pathname, whether general or in string pattern, can be either fixed or contingent.
The origin of an ideal pathname may be accomplished by invoking the getParent()
process of the Java IO File class.
• First of all, a user should build an object of the File class by giving it the filename or
directory name. A file method may execute limitations to specific actions on the real
file-system object, such as reading and writing. These constraints are collectively
identified as access permissions.
• Instances of the File class are immutable. That is, once created, the abstract pathname
denoted by a File object will nevermore change.
The methods of Java IO File are:
• canExecute(): This method is used to examine whether the application can
accomplish the file expressed by the abstract pathname.
• canWrite(): This method is used to test whether the application can transform the file
expressed by the abstract pathname or not.
• canRead(): This method is used to examine whether the application can read the given
file signified by the abstract pathname.
• getName(): This method is used to return the file or directory name denoted by the
abstract pathname.
• getPath(): This method is used to convert the abstract pathname into a pathname
string.
• getAbsolutePath(): This method is used to return the absolute pathname string of the
abstract pathname.
• getParent(): This method is used to return the pathname string of the abstract
pathname’s parent.
• exists(): This method is used to test whether the file or directory expressed by the
abstract pathname exists or not.
• length(): This method is used to return the length of the file denoted by the abstract
pathname.
• isDirectory(): This method is used to test whether the file denoted by the pathname
is a directory.
Example:
import java.io.File;

public class FileExample {


public static void main(String[] args) {
String fname = args[0];
File f = new File(fname);
System.out.println("File name - " + f.getName());
System.out.println("Path - " + f.getPath());
System.out.println("Absolute path - " + f.getAbsolutePath());
System.out.println("Parent - " + f.getParent());
System.out.println("Exists - " + f.exists());

if (f.exists()) {
System.out.println("Is writable - " + f.canWrite());
System.out.println("Is readable - " + f.canRead());
System.out.println("Is a directory - " + f.isDirectory());
System.out.println("File Size in bytes " + f.length());
}
}
}
Output:
Collection Overview in Java Utility Package:
Java's java.util package provides a comprehensive framework for handling collections of
objects. The Java Collections Framework is a set of interfaces and classes designed to
make it easy to manage groups of objects by offering functionality for data storage,
retrieval, manipulation, and sorting. The key interfaces in Java Collections Framework
are:
• Collection: It is the root interface in the collections hierarchy. It represents a group of
objects known as elements. Commonly used sub interfaces include List, Set, and
Queue.
• List: It is an ordered collection (also known as a sequence) that allows duplicate
elements. Elements are accessed by their integer index. Popular implementations are
ArrayList, LinkedList, Vector.
• Set: It is a collection that doesn’t allow duplicate elements. It models the mathematical
set abstraction. Popular implementations are HashSet, LinkedHashSet, TreeSet.
• Queue: It is designed to hold elements before processing, following FIFO (first-in-first-
out) order. Commonly used implementations are PriorityQueue, LinkedList (used as
a queue).
• Map: It is not technically a part of Collection. It represents a collection of key-value
pairs. Each key maps to exactly one value, with unique keys. Popular implementations
are HashMap, LinkedHashMap, TreeMap, Hashtable.
The Java Collections Framework provides several ready-made implementations for each
interface. They are:
• ArrayList (Implements List): It is a resizable array that allows duplicate elements and
maintains insertion order. It provides fast random access but slower at insertion and
deletion compared to LinkedList.
Example:
import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
System.out.println("ArrayList: " + list);
}
}
• HashSet (Implements Set): It stores elements in an unordered way and does not allow
duplicates. It provides constant-time performance for basic operations (add, remove,
contains).
Example:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate element, will be ignored
System.out.println("HashSet: " + set);
}
}
• LinkedList (Implements List and Queue): It is a doubly-linked list that can be used as
a List, Deque, or Queue. It is efficient for inserting and deleting elements at both ends.
Example:
import java.util.LinkedList;

public class LinkedListExample {


public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("Apple");
list.addFirst("Banana");
list.addLast("Orange");
System.out.println("LinkedList: " + list);
}
}
• HashMap (Implements Map): It stores key-value pairs with unique keys. It provides
constant-time performance for basic operations and doesn’t maintain any specific
order.
Example:
import java.util.HashMap;

public class HashMapExample {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
System.out.println("HashMap: " + map);
}
}
The advantages of using Java Collections Framework are:
• Reduces programming effort by providing data structures and algorithms that are
highly optimized.
• Increases performance by offering high-quality and efficient implementations.
• Improves code quality by using standard and reusable interfaces.
• Increases flexibility by allowing different implementations of interfaces to be
swapped without code changes.
• Enhances interoperability by adhering to common interfaces and patterns across
various types of collections.

Collection Utility Methods:


The java.util.Collections class provides several static utility methods for working with
collections, such as:
• sort(): Sorts a List in ascending order.
• reverse(): Reverses the order of elements in a List.
• max() and min(): Finds the maximum and minimum element.
• shuffle(): Randomly shuffles elements in a List.
Example:
import java.util.ArrayList;
import java.util.Collections;

public class CollectionsUtilityExample {


public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(5);
list.add(1);
list.add(3);
list.add(9);
Collections.sort(list);
System.out.println("Sorted List: " + list);
int max = Collections.max(list);
System.out.println("Max element: " + max);
Collections.reverse(list);
System.out.println("Reversed List: " + list);
}
}

Collection Interfaces in Java:


The Java Collections Framework (JCF) is a hierarchy of interfaces and classes that
provides a standardized way to manage groups of objects in Java. At the core of this
framework are a set of collection interfaces that define the operations and behavior of
different types of collections.
• Collection Interface: The Collection interface is the root of the hierarchy. It defines the
common behavior of all collection types, including methods for adding, removing, and
inspecting elements. The Collection interface has several sub interfaces for specific
collection types. The key methods are:
➢ boolean add(E e): Adds an element to the collection.
➢ boolean remove(Object o): Removes a single instance of the specified element.
➢ boolean contains(Object o): Checks if the collection contains the specified
element.
➢ int size(): Returns the number of elements in the collection.
➢ Iterator<E> iterator(): Returns an iterator to traverse the collection.
• List Interface: The List interface extends Collection and represents an ordered
collection that allows duplicate elements. Elements can be accessed by their index,
and the order is preserved. The characteristics are:
➢ Allows duplicate elements.
➢ Maintains insertion order.
➢ Provides positional access to elements.
Common implementations are ArrayList, LinkedList and Vector
Example:
import java.util.ArrayList;

public class ListExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple"); // Allows duplicates
System.out.println("List: " + list);
}
}
• Set Interface: The Set interface extends Collection and represents a collection that
does not allow duplicate elements. It models the mathematical set abstraction. The
characteristics are:
➢ No duplicate elements.
➢ No guaranteed order (unless using LinkedHashSet or TreeSet).
Common implementations are HashSet, LinkedHashSet and TreeSet.
Example:
import java.util.HashSet;

public class SetExample {


public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate, will be ignored
System.out.println("Set: " + set);
}
}
• Queue Interface: The Queue interface extends Collection and represents a collection
designed to hold elements before processing. It typically follows a FIFO (first-in-first-
out) order. The characteristics are:
➢ Allows duplicate elements.
➢ Operations: offer(), poll(), peek().
Common implementations are LinkedList (as a queue) and PriorityQueue.
Example:
import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {


public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.offer("Apple");
queue.offer("Banana");
System.out.println("Head of queue: " + queue.peek());
queue.poll(); // Removes "Apple"
System.out.println("Queue after poll: " + queue);
}
}
• Deque Interface: The Deque (Double-Ended Queue) interface extends Queue and
represents a collection that supports insertion and removal at both ends. The
characteristics are:
➢ Supports LIFO (Last-In-First-Out) and FIFO (First-In-First-Out) operations.
➢ Commonly used for stacks and queues.
Common implementations are LinkedList and ArrayDeque.
Example:
import java.util.ArrayDeque;

public class DequeExample {


public static void main(String[] args) {
ArrayDeque<String> deque = new ArrayDeque<>();
deque.addFirst("Apple");
deque.addLast("Banana");
System.out.println("Deque: " + deque);
deque.removeFirst();
System.out.println("Deque after removing first: " + deque);
}
}
• Map Interface: Though not part of the Collection interface hierarchy, the Map interface
is a key part of the Java Collections Framework. It represents a collection of key-value
pairs, where each key maps to exactly one value. The characteristics are:
➢ Keys are unique; values can be duplicate.
➢ Not ordered (unless using LinkedHashMap or TreeMap).
Common implementations are HashMap, LinkedHashMap, TreeMap and Hashtable.
Example:
import java.util.HashMap;

public class MapExample {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Apple", 3); // Overwrites previous value for "Apple"
System.out.println("Map: " + map);
}
}

Collection Classes in Java:


The ArrayList and LinkedList classes are part of the Java Collections Framework, and both
implement the List interface, providing ordered collections of elements. However, they
differ in their internal implementations and performance characteristics.
• ArrayList: ArrayList is a resizable array implementation of the List interface. It is best
suited for frequent random access but less efficient for insertions and deletions in the
middle of the list. The key features are:
➢ Dynamic resizing: Automatically increases its capacity when elements exceed the
current size.
➢ Allows duplicates: Permits duplicate elements and maintains the order of
insertion.
➢ Fast random access: Elements can be accessed in constant time using an index.
Access time of ArrayList is O(1) and insertion/deletion time is O(n) (due to shifting
of elements).
Example:
import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<String> students = new ArrayList<>();
students.add("Alice");
students.add("Bob");
students.add("Charlie");
students.add("Alice"); // Allows duplicate
System.out.println("Student List: " + students);
System.out.println("First Student: " + students.get(0));
students.remove(1);
System.out.println("After Removal: " + students);
System.out.println("Contains 'Bob'? " + students.contains("Bob"));
}
}
Output:
Student List: [Alice, Bob, Charlie, Alice]
First Student: Alice
After Removal: [Alice, Charlie, Alice]
Contains 'Bob'? false
• LinkedList: LinkedList is a doubly-linked list implementation of the List and Deque
interfaces. It is best suited for scenarios where frequent insertions and deletions are
needed. The key features are:
➢ Doubly linked: Each node contains references to both the previous and next nodes.
➢ Allows duplicates: Permits duplicate elements and maintains the order of
insertion.
➢ Efficient for sequential access: Better performance for adding/removing elements
at the beginning or middle of the list.
Access time of LinkedList is O(n) (traverses nodes sequentially) and
insertion/deletion time is O(1) (if the node reference is known).
Example:
import java.util.LinkedList;

public class LinkedListExample {


public static void main(String[] args) {
LinkedList<String> tasks = new LinkedList<>();
tasks.add("Complete assignment");
tasks.add("Prepare for meeting");
tasks.add("Pay bills");
tasks.addFirst("Check emails");
tasks.addLast("Call friend");
System.out.println("To-Do List: " + tasks);
tasks.removeFirst();
System.out.println("After Removing First Task: " + tasks);
System.out.println("Last Task: " + tasks.getLast());
}
}
Output:
To-Do List: [Check emails, Complete assignment, Prepare for meeting, Pay bills, Call
friend]
After Removing First Task: [Complete assignment, Prepare for meeting, Pay bills, Call
friend]
Last Task: Call friend
• Comparison of ArrayList and LinkedList:
Feature ArrayList LinkedList
Internal Structure Resizable array Doubly-linked list
Access Time O(1) (direct indexing) O(n) (sequential traversal)
O(1) (if node reference
Insertion/Deletion O(n) (shifting of elements)
known)
Memory Overhead Less (array-based) More (node references stored)
Use Case Frequent random access Frequent insertions/deletions

Accessing a Collection in Java using Iterator and for-each Statement:


In Java, collections like ArrayList, LinkedList, HashSet, and others can be accessed
sequentially using iterators or the enhanced for-each loop. These mechanisms simplify
the process of traversing collections while maintaining code readability.
• Accessing a Collection Using Iterator: The Iterator interface provides methods for
traversing elements in a collection. It is part of the java.util package and works with
any class that implements the Collection interface. The key features are:
➢ Iterator allows sequential traversal of elements.
➢ Can be used to remove elements while iterating.
➢ Provides better control over the iteration process than a for-each loop.
The key methods are:
➢ boolean hasNext(): Returns true if there are more elements to traverse.
➢ E next(): Returns the next element in the iteration.
➢ void remove(): Removes the last element returned by the iterator.
Example: Accessing and Removing Elements from an ArrayList
import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {


public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println("Current Fruit: " + fruit);
if (fruit.equals("Banana")) {
iterator.remove();
}
}
System.out.println("Updated List: " + fruits);
}
}
Output:
Current Fruit: Apple
Current Fruit: Banana
Current Fruit: Cherry
Updated List: [Apple, Cherry]
• Accessing a Collection Using the for-each Statement: The for-each loop (also called an
enhanced for loop) simplifies traversal by automatically iterating through all elements
in a collection. It is more concise but does not allow modification of the collection
during traversal. The key features are:
➢ Provides a simple and clean syntax.
➢ Best suited for read-only traversal or scenarios where no modifications are
needed.
➢ Does not support element removal.
Syntax:
for (Type element : collection) {
// Process the element
}
Example: Printing Elements of a HashSet
import java.util.HashSet;

public class ForEachExample {


public static void main(String[] args) {
HashSet<String> cities = new HashSet<>();
cities.add("New York");
cities.add("Paris");
cities.add("Tokyo");
for (String city : cities) {
System.out.println("City: " + city);
}
}
}
Output:
City: New York
City: Paris
City: Tokyo
• Comparison: Iterator vs. for-each:
Feature Iterator for-each
Can remove elements during Cannot modify the collection
Modification
iteration using remove() directly
Code Complexity Requires more boilerplate code Simpler and more concise
Provides greater control over
Control Limited control (read-only)
iteration
Works with collections and
Supported Types Works with all collections
arrays
Error Handling Explicit error handling required Implicit error handling

In some cases, you may want to use both Iterator and for-each for different parts of your
logic. For instance:
Example: Modifying Elements with Iterator and Printing with for-each
import java.util.ArrayList;
import java.util.Iterator;

public class CombinedExample {


public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Rabbit");
Iterator<String> iterator = animals.iterator();
while (iterator.hasNext()) {
if (iterator.next().equals("Cat")) {
iterator.remove();
}
}
System.out.println("Updated List of Animals:");
for (String animal : animals) {
System.out.println(animal);
}
}
}
Output:
Updated List of Animals:
Dog
Rabbit

Java Applet Class:


Java Applet is a special type of small Java program embedded in the webpage to generate
dynamic content. The specialty of the Java applet is it runs inside the browser and works
on the Client side (User interface side). For Creating any applet in Java, we use
the java.applet.Applet class. It has four Methods in its Life Cycle of Java Applet. The applet
can be executed using the applet viewer utility provided by JDK. A Java Applet was created
using the Applet class, i.e., part of the java.applet package.
The Applet class provides a standard interface between applets and their environment.
The Applet class is the superclass of an applet that is embedded in a Web page or viewed
by the Java Applet Viewer. The Java applet class gives several useful methods to give you
complete control over the running of an Applet. In Java, there are two types of Applets:
• Java Applets based on the AWT (Abstract Window Toolkit) packages by extending its
Applet class
• Java Applets based on the Swing package by extending its JApplet Class in it.
There are two ways to execute a Java Applet:
• By using an HTML file
• By using the appletviewer tool

Life Cycle of Java Applet Class:


Life cycle of Java Applet Class has four main methods in it:
• void init(): This init() method is the first method of a java applet. This is used to
initialize the applet when the applet begins to execute.
• void start(): void start() this method is called automatically after the init() method,
and it is used to start the Applet and to implementation of an applet.
• void paint(): The paint() method is used to draw graphics or render visual elements
(like shapes, text, and images) in an applet. It provides the applet with a Graphics
object that contains methods for drawing on the screen. The paint() method is defined
in the java.awt.Component class and is overridden in applet programs. The paint()
automatically invoked when the applet is first displayed or the applet window is
resized or the applet needs to be repainted due to user actions or system events (e.g.,
minimizing and restoring the window). We can explicitly request a repaint using the
repaint() method, which in turn calls update() and then paint().
• void stop(): void stop() is used to stop the Applet or to stop the running applet.
• void destroy(): void destroy() is used to destroy the Applet / to Terminate the applet.
• System.out.println(String): This method works from appletviewer, as not from
browsers, and it automatically opens an output window.
• ShowStatus(String): This method displays the string in the Applet’s status line, and
each call overwrites the previous call, and you have to allow time to read the line.
• String getParameter(String ParameterName): It returns the value of a parameter
defined in a current applet.
• Image getImage(URL url): This method returns an Image object which contains an
image specified at its location, url.
• void play(URL url): This method can play an audio clip found at the specified location,
url.
• setStub: It sets this applet’s stub, which is done automatically by the system.
• isActive: This method determines if this current applet is active. Then Applet is
marked active just before its start method is invoked. Then, it becomes inactive
immediately after its stop method when it is initialized.

Constructor of Applet Class:


The Applet class is just like any other class as an Applet Constructor is simply the subclass
constructor of the Applet class. Therefore, because the applet constructor is just like any
other constructor, it cannot be overridden, so constructors perform any necessary
initialization for the new object or create the new Object for it.
Example:
import java.applet.*;
import java.awt.*;

public class AppletExp1 extends Applet {


public void init() {
System.out.println("Initializing an applet");
}
public void start() {
System.out.println("Starting an applet");
}
public void paint(Graphics g) {
g.drawString("Hello World", 20, 20);
}
public void stop() {
System.out.println("Stopping an applet");
}
public void destroy() {
System.out.println("Destroying an applet");
}
}
By using Appletviewer, type the following command at the command prompt:
appletviewer AppletExp1.java
Advantages of Applet:
• It runs inside the browser and works on the client-side, so it takes less time to
respond.
• It is more secured.
• It can be executed by multi-platforms with any browsers, i.e., Windows, Mac, Linux.
Disadvantages of Applet:
• A plugin is required at the client browser (user side) to execute an Applet.

setForeground() and setBackground() Methods in Java:


The setForeground() and setBackground() methods in Java are part of the
java.awt.Component class. These methods are used to define the foreground (text color)
and background color of a component, such as buttons, labels, panels, etc.
• setForeground(Color c): It sets the text color or the foreground color of the
component. The Color parameter specifies the desired color.
Syntax:
public void setForeground(Color c)
• setBackground(Color c): It sets the background color of the component. The Color
parameter specifies the desired background color.
Syntax:
public void setBackground(Color c)
Color is an instance of the java.awt.Color class. If not explicitly set, components inherit
their colors from their parent containers. The Color class provides constants like
Color.RED, Color.BLUE, Color.WHITE, etc. We can create custom colors using the Color
constructor with RGB values, e.g., new Color(255, 100, 100).
Example:
import java.awt.Color;
import javax.swing.JButton;

public class Main {


public static void main(String[] args) {
JButton button = new JButton("Click me!");
JButton button2 = new JButton("Click me!");
button.setForeground(Color.RED); // Set the foreground color to red
button.setBackground(Color.YELLOW); // Set the background color to yellow
Color customColor = new Color(255, 100, 100); // RGB values
button2.setBackground(customColor);
}
}
Some common use cases are:
• Highlighting text or components in GUI.
• Creating visually appealing interfaces by customizing component colors.
• Indicating different states (e.g., success in green, error in red).
• Display intermediate results or state changes during development.
• Show helpful messages like "Loading..." or "Click here to proceed."
• Alert users about errors, warnings, or updates.
Its limitations are:
• The status window is a simple text-only area.
• It is browser-dependent and may not always be prominently visible.
HTML <applet> Tag in Java:
The <applet> tag in HTML is used to embed Java applets in a web page. This tag allows
applets (small Java programs) to be executed in a web browser. The applet is specified by
its class file, which must be accessible to the browser.
Syntax:
<applet code="AppletClassName.class" width="width" height="height">
<!-- Optional parameters and fallback message -->
</applet>
The different attributes of <applet> tag in Java is:
• code: It specifies the name of the .class file containing the applet's bytecode.
• width: It defines the width of the applet's display area in pixels.
• height: It defines the height of the applet's display area in pixels.
• name: It assigns a name to the applet, which can be used to refer to it from scripts.
• codebase: It specifies the base URL where the applet's .class file is located (optional).
• name: It assigns a name to the applet, which can be used to refer to it from scripts.
• alt: It displays alternative text if the browser does not support applets.
• archive: It specifies a .jar file containing the applet's classes and resources.
• align: It sets the alignment of the applet (e.g., left, right, top, bottom).
• hspace: It specifies horizontal spacing around the applet.
• vspace: It specifies vertical spacing around the applet.
• <param>: It adds parameters that can be passed to the applet.
Example: Basic Applet Tag
<applet code="MyApplet.class" width="400" height="300">
Your browser does not support Java applets.
</applet>
Example: Applet with Parameters
<applet code="ParamApplet.class" width="400" height="300">
<param name="username" value="Himesh">
<param name="color" value="blue">
Your browser does not support Java applets.
</applet>
getParameter(String name): It is a key method in applet class which is used to retrieve
the value of a parameter passed through the <param> tag. It returns null if the parameter
is not found.
Example: Java Code for Using Parameters
import java.applet.Applet;
import java.awt.Graphics;

public class ParamApplet extends Applet {


String username;
String color;
@Override
public void init() {
username = getParameter("username");
color = getParameter("color");
}
@Override
public void paint(Graphics g) {
g.drawString("Hello, " + username + "!", 50, 50);
g.drawString("Your favorite color is " + color, 50, 70);
}
}
Advantages of <applet> Tag:
• Seamless Integration: It easily embeds Java applets into web pages for interactive
content.
• Customizable: It passes parameters using <param> tags.
• Cross-Platform: Applets can run on any system with a Java-enabled browser.
Disadvantages of <applet> Tag:
• Deprecated: The <applet> tag is no longer supported in modern browsers due to
security concerns. Applets are replaced by Java Web Start or other technologies.
• Browser Dependency: It requires a Java-enabled browser or an applet viewer.
• Security Restrictions: Applets run in a sandbox with limited access to system
resources.

Passing Parameters to an Applet in Java:


In Java applets, parameters can be passed from an HTML file using the <param> tag
within the <applet> tag. These parameters can be accessed in the applet code using the
getParameter(String name) method. This allows applets to dynamically adapt their
behavior based on input provided in the HTML file. The steps for passing parameters are:
• Define Parameters in HTML: Use the <param> tag inside the <applet> tag to specify
the parameter name and value. The <param> tag has two attributes:
➢ name: It specifies the parameter's name.
➢ value: It specifies the parameter's value.
• Access Parameters in Applet: Use the getParameter(String name) method in the
applet code to retrieve the parameter value.
HTML Example:
<applet code="ParamApplet.class" width="300" height="200">
<param name="username" value="Himesh">
<param name="age" value="25">
Your browser does not support Java applets.
</applet>
Java Example:
import java.applet.Applet;
import java.awt.Graphics;

public class ParamApplet extends Applet {


String username;
int age;
@Override
public void init() {
username = getParameter("username");
String ageParam = getParameter("age");
try {
age = Integer.parseInt(ageParam);
} catch (NumberFormatException e) {
age = 0;
}
}
@Override
public void paint(Graphics g) {
g.drawString("Hello, " + username + "!", 20, 50);
g.drawString("You are " + age + " years old.", 20, 70);
}
}
The working of parameter passing to an Applet involve the steps as follows:
• HTML Parameters: Parameters (username and age) are passed from the HTML file
using the <param> tags.
• Applet Initialization: During initialization (init() method), the applet retrieves these
parameters using the getParameter() method.
• Display Parameters: The applet processes the parameters and displays them in the
applet window using the paint() method.
The key points of parameter passing to an Applet are:
• Default Values: Always handle cases where parameters are missing or invalid to avoid
runtime errors. Use default values if the parameter is null or cannot be parsed
correctly.
• Dynamic Behavior: Parameters make applets more flexible and reusable by enabling
dynamic behavior based on external inputs.
• String Format: Parameters retrieved using getParameter() are always strings.
Conversion may be required for numeric or boolean values.

Advantages of Passing Parameters to an Applet in Java:


• Customizability: Applets can be tailored for different users or scenarios without
modifying the Java code.
• Reusability: A single applet can behave differently based on the parameters provided.
Limitations of Passing Parameters to an Applet in Java:
• String Only: Parameters are passed as strings, requiring parsing for other data types.
• Deprecated Applets: Applets and the <applet> tag are outdated and not supported in
modern browsers.

getCodeBase() and getDocumentBase() Methods in Java Applet:


In Java applets, the getCodeBase() and getDocumentBase() methods are used to retrieve
the URLs associated with the applet's code and the HTML document that contains the
applet. These methods are part of the Applet class and are useful for accessing resources
or files relative to the applet's location.
The getCodeBase() method retrieves the URL of the directory or location from which the
applet's .class file was loaded. It returns a URL object representing the location of the
applet's code and is used for accessing resources (e.g., images, audio files) stored in the
same directory or relative to the directory of the .class file. It’s method signature is:
public URL getCodeBase();
The getDocumentBase() method retrieves the URL of the HTML document that contains
the applet. It returns a URL object representing the location of the HTML file embedding
the applet and is used for accessing resources located relative to the HTML file or
displaying the location of the document hosting the applet. It’s method signature is:
public URL getDocumentBase();
Example: Usage of getCodeBase()
import java.applet.Applet;
import java.awt.Graphics;
import java.net.URL;

public class CodeBaseExample extends Applet {


@Override
public void paint(Graphics g) {
URL codeBase = getCodeBase();
g.drawString("CodeBase: " + codeBase, 20, 50);
}
}
Output: Displays the URL of the directory where the .class file is stored.
Example: Usage of getDocumentBase()
import java.applet.Applet;
import java.awt.Graphics;
import java.net.URL;

public class DocumentBaseExample extends Applet {


@Override
public void paint(Graphics g) {
URL documentBase = getDocumentBase();
g.drawString("DocumentBase: " + documentBase, 20, 50);
}
}
Output: Displays the URL of the HTML file containing the applet.
Example: Combining Both Methods
import java.applet.Applet;
import java.awt.Graphics;
import java.net.URL;

public class BaseExample extends Applet {


@Override
public void paint(Graphics g) {
URL codeBase = getCodeBase();
URL documentBase = getDocumentBase();
g.drawString("CodeBase: " + codeBase, 20, 50);
g.drawString("DocumentBase: " + documentBase, 20, 70);
}
}
Use Cases:
• Loading Resources Dynamically: getCodeBase() is used to load images, audio, or other
files relative to the applet's location and getDocumentBase() is used to load resources
relative to the HTML file.
• Building Links: These methods are used to create absolute URLs for files based on
their relative paths.
• Security Context: It ensures that applets access resources only from their allowed
locations, respecting sandbox restrictions.
Limitations:
• Deprecated Technology: Applets and their related methods are no longer supported
in modern browsers.
• Limited Use Cases: Both methods rely on the applet being embedded in an HTML page,
which is outdated.

Delegation Event Model in Java:


The Delegation Event Model is the standard mechanism for handling events in Java. It is
part of the Abstract Window Toolkit (AWT) and Swing and provides a flexible and
efficient way to manage user interactions such as button clicks, mouse movements, or
keyboard inputs. The three key concepts are:
• Event Source: It is the object on which an event occurs (e.g., a button, a checkbox, or a
window). The event source generates an event and sends it to one or more listeners.
• Event Listener: It is an object that waits for an event to occur and responds to it. A
listener implements an appropriate interface to handle the event (e.g., ActionListener,
MouseListener).
• Event Object: It encapsulates information about an event. All event objects inherit
from the java.util.EventObject class.
The working of Delegation Event Model is as follows:
• Event Registration: The listener object registers itself with an event source.
Registration is done using methods like addActionListener() or addMouseListener().
• Event Generation: When an event occurs (e.g., a button click), the event source
generates an event object.
• Event Handling: The event object is dispatched to the registered listener, which
handles the event by executing a predefined method.
The steps to implement Delegation Event Model are:
• Implement the Listener Interface: Create a class that implements the required event
listener interface (e.g., ActionListener).
• Register the Listener: Attach the listener object to an event source using methods like
addActionListener().
• Override the Event-Handling Method: Define the logic to handle the event inside the
overridden method.
Advantages of Delegation Event Model in Java:
• Separation of Concerns: The event-handling logic is separate from the main
application logic.
• Flexibility: Multiple listeners can listen to the same event source.
• Reusability: Listener classes can be reused across different components or
applications.
Key Interfaces:
• ActionListener: It handles action events like button clicks. Some methods are void
actionPerformed(ActionEvent e).
Example: Handling Button Click
import javax.swing.*;
import java.awt.event.*;

public class ButtonClickExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Button Example");
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 100, 50);
button.addActionListener(e -> System.out.println("Button clicked!"));
frame.add(button);
frame.setSize(300, 300);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
• MouseListener: It handles mouse events like clicks or releases. Some methods are
mouseClicked(MouseEvent e), mousePressed(MouseEvent e), etc.
Example: Handling Mouse Clicks
import java.awt.*;
import java.awt.event.*;

public class SimpleMouseListener extends Frame {


public SimpleMouseListener() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: (" + e.getX() + ", " + e.getY() + ")");
}
});
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new SimpleMouseListener();
}
}
• KeyListener: It handles keyboard events. Some methods are keyPressed(KeyEvent e),
keyReleased(KeyEvent e), etc.
Example: Handling Keyboard Input
import java.awt.*;
import java.awt.event.*;

public class KeyListenerExample extends Frame {


Label label;
public KeyListenerExample() {
label = new Label("Type something...");
label.setBounds(50, 50, 200, 20);
add(label);
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
label.setText("Key typed: " + e.getKeyChar());
}
});
setSize(300, 200);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new KeyListenerExample();
}
}

Event Classes in Event Handling and AWT in Java:


Java provides a set of event classes in the java.awt.event package that represent various
types of events generated by AWT components. These classes encapsulate information
about events and are used in the Delegation Event Model to handle user interactions like
mouse clicks, key presses, window actions, etc. All event classes extend the
java.util.EventObject class, and most AWT event classes extend the java.awt.AWTEvent
class. The key event classes are:
• ActionEvent: It represents action events like button clicks or pressing Enter in a text
field. Source Components are Button, MenuItem, TextField. One of it’s method is
getActionCommand() which returns the command string associated with the action.
Example:
import java.awt.*;
import java.awt.event.*;

public class ActionEventExample {


public static void main(String[] args) {
Frame frame = new Frame("ActionEvent Example");
Button button = new Button("Click Me");
button.addActionListener(e -> System.out.println("Button clicked!"));
frame.add(button);
frame.setSize(200, 150);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
• MouseEvent: It represents mouse actions like clicks, presses, movements, or
entering/exiting a component. It has several methods like getX(), getY() which
returns the x and y coordinates of the mouse and getClickCount() which returns the
number of clicks.
Example:
import java.awt.*;
import java.awt.event.*;

public class MouseEventExample extends Frame {


public MouseEventExample() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new MouseEventExample();
}
}
• KeyEvent: It represents keyboard events like key presses and releases. It has several
methods like getKeyChar() which returns the character of the key pressed and
getKeyCode() which returns the virtual key code.
Example:
import java.awt.*;
import java.awt.event.*;

public class KeyEventExample extends Frame {


public KeyEventExample() {
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new KeyEventExample();
}
}
• WindowEvent: It represents events related to the state of a window, such as opening,
closing, minimizing, or restoring. The source components are Window, Frame, Dialog
and it has some methods like getWindow() which returns the window associated with
the event.
Example:
import java.awt.*;
import java.awt.event.*;

public class WindowEventExample extends Frame {


public WindowEventExample() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window closing");
dispose();
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new WindowEventExample();
}
}
• AdjustmentEvent: It represents adjustments made to scrollbars. The source
component is Scrollbar and it has some methods like getValue() which returns the
current value of the scrollbar.
Example:
import java.awt.*;
import java.awt.event.*;

public class AdjustmentEventExample extends Frame {


public AdjustmentEventExample() {
Scrollbar scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 100);
scrollbar.addAdjustmentListener(e -> System.out.println("Scrollbar value: " +
e.getValue()));
add(scrollbar);
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new AdjustmentEventExample();
}
}
• FocusEvent: It represents focus gained or lost by a component. It has some methods
like isTemporary() which returns true if the focus change is temporary.
Example:
import java.awt.*;
import java.awt.event.*;

public class FocusEventExample extends Frame {


public FocusEventExample() {
TextField textField = new TextField(20);
textField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
System.out.println("TextField gained focus");
}
});
add(textField);
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String[] args) {
new FocusEventExample();
}
}
Summary of all the Event Classes in Event Handling and AWT in Java:
Event Class Represents Source Components
ActionEvent Button clicks, menu actions Button, MenuItem
MouseEvent Mouse actions Component
KeyEvent Keyboard actions Component
WindowEvent Window state changes Frame, Dialog
AdjustmentEvent Scrollbar adjustments Scrollbar
FocusEvent Focus gain/loss Component

Sources of Events in Event Handling and AWT in Java:


In Java's Event Handling model, a source is an object that generates events. These events
represent user actions, such as button clicks, key presses, or mouse movements, and
system actions, such as window state changes. The source is typically an AWT component,
and it notifies registered listeners about events by calling their methods. The key sources
of events are:
• Button: Triggers an ActionEvent when clicked.
Example:
import java.awt.*;
import java.awt.event.*;

public class ButtonEventExample {


public static void main(String[] args) {
Frame frame = new Frame("Button Event Example");
Button button = new Button("Click Me");
button.addActionListener(e -> System.out.println("Button clicked!"));
frame.add(button);
frame.setSize(200, 150);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
• TextField: Triggers an ActionEvent when the Enter key is pressed and a TextEvent
when the text is modified.
Example:
import java.awt.*;
import java.awt.event.*;

public class TextFieldEventExample {


public static void main(String[] args) {
Frame frame = new Frame("TextField Event Example");
TextField textField = new TextField(20);
textField.addActionListener(e -> System.out.println("Text entered: " +
textField.getText()));
frame.add(textField);
frame.setSize(300, 150);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
• Scrollbar: Triggers an AdjustmentEvent when the scrollbar is adjusted.
Example:
import java.awt.*;
import java.awt.event.*;

public class ScrollbarEventExample {


public static void main(String[] args) {
Frame frame = new Frame("Scrollbar Event Example");
Scrollbar scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 100);
scrollbar.addAdjustmentListener(e -> System.out.println("Scrollbar value: " +
e.getValue()));
frame.add(scrollbar);
frame.setSize(300, 150);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
• Window: Triggers WindowEvent for actions like opening, closing, minimizing, or
restoring a window.
Example:
import java.awt.*;
import java.awt.event.*;

public class WindowEventExample extends Frame {


public WindowEventExample() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing");
dispose();
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new WindowEventExample();
}
}
• Mouse: Triggers a MouseEvent for actions like clicks, movements, or entering/exiting
a component.
Example:
import java.awt.*;
import java.awt.event.*;

public class MouseEventExample extends Frame {


public MouseEventExample() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new MouseEventExample();
}
}
• Key: Triggers a KeyEvent for actions like key presses and releases.
Example:
import java.awt.*;
import java.awt.event.*;

public class KeyEventExample extends Frame {


public KeyEventExample() {
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new KeyEventExample();
}
}

Event Listener Interfaces in Event Handling and AWT in Java:


In Java's Delegation Event Model, event listeners are objects that implement event listener
interfaces. These interfaces define methods that handle specific types of events, allowing
programs to respond to user interactions like button clicks, mouse movements, or
keyboard actions.
• Event Listeners: Objects that receive notifications about events.
• Listener Interfaces: Define methods for handling specific events.
• Registration: A listener must be registered with a source to receive events using
methods like addActionListener() or addMouseListener().
The key event listener interfaces are:
• ActionListener: It handles ActionEvent for components like buttons, menu items, and
text fields. void actionPerformed(ActionEvent e) is called when an action occurs.
Example:
import java.awt.*;
import java.awt.event.*;

public class ActionListenerExample {


public static void main(String[] args) {
Frame frame = new Frame("ActionListener Example");
Button button = new Button("Click Me");
button.addActionListener(e -> System.out.println("Button clicked!"));
frame.add(button);
frame.setSize(200, 150);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
• MouseListener: It handles MouseEvent for mouse actions like clicks, presses, and
entering/exiting a component. The several methods are:
➢ void mouseClicked(MouseEvent e)
➢ void mousePressed(MouseEvent e)
➢ void mouseReleased(MouseEvent e)
➢ void mouseEntered(MouseEvent e)
➢ void mouseExited(MouseEvent e)
Example:
import java.awt.*;
import java.awt.event.*;

public class MouseListenerExample extends Frame implements MouseListener {


public MouseListenerExample() {
addMouseListener(this);
setSize(300, 200);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public static void main(String[] args) {
new MouseListenerExample();
}
}
• KeyListener: It handles KeyEvent for keyboard actions like key presses and releases.
The methods are:
➢ void keyPressed(KeyEvent e)
➢ void keyReleased(KeyEvent e)
➢ void keyTyped(KeyEvent e)
Example:
import java.awt.*;
import java.awt.event.*;

public class KeyListenerExample extends Frame implements KeyListener {


public KeyListenerExample() {
addKeyListener(this);
setSize(300, 200);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new KeyListenerExample();
}
}
• WindowListener: It handles WindowEvent for window actions like opening, closing,
or minimizing. The methods are:
➢ void windowOpened(WindowEvent e)
➢ void windowClosing(WindowEvent e)
➢ void windowClosed(WindowEvent e)
➢ void windowIconified(WindowEvent e)
➢ void windowDeiconified(WindowEvent e)
➢ void windowActivated(WindowEvent e)
➢ void windowDeactivated(WindowEvent e)
Example:
import java.awt.*;
import java.awt.event.*;

public class WindowListenerExample extends Frame implements WindowListener {


public WindowListenerExample() {
addWindowListener(this);
setSize(300, 200);
setVisible(true);
}
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing");
dispose();
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public static void main(String[] args) {
new WindowListenerExample();
}
}
• FocusListener: It handles FocusEvent when a component gains or loses focus. The
methods are:
➢ void focusGained(FocusEvent e)
➢ void focusLost(FocusEvent e)
Example:
import java.awt.*;
import java.awt.event.*;

public class FocusListenerExample extends Frame {


public FocusListenerExample() {
TextField textField = new TextField(20);
textField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
System.out.println("TextField gained focus");
}
});
add(textField);
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String[] args) {
new FocusListenerExample();
}
}

Java Adapter Classes:


Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So, it saves code. The pros of using Adapter classes are:
• It assists the unrelated classes to work combinedly.
• It provides ways to use classes in different ways.
• It increases the transparency of classes.
• It provides a way to include related patterns in the class.
• It provides a pluggable kit for developing an application.
• It increases the reusability of the class.
The adapter classes are found in java.awt.event,
java.awt.dnd and javax.swing.event packages. The Adapter classes with their
corresponding listener interfaces are given below:
java.awt.event Adapter classes:
Adapter class Listener interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
java.awt.dnd Adapter classes:
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
javax.swing.event Adapter classes:
Adapter class Listener interface
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Example: Using MouseAdapter
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends Frame {
public MouseAdapterExample() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at X: " + e.getX() + ", Y: " + e.getY());
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
Instead of implementing all MouseListener methods, only mouseClicked is overridden.
Example: Using WindowAdapter
import java.awt.*;
import java.awt.event.*;

public class WindowAdapterExample extends Frame {


public WindowAdapterExample() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing!");
dispose(); // Close the window
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new WindowAdapterExample();
}
}
Only the windowClosing method is overridden to handle the event when the window is
closed.
Example: Using KeyAdapter
import java.awt.*;
import java.awt.event.*;

public class KeyAdapterExample extends Frame {


public KeyAdapterExample() {
TextField textField = new TextField(20);

textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}
});
add(textField);
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String[] args) {
new KeyAdapterExample();
}
}
Only the keyPressed method is overridden to handle key press events.

Inner and Anonymous Classes in Event Handling and AWT in Java:


In Java, inner classes and anonymous classes are commonly used for event handling in
AWT and Swing. They provide a clean and efficient way to associate event-handling code
with GUI components.
• Inner Classes for Event Handling: An inner class is a class defined within another class.
Inner classes can be used for event handling by implementing event listener
interfaces. The advantages are:
➢ Direct access to the enclosing class's members (including private members).
➢ Improved code organization by grouping related event-handling logic inside the
same class.
Example: Inner Class for Event Handling
import java.awt.*;
import java.awt.event.*;

public class InnerClassExample extends Frame {


public InnerClassExample() {
Button button = new Button("Click Me");
button.addActionListener(new ButtonClickListener());
add(button);
setSize(200, 150);
setLayout(new FlowLayout());
setVisible(true);
}
class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
}
public static void main(String[] args) {
new InnerClassExample();
}
}
• Anonymous Classes for Event Handling: An anonymous class is a class without a name.
It is used to create a one-time implementation of an interface or a subclass of a class.
The advantages are:
➢ Reduces boilerplate code by defining and instantiating the class in one step.
➢ Keeps event-handling code concise and close to the component that generates the
event.
Example: Anonymous Class for Event Handling
import java.awt.*;
import java.awt.event.*;

public class AnonymousClassExample extends Frame {


public AnonymousClassExample() {
Button button = new Button("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});
add(button);
setSize(200, 150);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String[] args) {
new AnonymousClassExample();
}
}
Comparison Between Inner and Anonymous Classes:
Feature Inner Class Anonymous Class
Named class defined inside
Definition Class defined without a name
another class
Reusability Can be reused elsewhere One-time use only
Conciseness Slightly more verbose More concise
When the event logic is reused or For simple, one-time event
Use Case
complex handling logic

Lambda Expressions for Simplified Event Handling:


For interfaces with a single abstract method (functional interfaces like ActionListener),
Java 8 introduced lambda expressions, which further simplify event handling.
Example:
import java.awt.*;
import java.awt.event.*;

public class LambdaExample extends Frame {


public LambdaExample() {
Button button = new Button("Click Me");
button.addActionListener(e -> System.out.println("Button clicked!"));
add(button);
setSize(200, 150);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String[] args) {
new LambdaExample();
}
}

Java AWT Button:


A button is basically a control component with a label that generates an event when
pushed. The Button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.
When we press a button and release it, AWT sends an instance of ActionEvent to that
button by calling processEvent on the button. The processEvent method of the button
receives the all the events, then it passes an action event by calling its own
method processActionEvent. This method passes the action event on to action listeners
that are interested in the action events generated by the button.
To perform an action on a button being pressed and released, the ActionListener interface
needs to be implemented. The registered new listener can receive events from the button
by calling addActionListener method of the button. The Java application can use the
button's action command as a messaging protocol.
AWT Button Class Declaration Syntax:
public class Button extends Component implements Accessible
Button Class Constructors:
Constructor Description
It constructs a new button with an empty string i.e. it has no
Button( )
label.
Button (String text) It constructs a new button with given string as its label.
Button Class Methods:
Method Description
void setText (String text) It sets the string message on the button
String getText() It fetches the String message on the button.
It sets the label of button with the specified
void setLabel (String label)
string.
String getLabel() It fetches the label of the button.
setEnabled(boolean enabled) Enables or disables the button.
isEnabled() Checks if the button is enabled.
Registers an ActionListener to handle
addActionListener(ActionListener l)
button click events.
setBounds(int x, int y, int width, int Sets the position and size of the button on
height) the frame.
Example: Demonstrating All Methods
import java.awt.*;
import java.awt.event.*;

public class ButtonExample extends Frame {


public ButtonExample() {
Button button = new Button("Click Me");
button.setBounds(50, 100, 80, 30);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button.setLabel("Clicked!");
System.out.println("Button is clicked!");
button.setEnabled(false);
}
});
add(button);
setSize(200, 200);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new ButtonExample();
}
}

Java AWT Label:


The object of the Label class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by a programmer but a user
cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed. To create
a label, we need to create the object of Label class.
AWT Label Class Declaration Syntax:
public class Label extends Component implements Accessible
AWT Label Fields:
The java.awt.Component class has following fields:
• static int LEFT: It specifies that the label should be left justified.
• static int RIGHT: It specifies that the label should be right justified.
• static int CENTER: It specifies that the label should be placed in center.
Label Class Constructors:
Constructor Description
Label() It constructs an empty label.
It constructs a label with the given string (left justified
Label(String text)
by default).
Label(String text, int It constructs a label with the specified string and the
alignement) specified alignment.
Label Class Methods:
Method name Description
void setText(String text) It sets the texts for label with the specified
text.
void setAlignment(int alignment) It sets the alignment for label with the
specified alignment.
String getText() It gets the text of the label
int getAlignment() It gets the current alignment of the label.
void addNotify() It creates the peer for the label.
AccessibleContext It gets the Accessible Context associated with
getAccessibleContext() the label.
protected String paramString() It returns the string the state of the label.
Example:
import java.awt.*;
import javax.accessibility.AccessibleContext;

public class LabelExample extends Frame {


public LabelExample() {
Label label = new Label("Default Text", Label.CENTER);
label.setText("Hello, AWT Label!");
label.setAlignment(Label.RIGHT);
System.out.println("Current Label Text: " + label.getText());
int alignment = label.getAlignment();
System.out.println("Current Alignment: " + (alignment == Label.RIGHT ? "RIGHT" :
alignment == Label.CENTER ? "CENTER" : "LEFT"));
label.addNotify();
System.out.println("Label peer created successfully.");
AccessibleContext accessibleContext = label.getAccessibleContext();
System.out.println("Accessible Context: " + accessibleContext);
String labelState = label.paramString();
System.out.println("Label State: " + labelState);
add(label);
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String[] args) {
new LabelExample();
}
}

Java AWT TextField:


The object of a TextField class is a text component that allows a user to enter a single line
text and edit it. It inherits TextComponent class, which further inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed), the
event is sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It
can also be done using ActionEvent; if the ActionEvent is enabled on the text field, then
the ActionEvent may be fired by pressing return key. The event is handled by
the ActionListener interface.
AWT TextField Class Declaration Syntax:
public class TextField extends TextComponent
TextField Class Constructors:
Constructor Description
TextField() It constructs a new text field component.
It constructs a new text field initialized with the given
TextField(String text)
string text to be displayed.
It constructs a new textfield (empty) with given number
TextField(int columns)
of columns.
TextField(String text, int It constructs a new text field with the given text and
columns) given number of columns (width).
TextField Class Methods:
Method Description
setText(String text) Sets the text in the text field.
getText() Retrieves the text currently in the text field.
setEditable(boolean editable) Enables or disables user editing of the text field.
isEditable() Checks if the text field is editable.
Sets a character to mask the input (useful for
setEchoChar(char c)
passwords).
getEchoChar() Gets the current echo character.
addTextListener(TextListener l) Adds a listener to monitor changes in the text field.
Gets the number of columns (character width) of
getColumns()
the text field.
Sets the number of columns (character width) of
setColumns(int columns)
the text field.
Example: Demonstrating All Methods
import java.awt.*;
import java.awt.event.*;

public class TextFieldExample extends Frame {


public TextFieldExample() {
TextField textField = new TextField("Default Text", 20);
textField.setText("Hello, AWT TextField!");
System.out.println("Current Text: " + textField.getText());
textField.setEditable(true);
System.out.println("Is Editable: " + textField.isEditable());
textField.setEchoChar('*');
System.out.println("Echo Character Set: " + textField.getEchoChar());
textField.addTextListener(new TextListener() {
public void textValueChanged(TextEvent e) {
System.out.println("Text changed to: " + textField.getText());
}
});
System.out.println("Number of Columns: " + textField.getColumns());
textField.setColumns(30);
System.out.println("Columns updated to: " + textField.getColumns());
add(textField);
setSize(400, 200);
setLayout(new FlowLayout());
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new TextFieldExample();
}
}

Java AWT TextArea:


The object of a TextArea class is a multiline region that displays text. It allows the editing
of multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps
us to scroll the text up and down, or right and left.
AWT TextArea Class Declaration Syntax:
public class TextArea extends TextComponent
Fields of TextArea Class: The fields of java.awt.TextArea class are as follows:
• static int SCROLLBARS_BOTH: It creates and displays both horizontal and vertical
scrollbars.
• static int SCROLLBARS_HORIZONTAL_ONLY: It creates and displays only the
horizontal scrollbar.
• static int SCROLLBARS_VERTICAL_ONLY: It creates and displays only the vertical
scrollbar.
• static int SCROLLBARS_NONE: It doesn't create or display any scrollbar in the text
area.
TextArea Class Constructors:
Constructor Description
It constructs a new and empty text area with no text
TextArea()
in it.
TextArea (int row, int It constructs a new text area with specified number of
column) rows and columns and empty string as text.
It constructs a new text area and displays the
TextArea (String text)
specified text in it.
It constructs a new text area with the specified text in
TextArea (String text, int row,
the text area and specified number of rows and
int column)
columns.
It construcst a new text area with specified text in text
TextArea (String text, int row,
area and specified number of rows and columns and
int column, int scrollbars)
visibility.
TextArea Class Methods:
Method name Description
void addNotify() It creates a peer of text area.
It appends the specified text to the current text
void append(String str)
of text area.
AccessibleContext It returns the accessible context related to the
getAccessibleContext() text area
int getColumns() It returns the number of columns of text area.
Dimension getMinimumSize() It determines the minimum size of a text area.
Dimension getMinimumSize(int It determines the minimum size of a text area
rows, int columns) with the given number of rows and columns.
Dimension getPreferredSize() It determines the preferred size of a text area.
Dimension preferredSize(int rows, It determines the preferred size of a text area
int columns) with given number of rows and columns.
int getRows() It returns the number of rows of text area.
It returns an enumerated value that indicates
int getScrollbarVisibility()
which scroll bars the text area uses.
It inserts the specified text at the specified
void insert(String str, int pos)
position in this text area.
It returns a string representing the state of this
protected String paramString()
TextArea.
It replaces text between the indicated start and
void replaceRange(String str, int
end positions with the specified replacement
start, int end)
text.
void setColumns(int columns) It sets the number of columns for this text area.
void setRows(int rows) It sets the number of rows for this text area.
Example: Demonstrating All Methods
import java.awt.*;

public class TextAreaExample extends Frame {


public TextAreaExample() {
TextArea textArea = new TextArea("Default Text", 5, 20);
textArea.setText("Welcome to Java AWT TextArea!");
System.out.println("Current Text: " + textArea.getText());
textArea.append("\nThis is an appended line.");
textArea.insert("Inserted Text: ", 0);
textArea.replaceRange("Modified Text", 0, 13);
textArea.setEditable(true);
System.out.println("Is Editable: " + textArea.isEditable());
System.out.println("Number of Rows: " + textArea.getRows());
System.out.println("Number of Columns: " + textArea.getColumns());
textArea.setRows(10);
System.out.println("Rows updated to: " + textArea.getRows());
textArea.setColumns(30);
System.out.println("Columns updated to: " + textArea.getColumns());
add(textArea);
setSize(400, 300);
setLayout(new FlowLayout());
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new TextAreaExample();
}
}

Java AWT Scrollbar:


The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.
It can be added to top-level container like Frame or a component like Panel. The Scrollbar
class extends the Component class.
AWT Scrollbar Class Declaration Syntax:
public class Scrollbar extends Component implements Adjustable, Accessible
Scrollbar Class Fields: The fields of java.awt.Image class are as follows:
• static int HORIZONTAL: It is a constant to indicate a horizontal scroll bar.
• static int VERTICAL: It is a constant to indicate a vertical scroll bar.
Scrollbar Class Constructors:
Constructor Description
Scrollbar() Constructs a new vertical scroll bar.
Constructs a new scroll bar with the specified
Scrollbar(int orientation)
orientation.
Scrollbar(int orientation, int Constructs a new scroll bar with the specified
value, int visible, int minimum, orientation, initial value, visible amount, and
int maximum) minimum and maximum values.
where the parameters:
• orientation: specify whether the scrollbar will be horizontal or vertical.
• Value: specify the starting position of the knob of Scrollbar on its track.
• Minimum: specify the minimum width of track on which scrollbar is moving.
• Maximum: specify the maximum width of track on which scrollbar is moving.
Scrollbar Class Methods:
Method Description
Sets the scrollbar's current value,
setValues(int value, int visible, int minimum, int
visible amount, minimum, and
maximum)
maximum range.
Returns the current value
getValue()
(position) of the scrollbar.
Sets the current value (position) of
setValue(int value)
the scrollbar.
Returns the minimum value of the
getMinimum()
scrollbar.
Returns the maximum value of the
getMaximum()
scrollbar.
Sets the unit increment (the
setUnitIncrement(int u) number of units to move when the
user clicks the scrollbar's arrows).
Sets the block increment (the
setBlockIncrement(int b) number of units to move when the
user clicks the scrollbar's track).
Returns the orientation of the
getOrientation()
scrollbar (vertical or horizontal).
Adds an adjustment listener that
addAdjustmentListener(AdjustmentListener l) reacts to changes in the scrollbar's
value.
Example: Demonstrating All Methods
import java.awt.*;
import java.awt.event.*;

public class ScrollbarExample extends Frame {


public ScrollbarExample() {
Scrollbar scrollbar = new Scrollbar();
scrollbar.setBounds(50, 50, 30, 200);
scrollbar.setValues(50, 10, 0, 100);
System.out.println("Initial Value: " + scrollbar.getValue());
System.out.println("Minimum Value: " + scrollbar.getMinimum());
System.out.println("Maximum Value: " + scrollbar.getMaximum());
System.out.println("Current Value of Scrollbar: " + scrollbar.getValue());
scrollbar.setValue(70);
System.out.println("Scrollbar Value after setValue(70): " + scrollbar.getValue());
System.out.println("Scrollbar Minimum Value: " + scrollbar.getMinimum());
System.out.println("Scrollbar Maximum Value: " + scrollbar.getMaximum());
scrollbar.setUnitIncrement(5);
System.out.println("Unit Increment set to 5.");
scrollbar.setBlockIncrement(20);
System.out.println("Block Increment set to 20.");
System.out.println("Scrollbar Orientation: " + (scrollbar.getOrientation() ==
Scrollbar.VERTICAL ? "Vertical" : "Horizontal"));
scrollbar.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("Scrollbar Value Changed: " + e.getValue());
}
});
add(scrollbar);
setSize(400, 400);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new ScrollbarExample();
}
}

You might also like