0% found this document useful (0 votes)
19 views254 pages

Java Material

The document provides an overview of Object-Oriented Programming (OOP) concepts and the history of the Java programming language. It covers fundamental OOP principles such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction, along with Java's evolution from its inception in 1995 to recent developments. Additionally, it discusses Java's key features, the architecture of the Java Virtual Machine (JVM), and variable types in Java.

Uploaded by

kratos66997
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)
19 views254 pages

Java Material

The document provides an overview of Object-Oriented Programming (OOP) concepts and the history of the Java programming language. It covers fundamental OOP principles such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction, along with Java's evolution from its inception in 1995 to recent developments. Additionally, it discusses Java's key features, the architecture of the Java Virtual Machine (JVM), and variable types in Java.

Uploaded by

kratos66997
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

PG DEPARTMENT OF COMPUTER SCIENCE

SUBJECT NOTES

PROGRAMME : [Link]., Computer Science

Class : II – [Link]., CS

Semester : IV - Semester

Batch : 2023 - 2026

Course Name : JAVA PROGRAMMING

Course Code : 23UCS04

Handling Staff Name : Mr. A. PRAKASH., M.C.A., [Link].,

Student Name :

Register No :
UNIT I
Introduction: Review of Object-Oriented Concepts

Object-Oriented Programming (OOP) is a programming paradigm based on the concept


of "objects." These objects represent real-world entities and can have attributes (data)
and behaviors (functions or methods).
OOP is widely used in modern programming languages like Java, Python, C++, and
others.
This introduction will review the core concepts of OOP:

1. Class: A class is a blueprint for creating objects. It defines the structure (attributes) and
behavior (methods) that the objects created from the class will have. For example, a class "Car"
might define attributes like color and model, and methods like drive() and brake().

2. Object: An object is an instance of a class. It holds the actual data and methods defined by the

class. Multiple objects can be created from a single class, each with its own unique set of data.
3. Encapsulation: This concept involves bundling the data (attributes) and methods (functions)
that operate on the data into a single unit or class. Encapsulation also ensures that the data
within a class is protected from unauthorized access by hiding its internal details, often
achieved by using access modifiers like private, protected, and public.

4. Inheritance: Inheritance allows a class to inherit attributes and methods from another class.
This promotes code reuse and hierarchical classification. For instance, a "Truck" class can
inherit from a "Vehicle" class, gaining its attributes and methods, while also having unique
features of its own.

5. Polymorphism: Polymorphism enables a single function or method to behave differently based


on the object that invokes it. There are two types:
o Compile-time polymorphism (method overloading): Same method name but different
parameters.
o Run-time polymorphism (method overriding): A subclass can provide a specific
implementation of a method already defined in its superclass.

6. Abstraction: Abstraction hides the complex implementation details of an object and exposes
only the necessary parts. This is typically achieved through abstract classes and interfaces,
allowing users to work with high-level entities without knowing the internal complexities.
These fundamental concepts form the foundation of OOP, allowing for modular, reusable, and
maintainable code, which is especially beneficial in large-scale software development.

History of Java
Java is a high-level, object-oriented programming language initially developed by Sun
Microsystems (now owned by Oracle Corporation) in 1995. The language has undergone
significant evolution since its inception and remains one of the most popular programming
languages in the world today. Here's a brief history of Java:
1. 1991: The Origins - The Green Team
Java was originally developed as part of a project called Green Project led by James
Gosling, along with Mike Sheridan and Patrick Naughton.
The team wanted a platform-independent language that could run on any type of device.
Initially, they called the language Oak, after an oak tree outside Gosling's office.
However, the name was later changed to Java due to a trademark conflict.

2. 1995: The Release of Java 1.0

Java was officially released in 1995. The language was promoted with the tagline
"Write Once, Run Anywhere" (WORA), signifying its ability to run on any device that
had a Java Virtual Machine (JVM). This platform independence was made possible
through the bytecode system, which allowed Java programs to be compiled once and
run anywhere.
Java 1.0 was widely adopted by web developers, as it allowed them to create dynamic
content using Java applets that could run within a web browser.

3. Late Growth

Java gained widespread popularity during the late 1990s due to the rise of the Internet.
It was widely used for creating web applications and applets. Around this time, Sun
Microsystems released various versions of Java, including:
Java 1.1 (1997): Introduced event handling, JDBC (Java Database
Connectivity), and inner classes.
Java 2 (1998): This version marked a major upgrade, bringing in the
concept of multiple configurations for different platforms, such as J2SE
(Java 2 Standard Edition), J2EE (Java 2 Enterprise Edition), and J2ME(Java
2 Micro Edition).
4. 2000s: Enterprise Adoption and J2EE

By the early 2000s, Java had become the standard for enterprise-level applications,
particularly with the introduction of Java 2 Enterprise Edition (J2EE), which
provided a robust platform for developing distributed, scalable, and secure applications.
The adoption of Java for server-side programming allowed for the development of
large-scale web applications and enterprise systems. Java's reliability, security features,
and scalability contributed to its dominance in the industry.
5. 2004: Java 5.0 (J2SE 5.0)

Java 5.0 (also known as J2SE 5.0 or Java 1.5) brought several significant language
improvements, such as:
o Generics
o Enhanced for loop
o Autoboxing/Unboxing
o Enums
o Varargs These additions improved developer productivity and made the language more
expressive.
6. 2006: OpenJDK and the Evolution to Java SE

In 2006, Sun Microsystems announced the OpenJDK project, which made Java's
source code available to the public under the GNU General Public License (GPL).
This step encouraged greater community involvement and innovation.

7. 2010: Oracle Acquisition

In 2010, Oracle Corporation acquired Sun Microsystems, including Java. Oracle


continued to develop Java and made several enhancements to the language, tools, and
JVM.
Subsequent releases of Java, such as Java 7 (2011), Java 8 (2014), and Java 9 (2017),
introduced new features like:
o Lambda Expressions (Java 8)
o Stream API (Java 8)
o Modularization (Project Jigsaw) (Java 9)
8. Recent Developments: Java 10 and Beyond

Java has moved to a more rapid release cycle, with a new version released every six
months. Notable versions include:
Java 11 (2018): The first long-term support (LTS) release under Oracle's new cadence.
It included new features like the var keyword for local variables and the removal of
some deprecated features.
Java 17 (2021): Another LTS release, introducing new features such as sealed classes
and pattern matching for switch expressions.
Java Buzzwords
Java, from its inception, has been associated with a series of key "buzzwords" that define its
philosophy and features. These buzzwords highlight the core strengths of the language and
explain why Java is so widely used. Here's a review of the main Java buzzwords:
1. Simple:
Java was designed to be easy to learn and use. It simplified many complex features of languages
like C and C++ by removing explicit pointers, operator overloading, and multiple
syntax is also clean and closely resembles C++, which makes it familiar tomany developers.
2. Object-Oriented:
Everything in Java is based on objects, which makes the language intuitive and flexible for solving
real-world problems. It supports the four fundamental OOP principles encapsulation,inheritance,
polymorphism, and abstraction.
3. Platform-Independent:

4. Secure:
Java places a strong emphasis on security. It provides a security manager that controls access to
automatic
memory management and strong type-checking, helping prevent common security vulnerabilities like
memory leaks or buffer overflow attacks.
5. Robust:
Java was designed with reliability in mind. It emphasizes strong memory management by
-checking
mechanism ensures fewer errors, and runtime checks help identify bugs early.
6. Multithreaded:
Java natively supports multithreading, allowing multiple threads to run concurrently within a
program. This makes it easier to develop applications that perform multiple tasks simultaneously,
such as handling multiple user requests in a web server or performing background operations.
7. Architecture-Neutral:

depend on any specific processor or operating system. This allows Java programs to run on anyplatform
with a compatible JVM.
8. Interpreted:
Java programs are compiled into bytecode, which is interpreted by the JVM. This intermediatestep
allows Java to be platform-independent and makes the program execution faster than traditional
interpreted languages while ensuring portability.
9. High Performance:
While Java may not be as fast as languages like C or C++ due to the overhead of bytecode
interpretation, techniques like Just-In-Time (JIT) compilation, where bytecode is compiledinto
time.
10. Distributed:
Java provides built-in support for developing distributed applications. It comes with libraries
such as Remote Method Invocation (RMI) and supports networking through its extensive API,
which allows Java programs to communicate over the network.
11. Dynamic:
Java is designed to adapt to an evolving environment. It supports dynamic loading of classes,meaning that new
modules can be loaded at runtime without restarting the application. Java also supports reflection, enabling the
inspection and manipulation of classes and objects at runtime.
12. Portable:
Since Java eliminates many system-dependent features (like pointer arithmetic in C/C++) anddefines platform-
independent data types (e.g., the size of int is always 32 bits), it ensures thatJava applications are highly portable
across different platforms.

Java Virtual Machine (JVM) Architecture


The Java Virtual Machine (JVM) is the heart of platform independence.
It provides an execution environment for Java bytecode, which is compiled from Java source
code.
The JVM is responsible for converting the platform-independent bytecode into machine code,
allowing the same Java program to run on different devices and operating systems.

an overview of the JVM architecture, broken down into key components:

1. ClassLoader
Role: The ClassLoader is responsible for loading class files into memory during runtime. Java
programs are compiled into .class files containing bytecode, which the ClassLoader brings into
the JVM.
Functions:
o Loading: It loads classes from different sources like local file systems, remote servers,
or JAR files.
o Linking: This step verifies the bytecode and prepares the class for execution.
o Initialization: This involves assigning default values to static variables and invoking
static blocks.
Types of Class Loaders:
o Bootstrap ClassLoader: Loads core Java libraries (like [Link]).
o Extension ClassLoader: Loads classes from the Java Extensions directory.
o Application ClassLoader: Loads application-level classes.

2. Runtime Data Areas


These are the memory areas used by the JVM during program execution. They are created
when the JVM starts and destroyed when the JVM shuts down.

Method Area:
The Method Area stores class-level information, including the runtime constant pool(constants,
method and field data), code for methods, and constructors.
Heap:
Objects created
using new are stored here. Garbage Collection (GC) is responsible for reclaiming memory from unused objects
in the heap.
Stack:
Each thread in the JVM has its own stack. The stack holds frames, where each frame containslocal variables,
method calls, and partial results. The stack grows and shrinks as methods are invoked and return.
Program Counter (PC) Register:
Each thread has its own PC register, which keeps track of the current instruction being executedby that thread. It
holds the address of the current instruction in the bytecode.
Native Method Stack:
This stack holds native (non-Java) methods written in other languages like C or C++. JNI (JavaNative Interface)
allows the JVM to invoke such methods.

3. Execution Engine

The Execution Engine is responsible for executing the bytecode loaded by the ClassLoader. It
converts bytecode into machine code and handles the actual execution of instructions.

Interpreter:
The interpreter executes the bytecode line-by-line. While it's fast to start, interpreting bytecodecan be slow for
frequently executed code.
Just-In-Time (JIT) Compiler:
The JIT compiler improves performance by compiling frequently executed bytecode (hotspots)into native machine
code at runtime. Once compiled, the native code runs faster than interpreting the bytecode repeatedly.
Garbage Collector (GC):
The GC is responsible for automatic memory management. It reclaims memory used by objectsthat are no longer
referenced by the application, ensuring efficient use of the heap memory.
Java Native Interface (JNI):
JNI provides a way for the JVM to call or be called by native applications and libraries writtenin languages like C
and C++. This is often used when interfacing with system-level resources.

4. Native Method Libraries

interface with underlying system resources.


These libraries are platform-dependent and help execute native methods via the Native Method
Interface.
For example, I/O operations like file handling, which depend on the operating system, are
managed through these libraries.

JVM Execution Flow:

1. Class Loading: When a Java program starts, the ClassLoader loads the necessary class files
into memory.
2. Bytecode Verification: The bytecode verifier ensures that the code adheres to Java's security
constraints and will not harm the JVM or the system it is running on.
3. Execution: The Execution Engine starts interpreting or compiling the bytecode into native
code. During execution, it can switch between interpreting and JIT compilation to optimize
performance.
4. Garbage Collection: The GC periodically frees up memory by reclaiming space from objects
that are no longer in use, ensuring efficient memory management.

Variables

Variable is a named memory location used to store data. Each variable has a specific data type
that determines what kind of values it can hold and what operations can be performed on it.
Variables in Java must be declared before they are used, and they can store different types of
data such as integers, floating-point numbers, characters, and more.
Types of Variables in Java
1. Instance Variables (Non-static Fields):
o Defined within a class but outside of any method, constructor, or block.
o Every instance of the class (object) has its own copy of instance variables.
o These variables are associated with objects, so they are also known as object-level
variables.
o Lifetime: They exist as long as the object exists.
o Default Values: They are assigned default values if not initialized explicitly.
Example:
class Example {

int instanceVar = 10; // Instance variable

2. Static Variables (Class Variables):

Declared with the static keyword.


They belong to the class rather than any individual object, meaning all objects share the same
static variable.
Lifetime: Static variables exist for the entire lifetime of the class.
Default Values: Like instance variables, static variables also have default values if not
initialized.

Example:

class Example {

static int staticVar = 20; // Static variable

}
3. Local Variables:

Declared inside a method, constructor, or block.


They are only accessible within the scope in which they are defined.
Local variables do not have default values, so they must be initialized before use.
Lifetime: They exist only during the execution of the method or block in which they are
declared.
Example:
class Example {
void method() {
int localVar = 30; // Local variable
}
}

4. Parameters:

Variables declared in the method signature are called parameters. They act as inputs to
methods.

Example:
class Example {
void method(int paramVar) { // Parameter variable
[Link](paramVar);
}
}
Declaration and Initialization of Variables
Variables in Java are declared by specifying the data type followed by the variable name.
Optionally, the variable can also be initialized with a value.

Syntax:
dataType variableName = value;
Example:
int age = 25; // Declaration and initializationfloat price; //
Declaration only
price = 99.99f; // Initialization later

What is Declaration and Initialization?


Declaration of a variable in a computer programming language is a statement used to specify the
variable name and its data type. Declaration tells the compiler about the existence of an entity in
the program and its location. When you declare a variable, you should also initialize it.
Initialization is the process of assigning a value to the Variable. Every programming language has
its own method of initializing the variable. If the value is not assigned to the Variable, then the
process is only called a Declaration.

Variable Naming Rules

Variable names must start with a letter (a-z, A-Z), a dollar sign ($), or an underscore (_).
Subsequent characters can be letters, digits (0-9), underscores, or dollar signs.
Java is case-sensitive, so age and Age are different variables.
Keywords cannot be used as variable names (e.g., int class; is invalid).

Scope and Lifetime of Variables

Instance Variables: Accessible throughout the class in instance methods and exist as long as
the object exists.
Static Variables: Accessible throughout the class and across objects, existing as long as the
class is loaded into memory.
Local Variables: Their scope is limited to the block, method, or constructor in which they are
declared, and they exist only during the execution of that block.

Example: Variable Declaration in Java


class Example {
int instanceVar = 10; // Instance variable
static int staticVar = 20; // Static variablevoid
display() {
int localVar = 30; // Local variable
[Link]("Instance Variable: " + instanceVar);
[Link]("Static Variable: " + staticVar);
[Link]("Local Variable: " + localVar);
}
public static void main(String[] args) {
Example obj = new Example();
[Link]();
}
}
Output:
Instance Variable: 10
Static Variable: 20
Local Variable: 30

Key Points

Instance Variables: Unique to each object, shared across instance methods.


Static Variables: Shared across all objects of the class.
Local Variables: Temporary and exist only during method/block execution.
Scope: Defines where the variable can be accessed, and its lifetime depends on the type of
variable.
Data Types in Java
In Java, data types specify the type of values that variables can hold. They are divided into two
main categories: Primitive Data Types and Reference Data Types.

1. Primitive Data Types

Primitive data types are the most basic data types that Java provides.
These are predefined by the language and named by a keyword.
They are used to store simple values. There are eight primitive data types in Java:

a. Integer Types
byte:
o Size: 1 byte (8 bits)
o Range: -128 to 127
o Use case: Useful for saving memory in large arrays.
short:
o Size: 2 bytes (16 bits)
o Range: -32,768 to 32,767
o Use case: Also used to save memory, like byte, but has a larger range.
int:
o Size: 4 bytes (32 bits)
o Range: -2^31 to 2^31 - 1 (-2,147,483,648 to 2,147,483,647)
o Use case: Most commonly used for representing integers in Java.
long:
o Size: 8 bytes (64 bits)
o Range: -2^63 to 2^63 - 1
o Use case: Used when a wider range of integers is needed (e.g., for large calculations).

b. Floating-Point Types
float:
o Size: 4 bytes (32 bits)
o Range: Approximately ±3.40282347E+38F (7 decimal digits)
o Use case: Useful for saving memory in large arrays of floating-point numbers,
especially when high precision isn't required.
double:
o Size: 8 bytes (64 bits)
o Range: Approximately ±1.79769313486231570E+308 (15 decimal digits)
o Use case: Default type for decimal values; used when precision is important.

c. Character Type
char:
o Size: 2 bytes (16 bits)
o Range: 0 to 65,535 (represents Unicode characters)
o Use case: Used to store a single character. It can store any character, including letters,
digits, or special symbols.

d. Boolean Type
boolean:
o Size: Not precisely defined (typically 1 bit, but implementation-specific)
o Values: true or false
o Use case: Used to represent logical values (i.e., true/false conditions). Often used in
conditional statements and loops.

2. Reference Data Types


Reference data types refer to objects and are created using constructors.
Unlike primitive types, reference types do not store the actual value; they store a reference (or
address) to the value.
They can also point to complex data structures like arrays, classes, and interfaces.

a. Classes:
A class is a blueprint for creating objects. Objects of a class can store data (attributes) and have
methods (functions).
Example: String class stores sequences of characters. Example: String name = "Java";
b. Interfaces:
An interface is a contract that classes can implement. It specifies what methods a class should
implement but not the implementation itself.
Example: List is an interface that is implemented by classes like ArrayList and LinkedList.
c. Arrays:
Arrays are objects that store multiple values of the same type in a contiguous memory location.
They can be primitive types or reference types.
Example: int[] numbers = {1, 2, 3, 4};

Summary Table of Primitive Data Types:

Data Type Size Default Value Range / Values Use Case


byte 1 byte 0 -128 to 127 Small integers, memory-saving
short 2 bytes 0 -32,768 to 32,767 Larger ranges than byte
int 4 bytes 0 -2,147,483,648 to 2,147,483,647 Most common integer type
long 8 bytes 0L -2^63 to 2^63 - 1 Very large integer values
Data Type Size Default Value Range / Values Use Case
float 4 bytes 0.0f ~7 decimal digits precision Floating-point numbers
double 8 bytes 0.0d ~15 decimal digits precision Precise floating-point numbers
char 2 bytes '\u0000' 0 to 65,535 Single characters, Unicode
boolean 1 bit false true, false Logical conditions

Class: Template for creating objects.


Interface: Contract that specifies methods to be implemented.
Array: A collection of elements of the same type.

Scope and Lifetime of Variables in Java


In Java, the scope of a variable refers to the region of the program where the variable is
accessible, and the lifetime refers to the duration during which the variable exists in memory.
Understanding the scope and lifetime of variables is important to manage data access and
resource usage efficiently.

1. Types of Variable Scope in Java

a. Local Variables
Definition: A local variable is declared inside a method, constructor, or block.
Scope: The variable is accessible only within the method, constructor, or block where it is
declared.
Lifetime: Local variables are created when the method or block is invoked and destroyed when
the method or block is exited.

Example:

java
Copy code
public void exampleMethod() {
int localVar = 10; // Local variable
[Link](localVar);
}
In this example, localVar exists only within the exampleMethod and cannot be accessed outsideof it.
b. Instance Variables (Non-Static Fields)
Definition: Instance variables are declared inside a class but outside any method or constructor.
They are also known as fields.
Scope: Instance variables are accessible by all methods, constructors, and blocks of the class in
which they are declared. Each object of the class has its own copy of the instance variables.
Lifetime: The lifetime of instance variables coincides with the lifetime of the object. They are
created when the object is created (instantiated) and destroyed when the object is destroyed
(garbage collected).

Example:

public class MyClass


{
int instanceVar = 5; // Instance variablepublic
void printValue()
{
[Link](instanceVar); // Accessible within the class
}
}

Here, instanceVar is an instance variable, and it will be accessible by all methods within theclass MyClass.
c. Static Variables (Class Variables)

Definition: Static variables are declared with the static keyword inside a class but outside any
method or constructor.
Scope: Static variables are accessible by all methods (both static and non-static) and
constructors of the class. Unlike instance variables, static variables are shared among all
instances of the class.
Lifetime: Static variables are created when the class is first loaded into memory (when it is
used for the first time) and destroyed when the class is unloaded (typically when the JVM shuts
down).

Example:
public class MyClass
{
static int staticVar = 10; // Static variable
public static void main(String[] args)
{
[Link](staticVar); // Accessible throughout the class
}
}

In this example, staticVar is a static variable shared by all objects of the class MyClass.

d. Block Variables
Definition: Block variables are declared inside a block of code, such as a loop or an if
statement.
Scope: They are accessible only within the block where they are declared.
Lifetime: Block variables exist only for the duration of the block execution.

Example:

public void exampleMethod()


{
for (int i = 0; i < 5; i++)
{ // `i` is a block variable
[Link](i);
}
// `i` is not accessible here
}
2. Lifetime of Variables

Local Variables: Exist only during the execution of the method, block, or constructor where
they are declared. Memory is allocated when the block is entered and freed when the block is
exited.
Instance Variables: Exist as long as the object they belong to exists. Memory for instance
variables is allocated when an object is instantiated and freed when the object is destroyed
(garbage collected).
Static Variables: Exist for the lifetime of the class in which they are declared. Memory for
static variables is allocated when the class is loaded into memory and is freed when the class is
unloaded (usually when the program terminates).

Example: Combining Scopes

public class ScopeExample


{
static int staticVar = 100; // Static variable (class-level)int
instanceVar = 50; // Instance variable (object-level)public
void methodExample()
{
int localVar = 20; // Local variable (method-level)if
(localVar == 20)
{
int blockVar = 10; // Block variable (block-level)
[Link]("Block variable: " + blockVar);
}
// blockVar is not accessible here
}
public static void main(String[] args)
{
ScopeExample obj = new ScopeExample(); // Object [Link](); //
Method call
[Link]("Static variable: " + staticVar); // Accessible from static context
[Link]("Instance variable: " + [Link]); // Accessible via object
reference
}
}

In this example:
staticVar is a static variable, accessible throughout the class.
instanceVar is an instance variable, tied to each object of ScopeExample.
localVar is a local variable, confined to methodExample().
blockVar is a block variable, confined to the if block.

Arrays in Java
An array in Java is a collection of elements of the same data type stored in contiguous memory
locations.
Arrays provide a way to store multiple values in a single variable, making it easier to work with
groups of related data.
Key Characteristics of Arrays:
Fixed Size: The size of the array is specified when it's created and cannot be changed.
Homogeneous Elements: All elements in an array must be of the same data type (e.g., int[] can
only hold integers).
Indexing: Elements in the array are accessed by their index, starting from 0.

Types of Arrays
1. Single-Dimensional Arrays
2. Multi-Dimensional Arrays (e.g., 2D Arrays)

1. Single-Dimensional Arrays
A single-dimensional array is the most basic form of an array, where data is stored in a single
row.

// Declaration
int[] arr; // Declares an array variable
// Initialization
arr = new int[5]; // Allocates memory for 5 integers
// Declaration and Initialization together int[] arr = new
int[5]; // Array of 5 integers
// Initializing with values
int[] arr = {1, 2, 3, 4, 5}; // Array with 5 elements
Array elements are accessed using their index. Indexes in Java arrays start at 0 and go up to length - 1.
int[] arr = {10, 20, 30, 40, 50};

You can modify elements in an array by assigning new values using their index.
arr[2] = 100; // Changes the third element (index 2) to 100
Example:

public class ArrayExample


{
public static void main(String[] args)
{
int[] numbers = {1, 2, 3, 4, 5};
// Accessing elements
[Link]("First element: " + numbers[0]);
// Changing an element
numbers[2] = 10;
[Link]("Modified third element: " + numbers[2]);
// Loop through the array
for (int i = 0; i < [Link]; i++) { [Link]("Element at index " +
i + ": " + numbers[i]);
}
}
}

2. Multi-Dimensional Arrays
A multi-dimensional array in Java is essentially an array of arrays.
The most commonly used type is the two-dimensional array, which is like a matrix (rows and
columns).

// Declarationint[][]
matrix;
// Initialization
matrix = new int[3][4]; // 3 rows, 4 columns
// Declaration and Initialization together
int[][] matrix = new int[3][4]; // A 2D array with 3 rows and 4 columns
// Initializing with values
int[][] matrix =
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
Elements in a two-dimensional array are accessed using two indices: one for the row and one
for the column.

Example:

public class TwoDArrayExample


{
public static void main(String[] args)
{
int[][] matrix =
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing an element
[Link]("Element at [0][1]: " + matrix[0][1]);
// Loop through the array
for (int i = 0; i < [Link]; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
[Link](matrix[i][j] + " ");
}
[Link](); // New line after each row
}
}
}

Common Operations on Arrays:


1. Finding Length of an Array: Use the .length property to get the number of elements in an
array.
int[] arr = {1, 2, 3, 4, 5};
[Link]("Length: " + [Link]); // Output: 5

2. Traversing Arrays: Arrays can be traversed using loops, such as for, for-each, or while loops.
For Loop:
for (int i = 0; i < [Link]; i++)
{
[Link](arr[i]);
}
Enhanced For Loop (For-Each Loop):
for (int num : arr)
{
[Link](num);
}
3. Copying Arrays: Arrays can be copied using built-in methods like [Link]().

int[] source = {1, 2, 3};


int[] destination = new int[3];
[Link](source, 0, destination, 0, [Link]);

4. Sorting Arrays: Java provides utility methods in the Arrays class for sorting.

int[] arr = {3, 1, 4, 1, 5};


[Link](arr);

Limitations of Arrays:
Fixed Size: Once an array's size is defined, it cannot be changed. If you need a dynamically
resizable array, consider using collections like ArrayList.
Homogeneous: Arrays can only hold elements of the same type. For heterogeneous collections
of objects, you can use Object[] or collections.

Summary:
Single-Dimensional Arrays: A list of elements of the same type stored in contiguous memory.
Multi-Dimensional Arrays: Arrays of arrays, useful for representing data in a tabular form.
Common Operations: Access, modify, traverse, copy, and sort arrays.
Limitations: Fixed size, homogeneous elements. For more flexibility, Java collections like
ArrayList can be used.

Operators in Java
Operators in Java are symbols that perform operations on variables and values.
Java provides several types of operators for different tasks like arithmetic calculations,
logical decisions, comparisons, and more.
Operators are divided into several categories:

1. Arithmetic Operators
These operators are used to perform basic arithmetic calculations.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (Remainder) a%b
Example:
int a = 10;
int b = 5;
[Link](a + b); // Output: 15
[Link](a % b); // Output: 0

2. Relational (Comparison) Operators


These operators are used to compare two values. The result is always true or false.
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
Example:
int a = 10;int
b = 20;
[Link](a == b); // Output: false
[Link](a < b); // Output: true

3. Logical Operators
Logical operators are used to combine multiple conditions (boolean expressions).
Operator Description Example
&& Logical AND a && b
` `
! Logical NOT !a
Example:
boolean a = true; boolean
b = false;
[Link](a && b); // Output: false
[Link](a || b); // Output: true
[Link](!a); // Output: false

4. Assignment Operators
Assignment operators are used to assign values to variables.
Operator Description Example
= Assign a=b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
Example:
int a = 10;
a += 5; // Equivalent to a = a + 5 [Link](a);
// Output: 15

5. Unary Operators
Unary operators are used with a single operand to perform operations like increment,
decrement, negation, etc.
Operator Description Example
+ Unary plus (positive) +a
- Unary minus (negative) -a
++ Increment (pre/post) ++a, a++
-- Decrement (pre/post) --a, a--
! Logical negation !a
Example:
int a = 10;
[Link](++a); // Output: 11 (Pre-increment)
[Link](a--); // Output: 11 (Post-decrement)
[Link](a); // Output: 10
6. Bitwise Operators
Bitwise operators perform operations on bits (binary digits) of integer types.
Operator Description Example
& Bitwise AND a&b
` ` Bitwise OR
^ Bitwise XOR a^b
~ Bitwise NOT ~a
<< Left shift a << 2
>> Right shift a >> 2
>>> Unsigned right shift a >>> 2
Example:
int a = 5; // 0101 in binaryint b = 3; //
0011 in binary
[Link](a & b); // Output: 1 (0001 in binary)
[Link](a | b); // Output: 7 (0111 in binary)

7. Ternary Operator
The ternary operator is a shorthand for an if-else statement. It takes three operands and
evaluates a condition.
Operator Description Example
?: Ternary (conditional) operator condition ? expr1 : expr2
Example:
int a = 10;int b = 20;
int max = (a > b) ? a : b; [Link](max); //
Output: 20

8. Instanceof Operator
The instanceof operator checks if an object is an instance of a specific class or interface.

Example:
String s = "Hello";
[Link](s instanceof String); // Output: true
Summary of Java Operators:
Arithmetic Operators: Perform basic mathematical operations like addition and
multiplication.
Relational Operators: Compare two values and return a boolean result.
Logical Operators: Combine boolean expressions to form complex conditions.
Assignment Operators: Assign values to variables.
Unary Operators: Operate on a single operand, often used for incrementing or negating
values.
Bitwise Operators: Perform bit-level operations on integer types.
Ternary Operator: A concise way to make decisions (if-else).
Instanceof Operator: Checks if an object is an instance of a class.

Control Statements in Java


Control statements in Java allow developers to control the flow of execution based on certain
conditions, loops, or jumps.
These statements help create logical decisions, repeat certain code blocks, or exit from loops
and methods when necessary.

Types of Control Statements:


1. Decision-Making Statements
o if
o if-else
o if-else-if
o switch
2. Looping Statements
o for
o while
o do-while
o Enhanced for (for-each)
3. Jump Statements
o break
o continue
o return

1. Decision-Making Statements

a. if Statement
The if statement executes a block of code if the given condition is [Link]
(condition)
{
// Code to execute if condition is true
}

Example:
int number = 10;if
(number > 5)
{
[Link]("Number is greater than 5.");
}

b. if-else Statement
The if-else statement provides an alternative block of code to execute if the condition is [Link]
(condition)
{
// Code if condition is true
} else
{
// Code if condition is false
}
Example:
int number = 10;if
(number > 15)
{
[Link]("Number is greater than 15.");
} else
{
[Link]("Number is not greater than 15.");
}

c. if-else-if Ladder
This statement is used to check multiple conditions one after [Link]
(condition1)
{
// Code if condition1 is true
} else if (condition2)
{
// Code if condition2 is true
} else
{
// Code if none of the conditions are true
}
Example:
int score = 85; if
(score >= 90)
{
[Link]("A");
} else if (score >= 80)
{
[Link]("B");
} else if (score >= 70)
{
[Link]("C");
} else
{
[Link]("Fail");
}
d. switch Statement
The switch statement is used to select one of many code blocks to execute based on the value ofa
variable.
switch (variable)
{
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
// More cases...
default:
// Default code if no case matches
}

Example:
int day = 2;
switch (day)
{
case 1:
[Link]("Sunday");
break;
case 2:
[Link]("Monday");break;

case 3: [Link]("Tuesday");break;

default:
[Link]("Invalid day");
}
2. Looping Statements

a. for Loop
The for loop is used to execute a block of code a specific number of [Link]
(initialization; condition; update)
{
// Code to execute in each iteration
}

Example:

for (int i = 0; i < 5; i++)


{
[Link]("Iteration: " + i);
}
b. while Loop
The while loop continues to execute a block of code as long as the specified condition is true.

while (condition)
{
// Code to execute while condition is true
}

Example:
int i = 0; while
(i < 5)
{
[Link]("i: " + i);
i++;
}
c. do-while Loop
The do-while loop is similar to the while loop, except that it guarantees that the loop willexecute
at least once, even if the condition is false.
do
{
// Code to execute
} while (condition);
Example:
int i = 0;
do
{
[Link]("i: " + i);
i++;
} while (i < 5);

d. Enhanced for Loop (for-each)


The enhanced for loop (for-each) is used to iterate over arrays or [Link]
(type variable : array)
{
// Code to execute for each element
}
Example:
int[] numbers = {1, 2, 3, 4, 5};for
(int number : numbers)
{
[Link](number);
}

3. Jump Statements

a. break Statement
The break statement is used to exit a loop or switch statement immediately.
Example (in a loop):
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit the loop when i is 5
}
[Link](i);
}

b. continue Statement
The continue statement skips the current iteration of a loop and continues with the next
iteration.
Example:
for (int i = 0; i < 5; i++)
{
if (i == 2)
{
continue; // Skip the rest of the loop body when i is 2
}
[Link](i);
}
c. return Statement
The return statement exits from the current method and can return a value if needed.
Example:
public int add(int a, int b)
{
return a + b; // Return the sum of a and b
}

Decision-Making Statements: Control the flow based on conditions (if, if-else, switch).
Looping Statements: Repeat code based on conditions (for, while, do-while).
Jump Statements: Interrupt normal flow by jumping to another point (break, continue, return).

Type Conversion and Casting in Java


In Java, type conversion refers to converting one data type to another. There are two types of
type conversion: implicit and explicit (or casting).
Understanding type conversion is essential for effective data handling and manipulation in
Java.

1. Implicit Type Conversion (Widening Conversion)


Implicit conversion, also known as widening conversion, occurs when the Java compiler
automatically converts a smaller data type to a larger data type without any explicit instruction
from the programmer.
This typically happens when assigning a value of a smaller data type to a variable of a larger
data type.

Examples of Implicit Conversion:


byte

Example:
int intValue = 100;
long longValue = intValue; // Implicit conversion from int to longfloat floatValue =
intValue; // Implicit conversion from int to float

2. Explicit Type Conversion (Narrowing Conversion or Casting)


Explicit conversion, also known as narrowing conversion or casting, occurs when a larger data
type is converted into a smaller data type.
This requires an explicit cast operator because it can lead to data loss.

Syntax for Casting:


targetType variableName = (targetType) value;

Examples of Explicit Conversion:


double float long int short byte

Example:
double doubleValue = 9.78;
int intValue = (int) doubleValue; // Explicit conversion from double to int
[Link](intValue); // Output: 9 (decimal part is truncated)

float floatValue = (float) doubleValue; // Explicit conversion from double to float


3. Type Conversion Between Primitive and Wrapper Classes
Java provides wrapper classes for each primitive data type, and you can convert between
primitive types and their corresponding wrapper classes using methods provided in these
classes.

Example of Boxing and Unboxing:


Boxing: Converting a primitive type to its corresponding wrapper class.
Unboxing: Converting a wrapper class back to its corresponding primitive type.

Example:
// Boxing
Integer integerValue = [Link](100); // from int to Integer
// Unboxing
int intValue = [Link](); // from Integer to int

4. Type Conversion with Strings


Converting strings to numeric types (and vice versa) is common. To convert a string to a
numeric type, use the wrapper class methods.

Example:
String numberString = "123";
int number = [Link](numberString); // String to int
double doubleNumber = [Link]("123.45"); // String to double
[Link](number); // Output: 123 [Link](doubleNumber); // Output:
123.45
// Converting numeric to string
String strFromInt = [Link](number); // int to String
String strFromDouble = [Link](doubleNumber); // double to String

5. Type Conversion in Expressions


When performing operations with mixed data types, Java applies implicit conversion to avoid
loss of data.
The result type of an expression is determined by the largest data type in the expression.

Example:
int intValue = 10;
double doubleValue = 5.5;
double result = intValue + doubleValue; // int is promoted to double
[Link](result); // Output: 15.5

Summary
Implicit Conversion: Automatic widening conversion from a smaller to a larger data type. No
data loss occurs.
Explicit Conversion (Casting): Narrowing conversion from a larger to a smaller data type,
which requires a cast and may result in data loss.
Wrapper Classes: Boxing and unboxing for converting between primitive types and their
corresponding object types.
String Conversion: Converting between strings and numeric types using wrapper class
methods.
Mixed Expressions: Java applies implicit conversion to the largest data type involved in the
expression.

Simple java program


Here's a simple Java program that demonstrates basic concepts such as defining a class, using
methods, and printing output to the console.
This program calculates the sum of two integers input by the user.

{ // Define a class named SimpleCalculator


// Method to add two numbers
public static int add(int num1, int num2)
{
return num1 + num2; // Return the sum of the two numbers
}
// Main method - entry point of the program
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]); // Create a Scanner object for input
// Prompt user for input
[Link]("Enter the first number: ");
int firstNumber = [Link](); // Read the first number
[Link]("Enter the second number: ");
int secondNumber = [Link](); // Read the second number
// Calculate the sum using the add method int
sum = add(firstNumber, secondNumber);
// Print the result
[Link]("The sum of " + firstNumber + " and " + secondNumber + " is: " + sum);
[Link](); // Close the scanner
}
}

Explanation:
1. Import Statement:
o import [Link]; imports the Scanner class, which is used for obtaining input
from the user.
2. Class Definition:
o public class SimpleCalculator defines a public class named SimpleCalculator.
3. Method:
o The add method takes two integer parameters and returns their sum.
4. Main Method:
o The main method is the entry point of the program. It creates an instance of the Scanner
class to read user input.
oIt prompts the user to enter two integers, calls the add method to calculate the sum, and
then prints the result.
5. Output:
o The program outputs the sum of the two numbers entered by the user.

How to Run the Program:


1. Save the Code: Save the code in a file named [Link].
2. Compile the Program: Open a terminal or command prompt, navigate to the directory where
the file is saved, and run:
javac [Link]

Run the Program: After successful compilation, run the program with:java
SimpleCalculator

1. Input: Follow the prompts to enter two numbers, and the program will display their sum.
This simple program showcases basic Java syntax, user input handling, method definition, and output.

Constructors in Java
Constructors are special methods in Java that are called when an object of a class is created.
They initialize the new object and can set initial values for the object's attributes.
Constructors have the same name as the class and do not have a return type.

Key Features of Constructors:


1. Same Name as Class: The name of the constructor must be the same as the name of the class.
2. No Return Type: Constructors do not have a return type, not even void.
3. Invoked Automatically: Constructors are called automatically when an object is created.
4. Can Be Overloaded: You can have multiple constructors in a class with different parameter
lists (constructor overloading).
5. Default Constructor: If no constructor is defined in a class, Java provides a default constructor
that initializes member variables to their default values.
Types of Constructors:

1. Default Constructor: A constructor that does not take any parameters. It initializes object
attributes to default values.
2. Parameterized Constructor: A constructor that takes parameters to initialize the object with
specific values.

Example of Constructors
class Student
{
// Attributes
String name;
int age;
// Default Constructor
public Student()
{
name = "Unknown";
age = 0;
}
// Parameterized Constructor public
Student(String name, int age)
{
[Link] = name; // 'this' refers to the current [Link] = age;
}
// Method to display student details
public void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
public class Main
{
public static void main(String[] args)
{
// Creating an object using the default constructor
Student student1 = new Student();
[Link]("Student 1 Details:"); [Link](); //
Output: Name: Unknown, Age: 0
// Creating an object using the parameterized constructor
Student student2 = new Student("Alice", 20);
[Link]("\nStudent 2 Details:"); [Link](); //
Output: Name: Alice, Age: 20
}
}
Explanation of the Example:
1. Class Definition:
o The Student class has two attributes: name and age.
2. Default Constructor:
o public Student() initializes the name to "Unknown" and age to 0.
3. Parameterized Constructor:
o public Student(String name, int age) initializes the attributes with values passed as
parameters. The this keyword differentiates between the instance variables and
parameters with the same name.
4. Method to Display Details:
o The display() method prints the values of the name and age attributes.
5. Main Method:
o An object of Student is created using both the default and parameterized constructors,
and their details are displayed.
Key Points:
Constructor Overloading: You can have multiple constructors with different parameters, as
shown in the example with both a default and a parameterized constructor.
The this Keyword: Used in constructors to refer to the current object's attributes when the
parameter names are the same as the attributes.
Object Initialization: Constructors are primarily used to set the initial state of an object during
its creation.
Summary
Constructors are special methods for initializing objects.
They can be default (no parameters) or parameterized (with parameters).
Constructors do not have a return type and are invoked automatically when an object is created.
You can overload constructors to create multiple ways of initializing an object.

Methods in Java
Methods in Java are blocks of code that perform specific tasks.
They allow for code reusability, better organization, and separation of functionality.
A method can take inputs (parameters), perform operations, and may return a result.
Understanding methods is fundamental to Java programming.
Key Features of Methods
1. Method Declaration: A method must be declared before it can be used. It consists of the
method signature, which includes the method name and parameters, followed by the method
body.
2. Return Type: Methods can return a value of a specific type or can be declared as void if they
do not return anything.
3. Parameters: Methods can accept parameters, which are values passed to the method when it is
called.
4. Method Overloading: You can have multiple methods in the same class with the same name
but different parameter lists (different types or number of parameters).

Method Syntax
The general syntax for declaring a method in Java is:
accessModifier returnType methodName(parameterType parameterName1, parameterType
parameterName2, ...)
{
// Method body
}
Example of Methods

overloading:
class Calculator
{
// Method to add two numbers (returns an int)
public int add(int a, int b)
{
return a + b; // Return the sum
}
// Method to add three numbers (overloaded method)
public int add(int a, int b, int c)
{
return a + b + c; // Return the sum of three numbers
}
// Method to multiply two numbers (returns a double)public double
multiply(double a, double b) {
return a * b; // Return the product
}
// Method to display results
public void displayResult(String operation, double result)
{
[Link]("The result of " + operation + " is: " + result);
}
}
public class Main
{
public static void main(String[] args)
{
Calculator calculator = new Calculator(); // Create a Calculator object
// Call the add method with two parametersint sum1 =
[Link](10, 20);
[Link]("addition of 10 and 20", sum1);
// Call the add method with three parametersint
sum2 = [Link](10, 20, 30);
[Link]("addition of 10, 20, and 30", sum2);
// Call the multiply method
double product = [Link](5.5, 4.5);
[Link]("multiplication of 5.5 and 4.5", product);
}
}

Explanation of the Example:

1. Class Definition:
o The Calculator class contains methods that perform different arithmetic operations.
2. Method Declarations:
o public int add(int a, int b): This method adds two integers and returns the result.
o public int add(int a, int b, int c): This overloaded method adds three integers.
o public double multiply(double a, double b): This method multiplies two doubles and
returns the result.
o public void displayResult(String operation, double result): This method displays the
result of an operation but does not return a value.
3. Method Calls:
o In the main method, a Calculator object is created.
o The add method is called with two and three parameters, demonstrating method
overloading.
o The multiply method is called to demonstrate another operation.
o The displayResult method is used to print the results.
Key Points
Access Modifiers: Methods can have access modifiers (like public, private, etc.) that define
their visibility.
Return Type: Indicates the type of value the method will return. If it does not return a value, it
should be declared as void.
Method Overloading: Allows multiple methods with the same name but different parameters,
improving code readability and organization.
Method Parameters: Can be of any type (primitive or object) and can be passed by value (for
primitives) or by reference (for objects).
Summary
Methods are essential for code organization and reusability in Java.
They can take parameters and return values, facilitating various operations.
Understanding method overloading and proper declaration is crucial for effective Java
programming.

Static Blocks in Java

A static block in Java is a block of code that initializes static variables when the class is
loaded.
Static blocks are executed only once when the class is loaded into memory, making them ideal
for initializing static fields that require complex initialization.

Key Features of Static Blocks


1. Executed Once: Static blocks are executed when the class is first loaded, before any instance
of the class is created or any static methods are called.
2. Initialization: They are typically used to initialize static variables or perform other one-time
setup tasks for the class.
3. Multiple Static Blocks: You can have multiple static blocks in a class. They will execute in the
order they are defined in the code.
4. Access to Static Members: Static blocks can access static variables and methods directly.
Syntax
The syntax for a static block is as follows:
static
{
// Code to be executed
}

Example of Static Block


class Example {
// Static variable
static int staticVariable;
// Static block to initialize static variablesstatic {
staticVariable = 10; // Initialize static variable

[Link]("Static block executed. Static variable initialized to " + staticVariable);


}
// Instance variable
int instanceVariable;
// Constructor
public Example(int value) {
instanceVariable = value; // Initialize instance variable
[Link]("Constructor executed. Instance variable initialized to " + instanceVariable);
}
}
public class Main {
public static void main(String[] args) {
[Link]("Creating first object...");
Example example1 = new Example(20); // This will call the constructor and initialize theinstance
variable
[Link]("\nCreating second object...");
Example example2 = new Example(30); // This will call the constructor again
}
}
Explanation of the Example:

1. Class Definition:
o The Example class has a static variable staticVariable and an instance variable
instanceVariable.
2. Static Block:
o The static block initializes staticVariable to 10 and prints a message indicating that the
static block has been executed.
3. Constructor:
o The constructor initializes instanceVariable with the value passed when creating an
object and prints a message.
4. Main Method:
o In the main method, two objects of the Example class are created. When the class is first
loaded, the static block executes only once, followed by the constructor for each object
created.
Output
When you run the program, the output will be:
Static block executed. Static variable initialized to 10Creating first
object...
Constructor executed. Instance variable initialized to 20Creating
second object...
Constructor executed. Instance variable initialized to 30

Key Points
Execution Order: The static block executes before any objects of the class are created and
before any static methods are invoked. In the example, the static block executes before the
constructors.
Usage: Static blocks are often used for complex initialization of static variables, loading
configuration data, or setting up resources that are needed by static methods.
Multiple Static Blocks: If multiple static blocks are present, they execute in the order they
appear in the class.
Summary
Static blocks are a powerful feature in Java for initializing static variables and performing one-
time setup tasks for a class.
They execute only once when the class is loaded, providing a clear and efficient way to manage
static initialization.

Static Data in Java


Static data refers to variables or fields that are shared among all instances of a class.
These variables are declared with the static keyword and belong to the class itself rather than to
any particular instance.
Static data is initialized when the class is loaded and is shared by all instances of that class,
making it useful for defining class-wide properties or counters.
Key Features of Static Data
1. Class-Level Variable: Static variables are associated with the class rather than any specific
object. All instances of the class share the same static variable.
2. Memory Management: Static variables are stored in the static memory area. They are created
when the class is loaded and destroyed when the class is unloaded.
3. Access: Static data can be accessed directly using the class name, which is often considered a
good practice for readability. They can also be accessed via instance references, though this is
less common.
4. Initialization: Static data can be initialized using a static block or directly when declared.
Syntax
The syntax for declaring static data is as follows:class
ClassName
{
static dataType variableName; // Static variable declaration
}

class Counter {
// Static variable to keep track of the number of instancesstatic
int count = 0;
// Constructor
public Counter() {
count++; // Increment count every time a new object is created
}
// Static method to get the current count
public static int getCount() {
return count; // Return the number of instances created
}
}
public class Main {
public static void main(String[] args) {
[Link]("Initial count: " + [Link]()); // Output: 0
// Create instances of Counter
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

// Display the current count


[Link]("Current count after creating objects: " + [Link]()); // Output: 3
}
}

Explanation of the Example:


1. Class Definition:
o The Counter class contains a static variable count to keep track of how many instances
of the class have been created.
2. Constructor:
o Each time a Counter object is instantiated, the constructor increments the static variable
count.
3. Static Method:
o The getCount static method returns the value of count, allowing access to the number of
instances created.
4. Main Method:
o In the main method, we first print the initial count (which is 0), create three instances of
the Counter class, and then print the updated count, which should reflect the number of
instances created.
Output
When you run the program, the output will be:
Initial count: 0
Current count after creating objects: 3
Key Points
Shared State: Static data is shared across all instances of a class, making it useful for tracking
common properties.
Accessing Static Data: It is generally best practice to access static data through the class name,
e.g., [Link](), rather than through instances, e.g., [Link]().
Lifetime: The lifetime of static data extends for the duration of the program, making it
available until the class is unloaded or the program terminates.
Summary
Static data provides a mechanism for sharing data across all instances of a class in Java.
It can be used for counting instances, holding configuration values, or managing shared
resources.
Understanding static data is crucial for effective class design and memory management in Java
applications.

Static Methods in String and StringBuffer Classes in Java

In Java, String and StringBuffer are two important classes used for handling strings, but they
have different characteristics and use cases.
Both classes have several static methods that provide functionality for string manipulation.
an overview of the String and StringBuffer classes, focusing on their static methods.
1. String Class
The String class in Java is used to represent immutable sequences of characters. Once a String
object is created, it cannot be changed.
This immutability makes the String class inherently thread-safe.

[Link](): Converts various types of values (like int, float, char, etc.) to their string
representation.
String str = [Link](100); // "100"
[Link](): Creates a formatted string using the specified format string and arguments.

String formatted = [Link]("Hello, %s! You have %d new messages.", "Alice", 5);
// "Hello, Alice! You have 5 new messages."

[Link](): Joins multiple strings with a specified delimiter.

String result = [Link](", ", "Apple", "Banana", "Cherry");


// "Apple, Banana, Cherry"

[Link](): Creates a new string from the character array.

char[] chars = {'H', 'e', 'l', 'l', 'o'};


String str = [Link](chars); // "Hello"

2. StringBuffer Class

The StringBuffer class is used for mutable sequences of characters.


Unlike String, the StringBuffer object can be modified after it is created, making it suitable for
scenarios where string manipulation is required.

[Link](): Appends the specified string to the end of the current StringBuffer
object.
StringBuffer sb = new StringBuffer("Hello");[Link]("
World"); // "Hello World"
[Link](): Inserts a string into the StringBuffer at a specified index.

StringBuffer sb = new StringBuffer("Hello");[Link](5, "


World"); // "Hello World"

[Link](): Reverses the contents of the StringBuffer.

StringBuffer sb = new StringBuffer("Hello");[Link](); //


"olleH"

[Link](): Deletes a substring from the StringBuffer.

StringBuffer sb = new StringBuffer("Hello World");[Link](5,


11); // "Hello"
Example of Using String and StringBuffer Classes
public class Main {
public static void main(String[] args) {
// Using String class static methods
String name = "Alice";
int age = 30;
// [Link] example

String greeting = [Link]("Hello, %s! You are %d years old.", name, age);
[Link](greeting); // Output: Hello, Alice! You are 30 years old.
// [Link] example
String fruits = [Link](", ", "Apple", "Banana", "Cherry");
[Link](fruits); // Output: Apple, Banana, Cherry
// Using StringBuffer
StringBuffer sb = new StringBuffer();
[Link]("Hello");
[Link](" World");
[Link]([Link]()); // Output: Hello World
[Link](5, ",");
[Link]([Link]()); // Output: Hello, World
[Link]();
[Link]([Link]()); // Output: dlroW ,olleH
}
}

Explanation of the Example


1. String Class:
o The [Link]() method is used to create a formatted string that includes the name
and age.
o The [Link]() method combines multiple strings into one with a specified delimiter.
2. StringBuffer Class:
o A StringBuffer object is created and the append() method is used to add strings.
o The insert() method adds a comma into the StringBuffer.
o Finally, the reverse() method reverses the entire string in the StringBuffer.
Key Points
Immutability vs. Mutability: String is immutable (cannot be changed), while StringBuffer is
mutable (can be changed).
Performance: StringBuffer is generally more efficient for operations that involve many string
manipulations, as it does not create new objects each time a modification is made.
Thread Safety: StringBuffer is synchronized, making it thread-safe for use in multi-threaded
environments.
Summary
The String class provides several useful static methods for manipulating and formatting strings,
while the StringBuffer class offers mutable strings with methods for dynamic manipulation.
Choosing between String and StringBuffer depends on whether you need immutability (use
String) or mutability (use StringBuffer).
MCQ:
1. What is the main principle of Object-Oriented Programming (OOP)?

2. Who is the creator of Java?

3. Which of the following is NOT a Java buzzword?


a) Object-oriented b) Platform-independent c) Slow d) Multithreaded
4. Which component of the JVM is responsible for converting bytecode to machine code?

5. Which of the following is NOT a primitive data type in Java?

6. What is the correct way to declare a variable in Java?

7. What is the scope of a local variable?

8. How do you declare an array in Java?

9. Which of the following operators is used to compare two values?

10. Which control statement is used to exit a loop immediately?

11. Which of the following is NOT a Java buzzword?


a) Platform-independent b) Object-oriented c) Pointers d) Multithreaded
12. What does "platform-independent" mean in the context of Java?
a) Java programs can run on any platform without modification.
b) Java supports all types of hardware.
c) Java requires different versions for different platforms.
d) Java applications cannot be ported to new platforms.
13. Which buzzword refers to ability to manage multiple tasks at once?

14. What is the role of the Class Loader in the JVM?

c) It manages memory. d) It compiles Java code to bytecode.


15. Which of the following components in the JVM is responsible for garbage collection?

16. What does the JVM convert Java bytecode into?

17. Which part of the JVM is responsible for the interpretation and execution of bytecode?

18. Which of the following is a valid primitive data type in Java?


a) String b) Object c) int d) ArrayList
19. Which data type would you use to store a character in Java?

20. What is the default value of a boolean variable in Java?

21. What is the size of an int data type in Java?


22. Which of the following statements is true about static variables?

c) They are local to a method. d) They cannot be accessed by class methods.


23. Where is the scope of a local variable in Java?

c) Within the class it is declared d) Across multiple classes


24. Which of the following is the correct way to declare an array in Java?
a) int[] arr = new int(5); b) int[] arr = new int[5];

25. What is the index of the first element in an array in Java?


a) 0 b) 1 c) -1 d) Depends on the array size
26. What will be the output of the following code?
int[] arr = {1, 2, 3, 4};
[Link](arr[2]);

27. Which statement about arrays in Java is true?


a) Arrays can hold multiple types of data. b) Array size can be changed after initialization.

28. Which operator is used to increment the value of a variable by 1?


29. What is the output of the following code?
int a = 10, b = 5;
int c = a % b;
[Link](c);

30. Which of the following is NOT a relational operator in Java?

31. The conditional (?:) operator in Java is also known as the:

32. Which control statement is used to exit a loop immediately?

33. Which control statement is used to skip the current iteration and move to the next iteration of
a loop?

34. What will the following code print?


int x = 10;if (x > 0) {
[Link]("Positive");
} else {
[Link]("Negative");
}

35. What is typecasting in Java?


c) Automatically converting a smaller data type to a larger one. d) Creating a new data type.
36. What is a constructor in Java?
a) A method that must have the same name as the class b) A method that returns the class object

37. Which of the following is true about constructors?


a) They have a return type. b) They are inherited.

38. Which statement about methods is true?

c) Methods cannot be called from constructors. d) Methods cannot be overloaded.


39. When is a static block executed?

c) When a method is called. d) During compilation.


40. Which keyword is used to declare a static variable?

5 MARK QUESTIONS:

1. Explain the concept of Object-Oriented Programming (OOP) and list its four
fundamentalprinciples.
2. Define any five Java buzzwords and explain their significance.
3. Describe the architecture of the Java Virtual Machine (JVM).
4. Explain different data types in Java with examples.
5. Differentiate between instance variables and static variables in Java.
6. What is the scope and lifetime of variables in Java?
7. Explain arrays in Java and how they are declared and initialized.
8. Describe the differences between break and continue statements in Java with examples.
9. Explain type conversion and casting in Java.

10 MARK QUESTIONS

1. Discuss in detail the four main concepts of Object-Oriented Programming (OOP) with
real-world examples.
2. Trace the history of Java from its development to its current version, highlighting
keymilestones.
3. Describe the Java buzzwords with examples. How do these characteristics make
Java apowerful and versatile programming language?
4. Explain the architecture and working of the Java Virtual Machine (JVM) with a
detaileddiagram.
5. What are data types in Java? Discuss both primitive and reference data types in detail
withexamples.
6. Write a simple Java program demonstrating the use of constructors, methods, and
instancevariables. Explain the output of the program.
7. Explain the differences between static data, static methods, and static blocks in Java
withexamples.
8. Discuss the differences between String and StringBuffer classes in Java.
9. Write a detailed explanation of control flow statements in Java (if, else, switch, for,
while,do-while) with examples.
10. Explain the concept of type conversion and casting in Java with an example program
thatdemonstrates both implicit and explicit casting.

UNIT II
Basic concept:
➢ In Java, inheritance is a core feature of Object-Oriented Programming (OOP) that allows
a new class to acquire properties (fields) and behaviors (methods) from an existing class.
➢ This promotes code reuse and establishes a relationship between classes.
➢ Here's an overview of the basic concepts of inheritance in Java:
1. Superclass (Parent Class)
2. Subclass (Child Class)
3. Inheritance of Methods and Attributes
4. Method Overriding
5. The super() Function
6. Types of Inheritance in Java
7. Multiple Inheritance via Interfaces
8. Constructor Inheritance

Inheritance in Java
➢ Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
➢ The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
➢ When you inherit from an existing class, you can reuse methods and fields of the parent class.
➢ Moreover, you can add new methods and fields in your current class also.

Why use inheritance in java


➢ For Method Overriding (so runtime polymorphism can be achieved)
➢ For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

Java Inheritance Example

Types of inheritance in java

➢ On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
➢ In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.


When one class inherits multiple classes, it is known as multiple inheritance. For Example:
Single Inheritance Example

➢ When a class inherits another class, it is known as a single inheritance.


➢ In the example given below, Dog class inherits the Animal class, so there is the single
inheritance.

File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}

Output:
barking…
eating…

Multilevel Inheritance Example


➢ When there is a chain of inheritance, it is known as multilevel inheritance.
➢ As you can see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}

Output:
weeping…
barking…
eating…

Hierarchical Inheritance Example


➢ When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}

Output:
meowing…
eating…

Why multiple inheritance is not supported in java?


➢ To reduce the complexity and simplify the language, multiple inheritance is not supported
in java.
Consider a scenario where A, B, and C are three classes.
➢ The C class inherits A and B classes.
➢ If A and B classes have the same method and you call it from child class object, there will
be ambiguity to call the method of A or B [Link] compile-time errors are better than
runtime errors, Java renders compile-time error if you inherit 2 classes.
➢ So whether you have same method or different, there will be compile time error.

class A{
void msg(){[Link]("Hello");}
}
class B{
void msg(){[Link]("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
[Link]();//Now which msg() method would be invoked?
}
}

Output:

Compile time error

MEMBER ACCESS RULES


➢ It define how variables, methods, and constructors of a class (members) can be accessed by
other classes, depending on their access modifiers and the relationship between classes.
➢ Access rules determine whether a member of a class is visible or accessible to other classes
within the same package, subclass, or unrelated classes.

1. Access Modifiers in Java

Java provides four types of access levels using the following access modifiers:
Same Same Subclass (Different World (Other
Modifier
Class Package Package) Classes)
private Yes No No No
Same Same Subclass (Different World (Other
Modifier
Class Package Package) Classes)
No Modifier (Package-Private
Yes Yes No No
or Default)
protected Yes Yes Yes No
public Yes Yes Yes Yes
Let's break down the rules for each modifier.

2. Private Members (private)


• Scope: Private members are accessible only within the same class. They are not visible to
other classes, even to subclasses.
• Usage: Used to encapsulate and restrict access to the internal state of a class.
Example:
class Animal {
private String type;
private void makeSound() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
void showType() {
// Cannot access type or makeSound() from Animal here
}
}
3. Default (Package-Private)
• Scope: Members without an explicit access modifier are package-private (default). They
are accessible within the same class and by other classes in the same package but not by
subclasses in different packages.
• Usage: Useful when you want to allow access within the same package but hide it from the
outside world.

class Animal {
String species; // Default access (package-private)
void makeSound() {
[Link]("Animal sound");
}
}
• In this example, species and makeSound() are accessible by any class within the same
package but are not accessible outside of it.

4. Protected Members (protected)


• Scope: Protected members are accessible within the same class, within classes in the same
package, and by subclasses, even if the subclass is in a different package.
• Usage: Used to allow controlled access to members by subclasses while keeping them
hidden from unrelated classes.

Example:
class Animal {
protected String species;
protected void makeSound() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
void showSpecies() {
[Link](species); // Accessible in subclass
}
}
• Here, species and makeSound() are accessible in the Dog class (a subclass), even if Dog is
in a different package.

5. Public Members (public)


• Scope: Public members are accessible everywhere, meaning they are accessible in the same
class, same package, subclasses in different packages, and by any unrelated classes.
• Usage: Used for members that should be accessible by any other class.

Example:

class Animal {
public String name;
public void makeSound() {
[Link]("Animal sound");
}
}
class Dog {
void showName() {
Animal a = new Animal();
[Link]([Link]); // Accessible from any class
[Link](); // Accessible from any class
}
}
• Both name and makeSound() are accessible from any class, regardless of package or class
hierarchy.

6. Accessing Members from Subclasses


• In the same package: Subclasses in the same package can access protected, public, and
default (package-private) members of the superclass.
• In a different package: Subclasses in different packages can access only protected and
public members from the superclass. They cannot access private or package-private
members.

Example with access in different packages:

// In package animals
package animals;
public class Animal {
protected String species = "Unknown";
}
// In package pets
package pets;
import [Link];
public class Dog extends Animal {
void showSpecies() {
[Link](species); // Accessible due to protected access
}
}

7. Member Access from Outside a Class Hierarchy


• When a class is unrelated (neither a subclass nor in the same package), it can access only
public members.

Example

package zoo;
public class Zoo {
public static void main(String[] args) {
Animal a = new Animal();
[Link]([Link]); // Can access only public members
[Link](); // Can access only public members
}
}

8. Final Members and Access


• Final Fields: A final field cannot be changed once initialized. If it is public, it can be
accessed but not modified outside the class.
• Final Methods: A final method cannot be overridden by subclasses.
• Final Classes: A final class cannot be subclassed. For example, String is a final class in
Java.

9. Summary of Access Control

• Private: Only within the same class.


• Default (Package-private): Accessible within the same package.
• Protected: Accessible within the same package and subclasses in other packages.
• Public: Accessible everywhere.
These rules help achieve encapsulation, ensuring that the internal implementation of a class is
hidden and secure, while also allowing flexibility for extending functionality via inheritance and
packages.

Usage of this and Super keyword


❖ The this and super keywords in Java are used to refer to current and parent class members,
respectively.
❖ They are powerful tools for accessing variables, methods, and constructors in the context of
object-oriented programming (OOP), especially when dealing with inheritance and method
overriding.

1. The this Keyword


➢ The this keyword refers to the current instance of the class. It is mainly used to:
• Differentiate between instance variables and parameters when they have the same name.
• Invoke the current class constructor.
• Pass the current class instance to another method or constructor.

Common Usage of this


a) Referring to Instance Variables
When an instance variable and a method parameter have the same name, this is used to refer
to the instance variable (i.e., the one that belongs to the object, not the method parameter).

Example:
class Animal {
String name;
// Constructor with parameter name
Animal(String name) {
[Link] = name; // '[Link]' refers to the instance variable, 'name' refers to the parameter
}
void display() {
[Link]("Animal name: " + [Link]); // Accessing the instance variable
}
}

In this example, [Link] refers to the instance variable, and name on the right side refers to the
constructor parameter.
b) Calling the Current Class Constructor
➢ You can use this() to invoke another constructor in the same class. This is known as
constructor chaining and can help avoid code duplication.

Example:
class Animal {
String name;
int age;
// Constructor 1
Animal(String name) {
this(name, 0); // Calls the second constructor
}
// Constructor 2
Animal(String name, int age) {
[Link] = name;
[Link] = age;
}
void display() {
[Link]("Animal name: " + [Link] + ", age: " + [Link]);
}
}
In this case, this(name, 0) calls the second constructor from the first one, allowing shared
initialization logic.

c) Passing the Current Instance as a Parameter


➢ You can pass the current object (instance) as a parameter to another method or constructor
using this.

Example:
class Dog {
void print(Dog d) {
[Link]("This is a dog.");
}

void callPrint() {
[Link](this); // Passing the current instance
}
}
Here, this refers to the current instance of the Dog class.

2. The super Keyword


➢ The super keyword refers to the parent (superclass) of the current class. It is used to:
• Call the superclass constructor.
• Access superclass methods and variables that have been overridden or hidden by the
subclass.
Common Usage of super
a) Calling the Superclass Constructor
➢ You can use super() to invoke the constructor of the parent class. This is often used when a
subclass needs to initialize fields or perform operations that the parent class does.

Example:
class Animal {
String name;
Animal(String name) {
[Link] = name;
}
}
class Dog extends Animal {
String breed;
Dog(String name, String breed) {
super(name); // Calls the constructor of Animal
[Link] = breed;
}
void display() {
[Link]("Dog name: " + [Link] + ", breed: " + [Link]);
}
}
In this example, super(name) is used to call the constructor of the Animal class, which initializes
the name field.
b) Accessing Superclass Methods
➢ When a method in a subclass overrides a method in its superclass, the subclass can still call
the superclass version of the method using [Link]().

Example:
class Animal {
void sound() {
[Link]("Animal makes a sound.");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link](); // Calls the sound method from Animal
[Link]("Dog barks.");
}
}
Here, [Link]() calls the sound() method from the Animal class, followed by the Dog class's
sound() method.

c) Accessing Superclass Variables


➢ Similarly, super can be used to access variables of the parent class that are hidden by
subclass variables of the same name.

Example:
class Animal {
String name = "Generic Animal";
}
class Dog extends Animal {
String name = "Dog";
void displayNames() {
[Link]("Animal name: " + [Link]); // Refers to Animal's name
[Link]("Dog name: " + [Link]); // Refers to Dog's name
}
}
In this example, [Link] refers to the name variable of the Animal class, while [Link] refers
to the name variable of the Dog class.

Key Differences between this and super:

Keyword Usage Context Refers To Purpose


Current class Refers to instance variables and methods, or calls
this Current class
instance the current class constructor
Subclass with Refers to superclass variables and methods, or
super Parent class
inheritance calls the superclass constructor
Example of this and super Together:
class Animal {
String name;
Animal(String name) {
[Link] = name;
}
void sound() {
[Link]("Animal sound");
}
}
class Dog extends Animal {
String name;
Dog(String name, String animalName) {
super(animalName); // Calls the constructor of Animal
[Link] = name; // Refers to Dog's own name
}
@Override
void sound() {
[Link](); // Calls Animal's sound method
[Link]("Dog barks");
}
void displayNames() {
[Link]("Animal name: " + [Link]); // Refers to Animal's name
[Link]("Dog name: " + [Link]); // Refers to Dog's name
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Buddy", "Generic Animal");
[Link](); // Displays both the animal and dog names
[Link](); // Calls both Animal and Dog's sound method
}
}
Output:

Animal name: Generic Animal


Dog name: Buddy
Animal sound
Dog barks

This example demonstrates how this and super are used together to manage instance variables and
methods in a subclass and its superclass.
Method Overloading
❖ 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.

Different Ways of Method Overloading in Java


• Changing the Number of Parameters.
• Changing Data Types of the Arguments.
• Changing the Order of the Parameters of Methods

Example of Method Overloading


// Java program to demonstrate working of method
// overloading in Java
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);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
}
}
Output
30
60
31.0

Method Overriding
➢ Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent
classes.
➢ When a method in a subclass has the same name, the same parameters or signature, and
the same return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.
➢ Method overriding is one of the ways by which Java achieves Run Time Polymorphism.
➢ The version of a method that is executed will be determined by the object that is used to
invoke it.
➢ If an object of a parent class is used to invoke the method, then the version in the parent
class will be executed, but if an object of the subclass is used to invoke the method, then
the version in the child class will be executed.
➢ In other words, it is 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.
Example of Method Overriding in Java
Below is the implementation of the Java Method Overriding:
// Java program to demonstrate
// method overriding in java
// Base Class
class Parent {
void show() { [Link]("Parent's show()"); }
}
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
[Link]("Child's show()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
[Link]();
// If a Parent type reference refers
// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = new Child();
[Link]();
}
}

Output
Parent's show()
Child's show()

Difference Between Method Overloading and Method Overriding:

Feature Method Overloading Method Overriding


Multiple methods with the same name A method in a subclass has the same
Definition but different signatures within the name and signature as a method in its
same class. superclass.
Polymorphism Compile-time polymorphism (static Run-time polymorphism (dynamic
Type binding). binding).
Feature Method Overloading Method Overriding
Inheritance No inheritance is required. Requires inheritance between classes.
Methods have different signatures
Signature Methods must have the same signature.
(parameters).
Return type must be the same or
Return Type Return type can be different.
covariant.
Access Access level must be the same or less
Can have any access modifier.
Modifiers restrictive.
Static Methods Can be overloaded. Cannot be overridden (only hidden).
Final Methods Can be overloaded. Cannot be overridden.

Abstract Class
❖ An abstract class in Java is a class that cannot be instantiated directly. It is meant to be
inherited by other classes that provide implementations for its abstract methods.
❖ The primary purpose of abstract classes is to provide a template for other classes and
enforce a certain structure or behavior.

Key Features of Abstract Classes:


1. Cannot Be Instantiated: You cannot create an object of an abstract class.
2. Abstract Methods: It can contain abstract methods (methods without a body) that must be
implemented by its subclasses.
3. Concrete Methods: It can also have regular (non-abstract) methods with implementations,
which can be inherited by the subclasses.
4. Inheritance: Abstract classes are designed to be inherited, and the subclass must provide
implementations for all abstract methods.
5. Constructors: Abstract classes can have constructors, but since they cannot be instantiated,
constructors are typically used to initialize fields when a subclass is instantiated.

Syntax of Abstract Class


abstract class Animal {
// Abstract method (no body)
abstract void sound();
// Concrete method
void sleep() {
[Link]("Animal is sleeping");
}
}

Abstract Method
❖ An abstract method is a method that is declared without an implementation (no method
body).
❖ Subclasses of the abstract class must provide an implementation for all abstract methods.

• Declaration: Abstract methods are declared using the abstract keyword.


• No Body: They do not have a method body, just a signature.

abstract class Animal {


// Abstract method (does not have a body)
abstract void sound();
}
Example of Abstract Class and Abstract Methods
// Abstract class
abstract class Animal {
// Abstract method (must be implemented by subclass)
abstract void sound();

// Concrete method
void sleep() {
[Link]("Animal is sleeping");
}
}
// Subclass that extends the abstract class
class Dog extends Animal {
// Provide implementation for abstract method
@Override
void sound() {
[Link]("Dog barks");
}
}
// Subclass that extends the abstract class
class Cat extends Animal {
// Provide implementation for abstract method
@Override
void sound() {
[Link]("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Create a Dog object
Animal myCat = new Cat(); // Create a Cat object
[Link](); // Calls Dog's implementation of sound()
[Link](); // Inherited from Animal class
[Link](); // Calls Cat's implementation of sound()
[Link](); // Inherited from Animal class
}
}

Output:
Dog barks
Animal is sleeping
Cat meows
Animal is sleeping

Key Points about Abstract Classes


1. Abstract Classes Can Have Both Abstract and Non-Abstract Methods
2. Abstract Classes Cannot Be Instantiated
3. Subclasses Must Implement All Abstract Methods
4. Can Have Constructors
5. Abstract Classes Can Have Fields
Abstract Class vs Interface

Feature Abstract Class Interface


Can have both abstract and concrete All methods are abstract by default
Methods
methods. (until Java 8).
Cannot have instance variables
Fields Can have instance variables (fields).
(only constants).
Supports multiple inheritance (a
Supports single inheritance (a class
Inheritance class can implement multiple
can extend only one abstract class).
interfaces).
Default Can provide default method From Java 8 onwards, interfaces can
Implementations implementations. also have default and static methods.
Can have any access modifier (public,
Access Modifiers All methods are public by default.
protected, private).
Instantiation Cannot be instantiated. Cannot be instantiated.

Dynamic Method Dispatch in Java


❖ Dynamic method dispatch is the process in Java where a call to an overridden method is
resolved at runtime rather than at compile-time.
❖ This is one of the key features of runtime polymorphism in Java. It allows the JVM to
determine at runtime which version of a method (in the superclass or subclass) should be
invoked based on the actual object type, even when the reference type is of the superclass.
In simpler terms, when a method is overridden in a subclass, and you have a reference variable of
the superclass, Java uses dynamic dispatch to determine the actual method to execute (based on
the object referred to) at runtime.

❖ Method overriding is one of the ways in which Java supports Runtime Polymorphism.
❖ 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.
• 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.

Therefore, if a superclass contains a method that is overridden by a subclass, then when different
types of objects are referred to through a superclass reference variable, different versions of the
method are executed.

How Dynamic Method Dispatch Works


1. Method Overriding: This concept only works with method overriding. The subclass
overrides a method from the superclass.
2. Superclass Reference, Subclass Object: A reference variable of the superclass can hold a
reference to an object of the subclass (this is called upcasting).
3. Actual Method Invoked at Runtime: When a method is called using the superclass
reference, the JVM checks the actual object type at runtime and invokes the overridden
method in the subclass (if present), not the method in the superclass.

Example of Dynamic Method Dispatch


class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal; // Reference of superclass
myAnimal = new Dog(); // myAnimal refers to Dog object
[Link](); // Calls Dog's sound method
myAnimal = new Cat(); // myAnimal refers to Cat object
[Link](); // Calls Cat's sound method
}
}

Output:
Dog barks
Cat meows

Explanation:
• myAnimal is a reference of type Animal (superclass) but refers to different subclass objects
(Dog and Cat).
• Even though myAnimal is of type Animal, the method that gets called depends on the actual
object type (Dog or Cat), not the reference type.
• This is dynamic method dispatch in action, where the method to execute is decided at
runtime.

Why Use Dynamic Method Dispatch?


• Runtime Polymorphism: It enables the use of polymorphism where objects of different
classes can be treated as objects of a common superclass, allowing for flexible and reusable
code.
• Extensibility: It helps in designing applications that can easily be extended by adding new
subclasses with their own specific behavior without modifying existing code.

Usage of the final Keyword in Java

❖ The final keyword in Java is used to restrict the modification of classes, methods, and
variables. Once something is declared final, its behavior or value cannot be changed.

❖ Java final keyword is a non-access specifier that is used to restrict a class, variable, and
method. If we initialize a variable with the final keyword, then we cannot modify its value.

❖ If we declare a method as final, then it cannot be overridden by any subclasses. And, if we


declare a class as final, we restrict the other classes to inherit or extend it.
1. Final Variables
❖ A variable declared with the final keyword becomes a constant, meaning its value can only
be assigned once, and after assignment, it cannot be modified.

final int MAX_SPEED = 120;

• Once a final variable is assigned a value, it cannot be changed.


• It is typically used for constants.

2. Final Methods
❖ A method declared as final cannot be overridden by any subclass.

class Animal {
final void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
// This will cause a compile-time error
// void sound() {
// [Link]("Dog barks");
// }
}

• The final keyword prevents any subclass from modifying the behavior of the sound()
method.
• This is useful when you want to lock the method's behavior and prevent subclasses from
changing it.

3. Final Classes
❖ A class declared as final cannot be extended (i.e., no class can inherit from it).

final class Animal {


void sound() {
[Link]("Animal makes a sound");
}
}

// This will cause a compile-time error


// class Dog extends Animal {
// void sound() {
// [Link]("Dog barks");
// }
// }

• A final class prevents inheritance, making the class behavior constant and unmodifiable.
• Examples in Java include the String class, which is final, meaning no one can extend the
String class to alter its functionality.

Key Uses of the final Keyword


1. Final Variables: Used to define constants whose values should not change.
2. Final Methods: Prevent method overriding to maintain the original method behavior.
3. Final Classes: Prevent class inheritance to ensure the class design is not modified by
subclasses.

Packages in Java
❖ A package in Java is a way to organize and group related classes and interfaces together.
❖ It helps manage large codebases by categorizing similar types of classes into different
namespaces, avoiding naming conflicts, and making code more modular, reusable, and
maintainable.
❖ Java has a vast standard library of classes, interfaces, and exceptions grouped into packages
(like [Link], [Link], etc.), and developers can also create custom packages.

Key Benefits of Using Packages:


1. Namespace Management: Packages prevent naming conflicts by providing separate
namespaces for classes.
2. Modularity: Related classes and interfaces can be grouped logically.
3. Access Control: Packages provide mechanisms to control access to classes and methods
using access modifiers (like public, private, protected).
4. Code Reusability: Classes in a package can be easily reused by importing the package.
5. Class Organization: Large projects can be managed effectively by grouping related classes
into different packages.

Defining a Package
❖ To declare that a class is part of a package, use the package keyword at the top of the Java
file, followed by the package name.
❖ The file should also be saved in a directory structure that matches the package name.

Syntax:
package package_name;

Example:
package [Link];
public class Dog {
public void bark() {
[Link]("Dog barks");
}
}
In this example:
• The class Dog is in the [Link] package.
• The source file [Link] must be saved in a directory structure like com/example/animals/.

Types of Packages in Java

1. Built-in Packages: Java provides several built-in packages like [Link], [Link], [Link],
etc. These packages contain various classes and interfaces to perform basic tasks.
o Example: [Link], [Link].
2. User-defined Packages: These are custom packages created by developers to organize their
own classes and interfaces logically.
o Example: [Link].

Access Protection in Java Packages


❖ Java provides access control mechanisms to protect data and methods within packages
using access modifiers. The access levels in Java are:

Same Same Subclass (Different Other


Modifier
Class Package Package) Packages
public Yes Yes Yes Yes
protected Yes Yes Yes No
default (no
Yes Yes No No
modifier)
private Yes No No No

1. Public: The class, method, or variable is accessible from anywhere.


o If a class is declared public, it can be accessed from any other class, regardless of the
package.
Example:

public class Dog {


public void bark() {
[Link]("Dog barks");
}
}
2. Protected: Methods or variables are accessible within the same package and by subclasses
in other packages.
• Protected access allows subclasses to inherit methods and variables but restricts access to
other classes outside the package.

Example
protected class Animal {
protected void eat() {
[Link]("Animal eats");
}
}
3. Default (Package-private): When no access modifier is specified, the member is accessible
only within the same package. This is known as package-private access.
• Default access helps keep internal functionality within a package without exposing it to
other packages.

Example
class Cat {
void meow() {
[Link]("Cat meows");
}
}
4. Private: The member is only accessible within the same class. Private members cannot be
accessed from outside the class, not even by classes in the same package or subclasses.

Example
class Lion {
private void roar() {
[Link]("Lion roars");
}
}

Importing Packages
❖ To use classes or interfaces from a different package, you need to import them into your
Java file.
❖ The import statement makes the specified package classes available for use in the current
class.

Syntax of Importing:
1. Single Class Import:
o This imports a specific class from a package.
import package_name.ClassName;
Example:
import [Link];
2. Wildcard Import:
• This imports all the classes and interfaces from a package.
import package_name.*;

Example:
import [Link].*;

Example of Using Imported Packages:


// Importing a built-in package
import [Link];
public class Main {
public static void main(String[] args) {
// Using the ArrayList class from [Link] package
ArrayList<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link](list);
}
}

Importing User-defined Packages:


// File: com/example/animals/[Link]
package [Link];
public class Dog {
public void bark() {
[Link]("Dog barks");
}
}
// File: com/example/[Link]
package [Link];
// Importing the custom package
import [Link];
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
}
}

Packages and Access Control


Access control across packages is determined by the use of access modifiers:
• Public members: Accessible from any class in any package.
• Protected members: Accessible within the same package and by subclasses in other
packages.
• Default members: Accessible only within the same package (also known as package-
private).
• Private members: Accessible only within the same class.
Interfaces in Java
❖ An interface in Java is a reference type, similar to a class that can contain only constants,
method signatures (abstract methods), default methods, static methods, and nested types.
Interfaces are used to achieve abstraction and multiple inheritance in Java.

Key Characteristics of an Interface:


• All methods in an interface are implicitly abstract (until Java 7) unless they are explicitly
defined as default or static (starting from Java 8).
• An interface cannot have instance fields (i.e., variables). It can only have constants
(variables that are both public, static, and final by default).
• Methods in an interface are implicitly public and abstract.
• A class can implement multiple interfaces, which helps achieve multiple inheritance in
Java.

Defining an Interface
You define an interface using the interface keyword, followed by the method declarations
without bodies.

Syntax:

interface InterfaceName {
// Method signatures (implicitly public and abstract)
void method1();
void method2();
}
Example of an Interface:

interface Animal {
void eat(); // Abstract method
void sleep(); // Abstract method
}

In this interface Animal:

• It declares two methods: eat() and sleep(), but they don't have any implementations (they
are abstract).
• Any class that implements the Animal interface must provide concrete implementations of
these methods.

Implementing an Interface
❖ A class that implements an interface must provide implementations for all the abstract
methods declared in the interface. To implement an interface, the class uses the implements
keyword.

Syntax:
class ClassName implements InterfaceName {
// Provide implementation of all abstract methods from the interface
public void method1() {
// method body
}
public void method2() {
// method body
}
}
Example of a Class Implementing an Interface:
interface Animal {
void eat(); // Abstract method
void sleep(); // Abstract method
}
class Dog implements Animal {
@Override
public void eat() {
[Link]("Dog eats bones");
}
@Override
public void sleep() {
[Link]("Dog sleeps");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Output: Dog eats bones
[Link](); // Output: Dog sleeps
}
}
Explanation:
• The Dog class implements the Animal interface by providing concrete implementations for
the eat() and sleep() methods.
• An object of the Dog class can then call these methods.

Multiple Interfaces:
A class can implement multiple interfaces in Java, which helps achieve multiple
inheritance.

Example
interface Animal {
void eat();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
@Override
public void eat() {
[Link]("Dog eats");
}
@Override
public void play() {
[Link]("Dog plays");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Output: Dog eats
[Link](); // Output: Dog plays
}
}

Explanation:
• The class Dog implements both the Animal and Pet interfaces, providing implementations
for methods from both interfaces.
• This allows Dog to have behaviors from both interfaces.

Extending Interfaces
❖ Just like classes, interfaces can extend other interfaces. When an interface extends another
interface, it inherits all the abstract methods of the parent interface. The child interface can
declare its own additional methods as well.

Syntax:
interface ParentInterface {
void method1();
}
interface ChildInterface extends ParentInterface {
void method2();
}
Explanation:
• The Mammal interface extends the Animal interface, meaning it inherits the eat() method.
• The Mammal interface also defines a new method walk().
• The Dog class implements the Mammal interface, which means it must provide
implementations for both eat() and walk().

Exception Handling in Java


❖ Exception handling in Java is a mechanism to handle runtime errors, ensuring the normal
flow of a program even when exceptions occur.
❖ An exception is an event that disrupts the normal flow of the program and can occur during
runtime (such as division by zero, accessing an out-of-bounds array element, etc.).
❖ Java provides a powerful way to handle these exceptions using try-catch blocks, along with
keywords like throw, throws, and finally.

Key Concepts in Exception Handling

1. Exception: An unwanted or unexpected event that occurs during the execution of a


program.
2. Exception Handling: The process of handling exceptions and ensuring the normal flow of
a program.

try-catch Block

The try block contains the code that might throw an exception, and the catch block is used
to handle the exception. If an exception occurs in the try block, it is caught and handled in the catch
block.

Syntax:

try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Example:
public class Main {
public static void main(String[] args) {
try {
int data = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
}
}
}
Output:
Cannot divide by zero!

throw Keyword

The throw keyword is used to explicitly throw an exception in Java. You can throw either
checked or unchecked exceptions. The exception object is created using the new keyword.
Syntax:
throw new ExceptionType("Error Message");
Example:

public class Main {


public static void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
[Link]("Eligible to vote");
}
}
public static void main(String[] args) {
validateAge(16); // This will throw an ArithmeticException
}
}

Output:
Exception in thread "main" [Link]: Not eligible to vote
return_type method_name() throws ExceptionType1, ExceptionType2 {
// Method code
}

Example:
import [Link].*;
public class Main {
public static void readFile() throws IOException {
FileReader file = new FileReader("[Link]");
BufferedReader fileInput = new BufferedReader(file);
[Link]();
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
[Link]("File not found");
}
}
}

In this example, the readFile method declares that it throws an IOException. The calling method
main() handles it using a try-catch block.

finally Block

❖ The finally block is used to execute important code such as closing resources, regardless of
whether an exception is thrown or caught.
❖ It always executes, even if an exception occurs or a return statement is used inside the try or
catch block.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}

Example:
public class Main {
public static void main(String[] args) {
try {
int data = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
} finally {
[Link]("Finally block is executed");
}
}
}
Output:

Cannot divide by zero


Finally block is executed

The finally block runs regardless of whether the exception is caught or not.

Built-in Exceptions in Java


❖ Java provides several built-in exceptions that are part of the [Link] package. They are
classified into two types:
1. Checked Exceptions: These are the exceptions that are checked at compile-time. The
programmer must handle these exceptions explicitly.
o Examples:
▪ IOException
▪ SQLException
▪ ClassNotFoundException
2. Unchecked Exceptions: These are the exceptions that occur at runtime and are not checked
at compile-time.
o Examples:
▪ ArithmeticException
▪ NullPointerException
▪ ArrayIndexOutOfBoundsException
Common Built-in Exceptions:

Exception Description
Thrown when an arithmetic error occurs (e.g., divide by
ArithmeticException
zero).
Thrown when trying to access an index that is out of bounds
ArrayIndexOutOfBoundsException
in an array.
Thrown when an application attempts to use null where an
NullPointerException
object is required.
IOException Thrown when an I/O operation fails or is interrupted.
Thrown when an attempt to open the file denoted by a
FileNotFoundException
specified pathname has failed.
Exception Description
Thrown when an application tries to load a class but no
ClassNotFoundException
definition for the class is found.
Thrown when an attempt to convert a string to a numeric type
NumberFormatException
fails.
Creating Your Own Exception Classes

Java allows developers to create custom exceptions by extending the Exception class or its
subclasses.
Steps to Create a Custom Exception:

1. Extend the Exception class (or a subclass of it).


2. Define a constructor that passes an error message to the super() constructor of Exception.
3. Throw the custom exception using the throw keyword when necessary.

Summary of Exception Handling:


1. try: Block of code where an exception can occur.
2. catch: Block of code that handles the exception.
3. throw: Used to explicitly throw an exception.
4. throws: Declares that a method can throw exceptions.
5. finally: Block of code that always executes, regardless of exceptions.
6. Built-in Exceptions: Java provides several built-in exceptions for common error scenarios
(e.g., ArithmeticException, NullPointerException).
7. Custom Exceptions: You can create your own exception classes by extending the
Exception class.

Creating own Exception classes


❖ An exception is an issue (run time error) that occurred during the execution of a program.
When an exception occurred the program gets terminated abruptly and, the code past the line
that generated the exception never gets executed.
❖ Java provides us the facility to create our own exceptions which are basically derived classes
of Exception.
❖ Creating our own Exception is known as a custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user
needs.
❖ In simple words, we can say that a User-Defined Exception or custom exception is creating
your own exception class and throwing that exception using the ‘throw’ keyword.

Following are a few of the reasons to use custom exceptions:

• To catch and provide specific treatment to a subset of existing Java exceptions.

• Business logic exceptions: These are the exceptions related to business logic and workflow. It
is useful for the application users or the developers to understand the exact problem.
MCQ’S
1. What is inheritance in Java?
A) A mechanism that allows one class to acquire properties of another class.
B) A mechanism to hide data from unauthorized access.
C) A method to increase the size of a class.
D) A technique to convert one type into another.
2. Which of the following is not a type of inheritance in Java?
A) Single Inheritance B) Multiple Inheritance (using classes)
C) Multilevel Inheritance D) Hierarchical Inheritance
3. Which keyword is used to inherit a class in Java?
A) implements B) extends C) inherits D) super
4. In Java, which member has the least accessibility?
A) public B) protected C) private D) default (package-private)
5. Which of the following is true regarding member access in inheritance?
A) Private members are inherited and can be accessed directly.
B) Protected members can be accessed in derived classes.
C) Public members cannot be inherited.
D) Default members can be accessed from any class in any package.
6. Which of the following best describes the usage of the this keyword in Java?
A) Refers to the current class constructor B) Refers to the current object instance
C) Refers to the parent class constructor D) Refers to the parent object instance
7. What does the super keyword do in Java?
A) Refers to the current object B) Refers to the parent class constructor and members
C) Refers to the child class methods D) Refers to static methods only
8. Method overloading is an example of which of the following?
A) Compile-time polymorphism B) Runtime polymorphism
C) Data abstraction D) Encapsulation
9. What is method overloading?
A) When two methods have the same name but different return types
B) When two methods have the same name but different argument lists
C) When two methods have the same signature but different return types
D) When a child class method has the same name as a parent class method
10. What is method overriding?
A) When two methods have the same name but different argument lists
B) When a subclass provides a specific implementation of a method that is already
defined by its parent class
C) When a class has multiple constructors with the same name
D) When two methods have the same name but different return types
11. What is the purpose of an abstract class in Java?
A) To define concrete methods only
B) To provide a blueprint for other classes, containing both abstract and concrete
methods
C) To instantiate objects
D) To support multiple inheritance
12. Which of the following is true about abstract classes?
A) You can create an instance of an abstract class.
B) An abstract class must contain at least one abstract method.
C) All methods in an abstract class must be abstract.
D) A class that extends an abstract class must implement all abstract methods of the
parent class.
13. What is dynamic method dispatch?
A) A process where a method is called based on the object type at compile-time.
B) A process where a method is called based on the object type at runtime.
C) A technique for overloading methods.
D) A technique to handle multiple inheritance.
14. What is the primary use of the final keyword when applied to a method?
A) The method cannot be overloaded.
B) The method cannot be overridden by subclasses.
C) The method can only be used by subclasses.
D) The method can be used with abstract classes.
15. What does it mean when a class is declared as final?
A) It cannot have a constructor. B) It cannot be subclassed.
C) It cannot implement an interface. D) It cannot have any variables.
16. Can a final class be extended in Java?
A) Yes, by any class. B) Yes, but only in the same package.
C) No, a final class cannot be extended. D) Yes, but only by one class.
17. Which of the following cannot be overridden in Java?
A) Static methods B) Final methods C) Both A and B D) Private methods
18. What is a package in Java?
A) A group of related classes and interfaces. B) A method to hide data.
C) A group of objects. D) A collection of constants.
19. Which of the following is a valid package declaration?
A) import [Link].*; B) package [Link].*;
C) package [Link]; D) class package [Link];
20. Which keyword is used to import a package in Java?
A) include B) using C) package D) import
21. What access level do members of a class have if no modifier is specified?
A) public B) protected C) private D) package-private (default)
22. Which of the following allows access to members within the same package?
A) public B) private C) protected D) package-private (default)
23. Which of the following is NOT a valid import statement?
A) import [Link].*; B) import [Link];
C) import static [Link].*; D) import package [Link];
24. What is an interface in Java?
A) A class that contains only concrete methods. B) A collection of abstract methods.
C) A class that cannot be extended. D) A class with final methods.
25. Which of the following is true about interfaces in Java?
A) An interface can contain only abstract methods.
B) An interface can contain both abstract methods and default methods.
C) A class can implement multiple interfaces but can extend only one interface.
D) A class cannot implement an interface.
26. What is the keyword used to implement an interface in Java?
A) extends B) implement C) implements D) interface
27. Can an interface extend multiple interfaces?
A) No, an interface can extend only one interface.
B) Yes, an interface can extend multiple interfaces.
C) An interface cannot extend another interface.
D) An interface must extend a class.
28. Which of the following is not allowed in an interface?
A) Abstract methods B) Default methods C) Static methods D) Instance variables
29. What is the default access modifier for methods declared inside an interface?
A) public B) private C) protected D) default (package-private)
30. What is exception handling in Java?
A) A method to hide data. B) A mechanism to handle runtime errors.
C) A mechanism to handle compile-time errors. D) A process of error-free coding.
31. Which block must be used with the try block?
A) finally B) throw C) catch D) throws
32. Which keyword is used to explicitly throw an exception in Java?
A) throws B) throw C) catch D) final
33. Which keyword is used to declare that a method might throw an exception?
A) throw B) catch C) throws D) final
34. What is the purpose of the finally block in Java?
A) It is executed when no exception is thrown.
B) It is executed only if an exception is thrown.
C) It is executed regardless of whether an exception occurs or not.
D) It is optional and executed if the program terminates abnormally.
35. Which of the following is a checked exception in Java?
A) ArithmeticException B) NullPointerException
C) FileNotFoundException D) ArrayIndexOutOfBoundsException
36. Which of the following exceptions is an unchecked exception?
A) IOException B) SQLException
C) ClassNotFoundException D) ArithmeticException
37. What is the base class for all exceptions in Java?
A) [Link] B) [Link]
C) [Link] D) [Link]
38. What is the correct order of exception handling blocks in Java?
A) try → catch → throw B) try → finally → catch
C) try → catch → finally D) throw → try → catch
39. What will happen if an exception is thrown in a try block and is not caught?
A) The program continues running. B) The program terminates abnormally.
C) The program will compile but won't execute.D) The program executes the catch block.
40. Which block is executed even if an exception is not caught in the catch block?
A) catch B) finally C) throw D) throws
41. When does Exceptions in Java arises in code sequence?
a) Run Time b) Compilation Time
c) Can Occur Any Time d) none of the mentioned
42. Which of these keywords is not a part of exception handling?
a) try b) finally c) thrown d) catch
43. What will be the output of the following Java program?

1. class exception_handling
2. {
3. public static void main(String args[])
4. {
5. try
6. {
7. [Link]("Hello" + " " + 1 / 0);
8. }
9. catch(ArithmeticException e)
10. {
11. [Link]("World");
12. }
13. }
14. }
a) Hello b) World c) HelloWorld d) Hello World
44. Which of the following handles the exception when a catch is not used?
a) finally b) throw handler c) default handler d) java run time system
45. Which part of code gets executed whether exception is caught or not?
a) finally b) try c) catch d) throw
46. Which of the following should be true of the object thrown by a thrown statement?
a) Should be assignable to String type b) Should be assignable to Exception type
c) Should be assignable to Throwable type d) Should be assignable to Error type
47. At runtime, error is recoverable.
a) True b) False
48. Which of these is a super class of all exceptional type classes?
a) String b) RuntimeExceptionsc) Throwable d) Cacheable
49. Which of these class is related to all the exceptions that cannot be caught?
a) Error b) Exception c) RuntimeExecption d) All of the mentioned
50. Which of these handles the exception when no catch is used?
a) Default handler b) finally c) throw handler d) Java run time system

5 MARKS QUESTIONS
1. Explain the basic concept of inheritance in Java.
2. What are the different types of inheritance supported in Java?
3. Explain the difference between method overloading and method overriding.
4. Describe the use of the this and super keywords in Java.
5. What is an interface in Java and how is it implemented?

10 MARK QUESTIONS
1. Explain the concept of dynamic method dispatch in Java with an example.
2. Discuss the access protection mechanism in Java packages.
3. Explain exception handling in Java using try, catch, finally, throw, and throws.
4. What are abstract classes in Java, and how do they differ from interfaces?
5. How can you create custom exceptions in Java, and what are the built-in exception classes

UNIT - III
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the main
program.

Creating a Thread
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
public class Main extends Thread {
public void run() {
[Link]("This code is running in a thread");
}
}
Another way to create a thread is to implement the Runnable interface:
Implement Syntax
public class Main implements Runnable
{ public void run() {
[Link]("This code is running in a thread");
}
}

Running Threads
If the class extends the Thread class, the thread can be run by creating an instance of the class and call
its start() method:
Extend Example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
[Link]();
[Link]("This code is outside of the thread");
}
public void run() {
[Link]("This code is running in a thread");
}
}
If the class implements the Runnable interface, the thread can be run by passing an instance of the class
to a Thread object's constructor and then calling the thread's start() method:
Implement Example
public class Main implements Runnable { public static void
main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj); [Link]();
[Link]("This code is outside of the thread");
}
public void run() {
[Link]("This code is running in a thread");
}
}
Differences between "extending" and "implementing" Threads
The major difference is that when a class extends the Thread class, you cannot extend any other
class, but by implementing the Runnable interface, it is possible to extend from another class as
well, like: class MyClass extends OtherClass implements Runnable.

public void run() { amount++;


}
}
Inter-thread Communication in Java
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the same critical section to be
[Link] is implemented by following methods of Object class:
o wait()
o notify()
o notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from the synchronized method
only otherwise it will throw exception.
Method Description

public final void wait()throws


It waits until object is notified.
InterruptedException

public final void wait(long


It waits for the specified amount
timeout)throws
of time.
InterruptedException

2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads
are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at
the discretion of the implementation.
Syntax:
1. public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
1. public final void notifyAll()
Understanding the process of inter-thread communication
The point to point explanation of the above diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases
the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.
Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
It is because they are related to lock and object has a lock.
Difference between wait and sleep?

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release

the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or After the specified amount of time,

notifyAll() methods sleep is completed.


Example of Inter Thread Communication in Java

[Link]
1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. [Link]("going to withdraw..."); 6.
7. if([Link]<amount){
8. [Link]("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. [Link]-=amount;
12. [Link]("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. [Link]("going to deposit...");
17. [Link]+=amount;
18. [Link]("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){[Link](15000);}
28. }.start();
29. new Thread(){
30. public void run(){[Link](10000);}
31. }.start();
32.
33. }}
34.
Output:

going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Definition and Usage of synchronization


The synchronized keyword is a modifier that locks a method so that only one thread can use it at a time.
This prevents problems that arise from race conditions between threads.
In the example above, removing the synchronized keyword from
the transfer() method may cause the values of a and b to be modified by another thread in between
operations. This would result in the total amount between the two variables to change.
Example
Use the synchronized modifier to prevent race conditions between threads:
public class Main implements Runnable { public static int a,
b;

public static void main(String[] args) {


a = 100;
b = 100;
// Check the total amount shared between a and b before the transfers [Link]("Total before: " + (a +
b));
// Run threads which will transfer amounts between a and b Thread thread1 = new
Thread(new Main());
Thread thread2 = new Thread(new Main());
[Link]();
[Link]();
// Wait for the threads to finish running try {
[Link](); [Link]();
} catch (InterruptedException e) { [Link]();
}
// Check the total amount shared between a and b after the transfers
// It should be the same amount as before
[Link]("Total after: " + (a + b));
}
public void run() {
for (int i = 0; i < 10000000; i++) { transfer();
}
}
public static synchronized void transfer() {
// Choose a random amount to transfer
int amount = (int) (5.0 * [Link]());
// Transfer between a and b if (a > b) {
a -= amount;
b += amount;
} else {
a += amount;
b -= amount;
}
}
Java Files
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files.

Java File Handling


The File class from the [Link] package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name:
ExampleGet your own Java Server
import [Link]; // Import the File class

File myObj = new File("[Link]"); // Specify the filename


If you don't know what a package is, read our Java Packages Tutorial.
The File class has many useful methods for creating and getting information about files.
For example:
Method Type Description
canRead()
Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile()
Boolean Creates an empty file

delete() Boolean Deletes a file

exists()
Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath()
String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes

list()
String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory

Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value:
true if the file was successfully created, and false if the file already exists. Note that the method is
enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if
the file cannot be created for some reason):
Example
import [Link]; // Import the File class
import [Link]; // Import the IOException class to handle
errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("[Link]");
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}
The output will be:
File created: [Link]
To create a file in a specific directory (requires permission), specify the path of the file and use double
backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the
path, like: /Users/name/[Link]
Example
File myObj = new File("C:\\Users\\MyName\\[Link]");

Write To a File
In the following example, we use the FileWriter class together with
its write() method to write some text to the file we created in the example above. Note that when you
are done writing to the file, you should close it with the close() method:
Example
import [Link]; // Import the FileWriter class
import [Link]; // Import the IOException class to handle
errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("[Link]");
[Link]("Files in Java might be tricky, but it is fun
enough!");
[Link]();
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}
The output will be:
Successfully wrote to the file.

Read a File
In the following example, we use the Scanner class to read the contents of the text file
Example
import [Link]; // Import the File class
import [Link]; // Import this class to handle
errors
import [Link]; // Import the Scanner class to read text
files public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new
File("[Link]"); Scanner
myReader = new Scanner(myObj); while
([Link]()) {
String data =
[Link]();
[Link](data);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("An error occurred.");
[Link]();
}
}
}
The output will be:
Files in Java might be tricky, but it is fun enough!

Get File Information


To get more information about a file, use any of the File methods:
Example
import [Link]; // Import the File class
public class GetFileInfo {
public static void main(String[] args)
{ File myObj = new
File("[Link]"); if
([Link]()) {
[Link]("File name: " + [Link]());
[Link]("Absolute path: " + [Link]());
[Link]("Writeable: " + [Link]());
[Link]("Readable " + [Link]());
[Link]("File size in bytes " + [Link]());
} else {
[Link]("The file does not exist.");
}
}
}
The output will be:
File name: [Link]
Absolute path: C:\Users\MyName\[Link]
Writeable: true

Readable: true
File size in bytes: 0
Delete a File
To delete a file in Java, use the delete() method:
Example
import [Link]; // Import the File class
public class DeleteFile {
public static void main(String[] args)
{ File myObj = new
File("[Link]"); if
([Link]()) {
[Link]("Deleted the file: " + [Link]());
} else {
[Link]("Failed to delete the file.");
}
}
}
The output will be:
Deleted the file: [Link]
Deadlock in Java
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting
for an object lock, that is acquired by another thread and second thread is waiting for an object lock
that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the
condition is called deadlock.

Example of Deadlock in Java


[Link]
1. public class TestDeadlockExample1 {
2. public static void main(String[] args) {
3. final String resource1 = "ratan jaiswal";
4. final String resource2 = "vimal jaiswal";
5. // t1 tries to lock resource1 then resource2
6. Thread t1 = new Thread() {
7. public void run() {
8. synchronized (resource1) {
9. [Link]("Thread 1: locked resource 1");
10.
11. try { [Link](100);} catch (Exception e) {} 12.
13. synchronized (resource2) {
14. [Link]("Thread 1: locked resource 2");
15. }
16. }
17. }
18. };
19.
20. // t2 tries to lock resource2 then resource1
21. Thread t2 = new Thread() {
22. public void run() {
23. synchronized (resource2) {
24.
[Link]("Thread 2: locked resource 2");
25.
26.
try { [Link](100);} catch (Exception e) {}
27.
28.
synchronized (resource1) {
29.
[Link]("Thread 2: locked resource 1");
30. }
31.
}
}
32.
};
33.
34.
35.
36. [Link]();

37.
38. [Link]();
}
39.
40. }
Output:

Thread 1: locked resource 1


Thread 2: locked resource 2

More Complicated Deadlocks


A deadlock may also include more than two threads. The reason is that it can be difficult to detect a
deadlock. Here is an example in which four threads have deadlocked:
Thread 1 locks A, waits for B
Thread 2 locks B, waits for C
Thread 3 locks C, waits for D
Thread 4 locks D, waits for A
Thread 1 waits for thread 2, thread 2 waits for thread 3, thread 3 waits for thread 4, and
thread 4 waits for thread 1.
How to avoid deadlock?
A solution for a problem is found at its roots. In deadlock it is the pattern of accessing the resources A
and B, is the main issue. To solve the issue we will have to simply re-order the statements where the
code is accessing shared resources.
[Link]
1. public class DeadlockSolved { 2.
3. public static void main(String ar[]) {
4. DeadlockSolved test = new DeadlockSolved(); 5.
6. final resource1 a = [Link] resource1();
7. final resource2 b = [Link] resource2(); 8.
9. // Thread-1
10. Runnable b1 = new Runnable() {
11. public void run() {
12. synchronized (b) {
13. try {
14. /* Adding delay so that both threads can start trying to lock resources */
15. [Link](100);
16. } catch (InterruptedException e) {
17. [Link]();
18. }
19. // Thread-1 have resource1 but need resource2 also
20. synchronized (a) {
21. [Link]("In block 1");
22. }
23. }
24. }
25. };
26.
27. // Thread-2
28. Runnable b2 = new Runnable() {
29. public void run() {
30. synchronized (b) {
31. // Thread-2 have resource2 but need resource1 also
32. synchronized (a) {
33. [Link]("In block 2");
34. }
35. }
36. }
37. };
38.
39.
40. new Thread(b1).start();
41. new Thread(b2).start();
42. }

43.
44. // resource1
45. private class resource1 {
46. private int i = 10;
47.
48. public int getI() {
49. return i;
50. }
51.
52. public void setI(int i) {
53. this.i = i;
54. }
55. }
56.
57. // resource2
58. private class resource2 {
59. private int i = 20;
60.
61. public int getI() {
62. return i;
63. }
64.
65. public void setI(int i) {
66. this.i = i;
67. }
68. }
69. }
Output:

In block 1
In block 2

In the above code, class DeadlockSolved solves the deadlock kind of situation. It will help in
avoiding deadlocks, and if encountered, in resolving them.
How to Avoid Deadlock in Java?
Deadlocks cannot be completely resolved. But we can avoid them by following basic rules
mentioned below:
1. Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main reason
for a deadlock condition. It normally happens when you give locks to multiple threads.
2. Avoid Unnecessary Locks: The locks should be given to the important threads. Giving locks to
the unnecessary threads that cause the deadlock condition.
3. Using Thread Join: A deadlock usually happens when one thread is waiting for the other to finish. In
this case, we can use join with a maximum time that a thread will take.
Parallel Stream in Java
One of the prominent features of Java 8 (or higher) is Java Parallel Stream. It is meant for utilizing the
various cores of the processor. Usually, any Java code that has only one processing stream, where it is
sequentially executed. However, by using parallel streams, one can separate the Java code into more
than one stream, which is executed in parallel on their separate cores, and the end result is the
combination of the individual results. The order in which they are executed is not in our control. Hence,
it is suggested to use a parallel stream when the order of execution of individual items does not affect
the final result.
Analysis of Parallel Stream
For increasing the performance of a program, parallel streams are introduced. However, it is not a
guarantee that applying a parallel stream will enhance the result. For example, there can be a scenario
where code must be executed in a certain order. There are certain instances in which we need the code
to be executed in a certain order, and in such a case, it is required to use sequential streams instead of
parallel streams.
Different Ways to Create Stream
There are two ways we can create, which are listed below and described later as follows:
1. Using the parallel() method on a stream
2. Using parallelStream() on a Collection

Using parallel() method on a stream


The parallel() method of the BaseStream interface returns an equivalent parallel stream. Let's
understand its working through an example.
FileName: [Link]
1. // Importing the required classes
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6.
7.
8. // Main class
9. public class ParallelStream
10. {
11.
12. // Main method
13. public static void main(String[] argvs) throws IOException
14. {
15.
16. // Creating a File object
17. File f = new File("C:\\Users\\Nikhil\\Downloads\\ParallelStreams\\[Link]"); 18.
19. // A Stream of the string type using the method line() is created
20. // for reading only one link at a time from the mentioned text file
21. Stream<String> txt = [Link]([Link]()); 22.
23. // Creating the parallel streams using the parallel() method
24. // and later using the forEach() in order to print on the console
25. [Link]().forEach([Link]::println);
26.
27. // the Stream is closed by invoking the close() method
28. [Link]();
29. }
30. }
Output 1:

Vestibulum urna lacus, eleifend venenatis ipsum at, venenatis fringilla mauris.
Fusce nulla augue, convallis at velit ac, pulvinar convallis eros.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac
turpis egestas. Sed ut ipsum molestie dolor dictum luctus.
Maecenas interdum erat feugiat rhoncus mattis. Phasellus facilisis ex non magna
faucibus mollis.
Vestibulum eu tellus nec lectus rutrum ornare ac tincidunt sem.

Explanation: In the above program, we have made a file object that points to a
[Link] file that is already present in the system. After that, a stream is created that does
reading from the text file (only one line at a time). Then we invoke the parallel() method to display the
content of the [Link] on the console. Note that the order of the execution is different each
time we execute the above code. The code is executed again; the following output is displayed on the
console.
Output 2:

Fusce nulla augue, convallis at velit ac, pulvinar convallis eros.


Vestibulum urna lacus, eleifend venenatis ipsum at, venenatis fringilla mauris.
Maecenas interdum erat feugiat rhoncus mattis. Phasellus facilisis ex non magna
faucibus mollis.
Vestibulum eu tellus nec lectus rutrum ornare ac tincidunt sem.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac
turpis egestas. Sed ut ipsum molestie dolor dictum luctus.
Using parallelStream() on a Collection
The parallelStream() method is part of the Collection interface and returns a parallel stream with the
collection as a source. It's working of it is explained in the following example.

FileName: [Link]
1. // Importing the required classes
2. import [Link].*;
3. import [Link];
4. import [Link];
5. import [Link];
6.
7.
8. // Main class
9. public class ParallelStream
10. {
11.
12. // Main method
13. public static void main(String[] argvs) throws IOException
14. {
15.
16. // Creating a File object
17. File f = new File("C:\\Users\\Nikhil\\Downloads\\ParallelStreams\\[Link]"); 18.
19. // Reading the lines of the file [Link] by
20. // making a List by invoking the method readAllLines()
21. List<String> text = [Link]([Link]());
22.
23. // Creating different parallel streams by making a List
24. // by invoking the method readAllLines()
25. [Link]().forEach([Link]::println);
26. }
27. }
28.
Output 1:

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac


turpis egestas. Sed ut ipsum molestie dolor dictum luctus.
Vestibulum urna lacus, eleifend venenatis ipsum at, venenatis fringilla mauris.
Maecenas interdum erat feugiat rhoncus mattis. Phasellus facilisis ex non magna
faucibus mollis.
Fusce nulla augue, convallis at velit ac, pulvinar convallis eros.
Vestibulum eu tellus nec lectus rutrum ornare ac tincidunt sem.

Explanation: In the above-mentioned code, we are using a parallel stream. However, we are using the
List to read from the [Link] file. Hence, the parallelstream() method is required.
Other Examples of Parallel Execution of Stream
Let's see a few more examples of parallel execution of streams.

FileName: [Link]
1. // important import statement
2. import [Link];
3.
4. public class ParallelStream1
5. {
6.
7. // main method
8. public static void main(String[] argvs)
9. {
10.
11. [Link]("In Normal");
12.
13. // prints values from 1 to 5 (1 and 5 included)
14. IntStream r = [Link](1, 5);
15. [Link]([Link]::println);
16.
17. [Link]("In Parallel");
18.
19. // prints values from 1 to 5 (1 and 5 included)
20. IntStream r1 = [Link](1, 5);
21. [Link]().forEach([Link]::println);
22.
23. }
24.
25. }
Output:

In Normal
1
2
3
4
5
In Parallel
3
5
4
2
1

Reading console input and Writing console output


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 operation fast. The [Link] package contains all the
classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
Core Concepts of Java I/O
Java I/O revolves around two primary concepts: streams and readers/writers.
Streams: Streams represent a sequence of data. In Java, there are two types of streams: input streams
and output streams. Input streams are used to read data from a source, while output streams are used to
write data to a destination. Streams can be categorized into byte streams (InputStream and
OutputStream) and character streams (Reader and Writer).
Readers/Writers: Readers and writers are specialized stream classes designed for handling character
data. They provide a convenient way to read from and write to character- based data sources. Readers
read character data from input streams, while writers write character data to output streams.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it
is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1) [Link]: standard output stream
2) [Link]: standard input stream
3) [Link]: standard error stream
Let's see the code to print output and an error message to the console.
1. [Link]("simple message");
2. [Link]("error message");
Let's see the code to get input from console.
1. int i=[Link]();//returns ASCII code of 1st character
2. [Link]((char)i);//will print the character
OutputStream Vs. InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral
device or socket.

Input Stream
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral
device or socket.
Let's understand the working of Java OutputStream and InputStream class by the figure given below.

OutputStream Class
OutputStream class is an abstract class. It is the superclass of all classes representing an output stream
of bytes. An output stream accepts output bytes and sends them to some sink.
Useful Methods of OutputStream Class

Method Description

public void write(int) throws It is used to write a byte to the current output

IOException stream.

public void
It is used to write an array of byte to the
write(byte[])throws
current output stream.
IOException
public void flush() throws
It flushes the current output stream.
IOException

public void close() throws It is used to close the current output stream.
IOException

Output Stream Hierarchy

Input Stream Class


Input Stream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.

Useful Methods of InputStream Class

Method Description

public abstract int read() throws It reads the next byte of data from
IOException the input stream. It
returns -1 at the end of the file.

It returns an estimate of the

public int available() throws number of bytes that can be

IOException read from the current input


stream.

public void close() throws It is used to close the current

IOException input stream.

Input Stream Hierarchy

Java I/O Classes


1. Java provides a rich set of classes for performing I/O operations. Some of the key classes include:
2. InputStream and OutputStream: These abstract classes form the foundation for byte- oriented I/O
operations. They provide methods for reading and writing bytes from/to various sources and
destinations.
3. Reader and Writer: These abstract classes are used for character-based I/O operations. They provide
methods for reading and writing characters from/to character-based streams.
4. FileInputStream and FileOutputStream: These classes allow reading from and writing to files in a
byte-oriented manner.
5. FileReader and FileWriter: These classes enable reading from and writing to files using character-
oriented operations.
6. BufferedInputStream and BufferedOutputStream: These classes provide buffering capabilities,
which can significantly improve I/O performance by reducing the number of system calls.
7. BufferedReader and BufferedWriter: These classes offer buffered reading and writing of character
data, enhancing I/O efficiency when working with character-based streams.

Practical Applications of Java I/O


Best Practices for Java I/O
When working with Java I/O, consider the following best
practices:
1. Use Try-with-Resources: Always use the try-with-resources statement when working with streams to
ensure proper resource management. This automatically closes the streams when they are no longer
needed, preventing resource leaks.
2. Use Buffered I/O: Whenever possible, use buffered I/O classes to minimize the number of system calls
and improve performance.
3. Handle Exceptions Gracefully: Handle I/O exceptions gracefully by implementing error handling
mechanisms such as logging or error propagation.
4. Use NIO for Performance: For high-performance I/O operations, consider using Java's NIO
(New I/O) package, which provides non-blocking I/O features and enhanced performance.
Conclusion
Java I/O is a fundamental aspect of Java programming, offering powerful capabilities for handling
input and output operations. By understanding the core concepts, classes, and best practices of Java
I/O, developers can build robust and efficient applications that interact with external resources
seamlessly. Whether it's reading from files, communicating over networks, or processing data streams,
Java I/O provides the tools necessary to tackle a wide range of I/O tasks effectively.
Difference between Character Stream and Byte Stream in Java
In Java the streams are used for input and output operations by allowing data to be read from or written
to a source or destination.
Java offers two types of streams:
1. character streams
2. byte streams.
These streams can be different in how they are handling data and the type of data they are handling.
1. Character Streams:
Character streams are designed to address character based records, which includes textual records
inclusive of letters, digits, symbols, and other characters. These streams are represented by way of
training that quit with the phrase "Reader" or "Writer" of their names, inclusive of FileReader,
BufferedReader, FileWriter, and BufferedWriter.
Character streams offer a convenient manner to read and write textual content-primarily based
information due to the fact they mechanically manage character encoding and decoding. They convert
the individual statistics to and from the underlying byte circulation the usage of a particular individual
encoding, such as UTF-eight or [Link] makes person streams suitable for operating with textual
content files, analyzing and writing strings, and processing human-readable statistics.
2. Byte Streams:
Byte streams are designed to deal with raw binary data, which includes all kinds of data, including
characters, pictues, audio, and video. These streams are represented through cclasses that cease with
the word "InputStream" or "OutputStream" of their names,along with
FileInputStream,BufferedInputStream, FileOutputStream and BufferedOutputStream.
Byte streams offer a low-stage interface for studying and writing character bytes or blocks of bytes.
They are normally used for coping with non-textual statistics, studying and writing files of their binary
form, and running with network sockets. Byte streams don't perform any individual encoding or
deciphering. They treat the data as a sequence of bytes and don't interpret it as characters.

Here are the some of the differences listed:

Aspect Character Streams Byte Streams

Handle character-based Handle raw binary data


Data Handling
data

Classes end with


Classes end with "Reader"
Representation "InputStream" or
or "Writer"
"OutputStream"

Non-textual data,
Textual data, strings,
Suitable for binary files,
human-readable info
multimedia

Automatic encoding and No encoding or


Character Encoding
decoding decoding
Text vs non-Text data Binary data, images,
Text-based data, strings
audio, video

Additional conversion may Efficient for handling


Performance
impact performance large binary data

Handle Large Text May impact performance Efficient, no encoding


Files due to encoding overhead

Not specifically
Convenient methods for
String Operations designed for string
string operations
operations

Convenience Methods Higher-level abstractions Low-level interface for

for text data byte data

Byte-oriented, no
Reading Line by Line Convenient methods for
built-in line-reading
reading lines
methods

Read/write binary files


File Handling Read/write text files
Network Sending/receiving text data Sending/receiving

Communication binary data

Not designed for handling Suitable for handling


Handling
binary data binary multimedia
Images/Audio/Video
directly data

Supports various character No specific text


Text Encoding
encodings encoding support

Example code for Character Stream:


FileName: [Link]
1. import [Link];
2. import [Link];
3.
4. public class CharacterStreamExample
5. {

6. public static void main(String[] args) {


7. // Creates an array of characters
8. char[] array = {'H','e','l','l','o'};
9. try {
10. CharArrayReader reader=new CharArrayReader(array);
11. [Link]("The characters read from the reader:");
12. int charRead;
13. while ((charRead=[Link]())!=-1) {
14. [Link]((char)charRead+",");
15. }
16. [Link]();
17. } catch (IOException ex)
18. {
19. [Link]();
20. }
21. }
22. }
Output:

The characters read from the reader:H,e,l,l,o,

Example code for Byte Stream:


FileName: [Link]
1. import [Link];
2.
3. public class ByteStreamExample
4. {
5. public static void main(String[] args)
6. {
7. // Creates the array of bytes
8. byte[] array = {10,20,30,40};
9. try {
10. ByteArrayInputStream input=new ByteArrayInputStream(array);
11. [Link]("The bytes read from the input stream:");
12. for (int i=0;i<[Link];i++)
13. {
14. // Reads the bytes
15. int data=[Link]();
16. [Link](data+",");
17. }
18. [Link]();
19. } catch (Exception ex)
20. {
21. [Link]();
22. }
23. }
24. }
Output:

The bytes read from the input stream:10,20,30,40.


MCQ
1. Which class is used to create a thread in Java?
a) Thread
b) Runnable
c) Task
d) Executor
Answer: a) Thread
2. What is the method used to start a thread in Java?
a) run()
b) start()
c) begin()
d) execute()
Answer: b) start()
3. Which of the following is true about the run()method in Java threads?
a) It is executed automatically when a thread is created.
b) It must be called explicitly in the main method.
c) It contains the code that defines the task of the thread.
d) It is used to initialize the thread object.
Answer: c) It contains the code that defines the task of the thread.
4. What will happen if a thread’s run()method is called directly instead of
start()?
a) The thread will start executing in a new thread.
b) The run()method will execute in the current thread.
c) The program will throw an exception.
d) The thread will be ignored.
Answer: b) The run()method will execute in the current thread.
5. Which interface must a class implement to create a thread by using the
Runnableinterface?
a) Executor
b) Runnable
c) Thread
d) Callable
Answer: b) Runnable
6. Which method is used to pause the execution of a thread for a specified time in
Java?
a) suspend()
b) wait()
c) sleep()
d) hold()
Answer: c) sleep()
7. What is the state of a thread after calling [Link]()?
a) Running
b) Blocked
c) Waiting
d) Timed Waiting
Answer: d) Timed Waiting
8. Which of the following is NOT a valid thread state in Java?
a) New
b) Ready
c) Blocked
d) Waiting
Answer: b) Ready
9. Which method is used to stop a thread in Java?
a) stop()
b) terminate()
c) interrupt()
d) suspend()
Answer: c) interrupt()
(Note: stop()is deprecated and not recommended for use.)
10. In Java, what happens when a thread calls the join()method on another
thread?
a) The calling thread starts executing the target thread.
b) The calling thread terminates.
c) The calling thread waits for the target thread to finish execution.
d) The target thread is paused indefinitely.
Answer: c) The calling thread waits for the target thread to finish execution.
11. Which of the following methods is used to get the status of a thread?
a) status()
b) getStatus()
c) getState()
d) isAlive()
Answer: c) getState()
12. Which of the following is true about the [Link]()method?
a) It releases the CPU and allows other threads to execute.
b) It must be surrounded by a try-catch block for handling exceptions.
c) It puts the thread in a running state.
d) It can only be used inside a synchronized block.
Answer: b) It must be surrounded by a try-catch block for handling exceptions.
13. What is the default priority of a thread in Java?
a) 1
b) 5
c) 10
d) 7
Answer: b) 5
14. What is the effect of calling [Link]()in Java?
a) It stops the current thread immediately.
b) It gives the processor to another thread that is ready to run.
c) It blocks the current thread for a specified period.
d) It prevents the current thread from executing further.
Answer: b) It gives the processor to another thread that is ready to run.
15. Which of the following classes in Java provides the ability to execute multiple
threads in a pool?
a) ThreadPoolExecutor
b) ExecutorService
c) Executor
d) ScheduledExecutorService
Answer: b) ExecutorService
16. Which method is used to start a thread that is created using the Runnable
interface in Java?
a) start()
b) execute()
c) run()
d) initiate()
Answer: a) start()
17. What is a daemon thread in Java?
a) A thread that runs in the background and is typically used for supporting tasks.
b) A thread that must complete before the main program can exit.
c) A thread that is not part of the thread pool.
d) A thread that runs indefinitely until terminated manually.
Answer: a) A thread that runs in the background and is typically used for supporting
tasks.
18. What happens when a thread is blocked?
a) It waits for I/O operations to complete or some condition to be met.
b) It immediately stops and terminates.
c) It goes into the running state again.
d) It never wakes up again.
Answer: a) It waits for I/O operations to complete or some condition to be met.
19. Which of the following methods is used to suspend the execution of the
current thread for a specific period?
a) delay()
b) pause()
c) sleep()
d) halt()
Answer: c) sleep()
20. Which of the following is used to ensure that a thread does not interrupt the
ongoing task in Java?
a) synchronized block
b) volatile variable
c) [Link]()
d) [Link]()
Answer: a) synchronized block
21. What is a deadlock in Java?
A) A situation where a thread is stuck in an infinite loop
B) A situation where two or more threads are blocked forever
C) A situation where a thread is waiting for an input from the user
D) A situation where threads are executing without any issues
Answer: B) A situation where two or more threads are blocked forever
22. Which of the following is NOT a necessary condition for a deadlock in Java?
A) Mutual Exclusion
B) Hold and Wait
C) Preemption
D) Circular Wait
Answer: C) Preemption
Explanation: Preemption, which allows a thread to be forcefully stopped or interrupted, is not
necessary for a deadlock. Deadlock occurs only if mutual exclusion, hold and wait, no
preemption, and circular wait conditions are all met.
23. In which scenario can deadlock occur in Java?
A) When two threads acquire two locks in different order
B) When a thread acquires multiple locks in the same order
C) When no thread holds any lock
D) When all threads acquire a lock simultaneously
Answer: A) When two threads acquire two locks in different order
Explanation: Deadlock can occur when two threads hold one lock and are trying to acquire the
other's lock in reverse order, creating a circular dependency.
24. Which of the following can help in preventing deadlock in Java?
A) Locking all resources in a predefined order
B) Increasing the priority of threads
C) Using [Link]()
D) Allowing threads to lock any resource at any time
Answer: A) Locking all resources in a predefined order
Explanation: Deadlock prevention can be achieved by acquiring locks in a consistent order,
ensuring that circular dependencies are avoided.
25. What happens when a deadlock occurs in a Java program?
A) The program will throw an exception
B) The threads involved in the deadlock will continue executing indefinitely
C) The JVM will terminate the deadlocked threads
D) The JVM will restart the program
Answer: B) The threads involved in the deadlock will continue executing indefinitely
Explanation: Once a deadlock occurs, the threads involved are stuck and will not proceed,
leading to the indefinite blocking of the involved threads.
26. Which Java class can be used to detect deadlocks?
A) Thread
B) ThreadGroup
C) ThreadMXBean
D) Lock
Answer: C) ThreadMXBean
Explanation: The ThreadMXBeaninterface, part of the [Link], provides
methods for detecting thread deadlocks.
27. Which of the following is a method that helps avoid deadlocks in Java?
A) Using synchronized blocks only
B) Using ReentrantLockwith a timeout
C) Using [Link]()to stop threads
D) Using [Link]()for synchronization
Answer: B) Using ReentrantLockwith a timeout
Explanation: ReentrantLockallows for a timeout feature when trying to acquire a lock. If the lock
cannot be acquired within the specified time, the thread can back out, helping to avoid a
deadlock situation.
28. Which of the following Java constructs can lead to a deadlock?
A) Synchronized methods
B) Synchronized blocks
C) Lockinterface
D) Both A and B
Answer: D) Both A and B
Explanation: Both synchronized methods and synchronized blocks can lead to deadlocks if the
locking order and other conditions are not handled carefully.
29. Which of the following is a potential solution to deal with deadlocks in Java?
A) Avoid synchronization entirely
B) Use nested synchronizedblocks
C) Implement timeout-based locking
D) Allow all threads to acquire locks freely
Answer: C) Implement timeout-based locking
Explanation: Implementing timeout-based locking (such as with ReentrantLock) allows threads
to abandon lock attempts after a specified time, preventing deadlocks.
30. What is the [Link]()method used for in Java?
A) To release locks
B) To simulate I/O operation
C) To pause the current thread for a specified time
D) To detect deadlocks
Answer: C) To pause the current thread for a specified time
31. Which class in Java is used to read user input from the console?
a) FileReader
b) Scanner
c) InputStreamReader
d) BufferedReader
Answer:
b) Scanner
The Scannerclass is commonly used to read user input from the console.
32. Which method of [Link] used to read a single byte of data?
a) read()
b) next()
c) nextInt()
d) readLine()
Answer:
a) read()
The read()method of [Link] a single byte of input.
33. Which method is used to read a line of text from the user using the
BufferedReader class?
a) read()
b) readLine()
c) nextLine()
d) next()
Answer:
b) readLine()
The readLine()method of the BufferedReaderclass is used to read a complete line of text from the
user.
34. What will be the output of the following code snippet?
java
Copy code [Link]("Hello ");
[Link]("World!");
a) HelloWorld!
b) Hello
World!
c) Hello World!
d) Compilation error
Answer:
b) Hello
World!
The [Link]()method prints without a newline, whereas [Link]()
adds a newline after printing.
35. Which of the following classes is used to read input from the keyboard in
Java?
a) FileReader
b) FileWriter
c) InputStreamReader
d) PrintWriter
Answer:
c) InputStreamReader
InputStreamReaderis used to read bytes and decode them into characters. It's commonly wrapped
in BufferedReader for better performance.
36. Which method of Scanneris used to read an integer from the user input?
a) nextInt()
b) next()
c) nextByte()
d) readInt()
Answer:
a) nextInt()
The nextInt()method of the Scannerclass is used to read an integer from the user.
37. What is the default delimiter used by the Scannerclass when reading input
from the console?
a) Space
b) Comma
c) Newline
d) Tab
Answer:
a) Space
The Scannerclass uses space as the default delimiter to separate input tokens.
38. Which of the following is a valid way to print formatted output to the console
in Java?
a) [Link]("Hello %s!", "World");
b) [Link]("Hello %s!", "World");
c) [Link]("Hello %s!", "World");
d) [Link]("Hello %s!", "World");
Answer:
a) [Link]("Hello %s!", "World");
[Link]()or [Link]()can be used to print formatted output in Java.
39. Which method of [Link] the specified string without adding a
newline at the end?
a) print()
b) println()
c) write()
d) flush()
Answer:
a) print()
The [Link]()method prints the string without adding a newline at the end.
40. Which of the following code snippets will correctly read a string from the
console using Scanner?
a) String input = [Link]();
b) String input = new Scanner([Link]).nextLine();
c) String input = [Link]();
d) String input = readLine();
Answer:
b) String input = new Scanner([Link]).nextLine();
This is the correct way to read a full line of text using Scanner.
41. What will happen if you try to read an integer using nextInt()and the user
inputs a non-integer value?
a) The program will terminate.
b) It will throw an InputMismatchException.
c) It will prompt the user to enter the integer again.
d) It will read the first integer part of the input.
Answer:
b) It will throw an InputMismatchException.
If the user inputs a value that cannot be parsed as an integer, nextInt()throws an
InputMismatchException.
42. Which of the following is the correct way to read a character from the console
in Java?
a) char ch = [Link]();
b) char ch = new Scanner([Link]).nextChar();
c) char ch = new BufferedReader(new
InputStreamReader([Link])).read();
d) char ch = new Scanner([Link]).next().charAt(0);
Answer:
d) char ch = new Scanner([Link]).next().charAt(0);
To read a single character, we can use the next()method of Scannerand then extract the first
character using charAt(0).
43. What is the purpose of the flush()method in the context of the PrintWriter
class?
a) To close the output stream
b) To force any buffered data to be written to the output stream
c) To clear the console screen
d) To write the next line
Answer:
b) To force any buffered data to be written to the output stream
The flush()method ensures that all buffered data is written out immediately, without waiting for
the buffer to fill up.
44. Which of the following classes provides buffering to improve performance of
input and output operations?
a) FileReader
b) BufferedReader
c) PrintWriter
d) InputStreamReader
Answer:
b) BufferedReader
BufferedReaderprovides efficient reading by buffering input, which improves performance when
reading large amounts of data.
45. In Java, which class would you typically use for reading console input with
error handling for invalid input?
a) FileReader
b) BufferedReader
c) Scanner
d) PrintWriter
Answer:
c) Scanner

46. What is the purpose of synchronization in Java?


A) To prevent multiple threads from accessing the same resources simultaneously
B) To allow threads to run independently without any interference
C) To make sure that threads run faster
D) To limit the number of threads that can run simultaneously
Answer:
A) To prevent multiple threads from accessing the same resources simultaneously
47. Which keyword is used in Java to ensure synchronization of a method?
A) synchronized
B) volatile
C) transient
D) static
Answer:
A) synchronized
48. What does the synchronizedkeyword do when applied to a method?
A) It makes sure only one thread can execute that method at any given time.
B) It allows multiple threads to execute the method simultaneously.
C) It prevents the method from being accessed outside the class.
D) It makes the method accessible only to threads running on the same processor.
Answer:
A) It makes sure only one thread can execute that method at any given time.
49. Which of the following is a valid scenario where synchronization can be
used?
A) Updating shared data in a multi-threaded environment
B) Making an object accessible to all threads in an application
C) Ensuring multiple threads can read a variable at the same time without conflict
D) None of the above
Answer:
A) Updating shared data in a multi-threaded environment
50. Which of the following is true about synchronized blocks in Java?
A) Synchronized blocks can only synchronize methods.
B) A synchronized block can synchronize a block of code within a method.
C) A synchronized block automatically synchronizes the whole class.
D) None of the above.
Answer:
B) A synchronized block can synchronize a block of code within a method.
5 MARKS:
1. Explain the differences between Thread and Runnable in Java.

2. What are synchronizedmethods in Java? Why are they important in


multithreading?

3. Describe lifecycle of thread in Java.

4. Difference between FileInputStream and FileReader in Java

5. Describe now ObjectOutputStream and ObjectInputStream work for serializin


and deserializin objects in Java

10 MARKS:

1. Explain the concept of a deadlock in Java multithreading. Describe a scenario


where deadlock might occur, and discuss methods to avoid it.

2. What is thread synchronization in Java? Discuss the role of synchronized blocks, and
compare synchronized methods versus synchronized blocks with examples.

3. Describe the [Link] package in Java. Explain how it helps with


thread-safe operations, focusing on key classes such as ReentrantLock, Semaphore,
and CountDownLatch.

4. Illustrate the producer-consumer problem using threads in Java, employing wait() and notify().
Explain how these methods facilitate inter-thread communication.

5. Explain the difference between byte streams and character streams in Java. Give
examples of commonly used classes in each category, and describe when each type
should be used.
UNIT IV

Java AWT Tutorial

➢ Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows-based applications in Java.
➢ Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its components
are using the resources of underlying operating system (OS).
➢ The [Link] package provides classes for AWT API such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
➢ The AWT tutorial will help the user to understand Java GUI programming in simple
and easy steps.
➢ Java AWT Hierarchy
➢ The hierarchy of Java AWT classes are given below.

Components
➢ All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in above diagram. In order
to place every component in a particular position on a screen, we need to add them to a
container.
Container
➢ The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class are known
as container such as Frame, Dialog and Panel.

Types of containers:

There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. Dialog

Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container.

Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.

Frame
The Frame is the container that contain title bar and border and can have menu bars. It can have
other components like button, text field, scrollbar etc. Frame is most widely used container
while developing an AWT application.

Useful Methods of Component Class

Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the
component.

public void setLayout(LayoutManager m) Defines the layout manager for the


component.

public void setVisible(boolean status) Changes the visibility of the component,


by default false.

User interface components


➢ User interface components are the building blocks of a digital interface, enabling
users to interact with software, websites, or applications.
➢ These components range from basic elements like buttons and text fields to more
complex structures like forms and modal dialogs.
➢ Here’s a breakdown of common UI components and their purposes:

1. Input Components

• Text Fields: Allow users to input text information (e.g., search bars, login fields).
• Checkboxes: Enable users to make binary choices; they can be checked or
unchecked.
• Radio Buttons: Allow users to select one option from a group.
• Dropdown Menus: Provide a list of options to select from, saving space.
• Sliders: Enable users to select a value or range by sliding a control.

2. Action Components

• Buttons: Trigger actions when clicked, like submitting a form or opening a link.
• Icon Buttons: Smaller buttons with an icon, often used for actions like editing,
deleting, or sharing.
• Floating Action Buttons (FABs): Circular buttons that promote primary actions,
commonly used in mobile apps.

3. Navigation Components

• Menus: Lists of navigational options, usually opened by clicking on a button or icon.


• Tabs: Allow users to switch between different views or sections within the same
interface.
• Breadcrumbs: Display a trail of links to indicate the user’s current location within
the hierarchy of a site.
• Sidebars: Vertical panels that offer navigation or additional options, usually on the
left or right side.

4. Display Components

• Cards: Containers that present information or actions, often used for showcasing
individual items in a list.
• Tables: Present data in a grid format, useful for organizing structured information.
• Lists: Display items in a sequential format, often with a consistent layout.
• Modals/Dialogs: Pop-up windows that overlay the main interface to capture the
user’s attention for critical actions.

5. Feedback Components

• Progress Bars/Spinners: Indicate loading states or progress through a process.


• Tooltips: Small text boxes that appear when users hover over elements, providing
additional information.
• Notifications: Alerts that inform users of important updates or actions, often
appearing temporarily.
6. Form Components

• Labels: Text that describes input fields, making forms more accessible and easier to
understand.
• Error Messages: Appear when users input invalid data, guiding them on what needs
to be corrected.
• Submit and Reset Buttons: Essential for forms, allowing users to complete or reset
the input fields.

7. Utility Components

• Accordions: Expandable sections that reveal or hide content, useful for FAQs and
minimizing clutter.
• Breadcrumbs: Help users understand the site hierarchy and easily navigate back to
previous levels.
• Carousel/Slider: Allow users to scroll through images or items horizontally or
vertically.

These components, when combined effectively, create an intuitive and smooth user
experience that aligns with the goals of the application or website.

Basic UI Components:

1. Labels:
o Labels are non-interactive text components used to display information or
descriptions near other components (like input fields).
o In Java’s Swing, a label can be created using JLabel.
2. Button Text Components:
o Buttons are interactive components that perform an action when clicked. They
can have text, icons, or both.
o In Java, JButton represents a button component.
3. Checkbox:
o A checkbox is a small square that can either be checked or unchecked,
representing a binary choice.
o In Swing, checkboxes are created using JCheckBox.
4. Checkbox Group:
o A checkbox group contains multiple checkboxes, allowing users to select
multiple options.
o In Swing, while checkboxes are independent, a set of checkboxes can be
logically grouped for a cleaner UI.
5. Choice:
o Also known as a dropdown or combo box, a choice component allows users to
select one item from a list.
o In Swing, JComboBox or JList can represent a choice component.
6. List Box:
o A list box displays a list of items, often allowing multiple selections.
o In Swing, JList is used to create a list box.

Container Components:

7. Panels:
o Panels are container components used to group other UI components together.
o In Swing, JPanel is used as a basic container.
8. Scroll Pane:
o A scroll pane allows content to be scrollable, useful for large data sets or
images.
o In Swing, JScrollPane wraps around components that need scrolling, like
tables, lists, or images.
9. Menu:
o A menu component provides a list of commands or options, typically
organized within a menu bar at the top of a window.
o In Swing, menus are created using JMenuBar, JMenu, and JMenuItem.
10. Scroll Bar:

• A scroll bar allows the user to navigate vertically or horizontally through content that
doesn’t fit within the visible area.
• Swing provides JScrollBar to create standalone scroll bars.

Working with Frame Class:

• Frames are the main window containers in many GUI applications.


• In Swing, JFrame is a top-level container that provides the main application window.
Styling and Layout Components:

Color:

• Colors enhance the visual appearance of the interface.


• In Java, colors can be set using the Color class, such as [Link] or new Color(255,
0, 0).

Fonts:

• Fonts define the style and appearance of text within components.


• The Font class in Java allows setting font type, style, and size, like new Font("Serif",
[Link], 14).

Layout Managers:

• Layout managers determine how components are arranged within a container.


• Common layout managers include:
o FlowLayout: Arranges components in a left-to-right flow.
o BorderLayout: Divides the container into five regions (North, South, East,
West, Center).
o GridLayout: Places components in a grid of cells.
o BoxLayout: Arranges components either vertically or horizontally.

EventHandling
➢ An event can be defined as changing the state of an object or behavior by
performing actions.
➢ Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
➢ The [Link] package can be used to provide various event classes.
Classification of Events

• Foreground Events
• Background Events

1. Foreground Events
➢ Foreground events are the events that require user interaction to generate, i.e.,
foreground events are generated due to interaction by the user on components in
Graphic User Interface (GUI).
➢ Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor
moments, etc.

2. Background Events
➢ Events that don’t require interactions of users to generate are known as background
events. Examples of these events are operating system failures/interrupts, operation
completion, etc.
Event Handling
➢ It is a mechanism to control the events and to decide what should happen after an
event occur. To handle the events, Java follows the Delegation Event model.

Delegation Event model


• It has Sources and Listeners

• Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
• Listeners: Listeners are used for handling the events generated from the source. Each
of these listeners represents interfaces that are responsible for handling events.

➢ To perform Event Handling, we need to register the source with the listener.
➢ Registering the Source With Listener
➢ Different Classes provide different registration methods.
Syntax:
addTypeListener()

where Type represents the type of event.


Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.
Event Classes in Java
Event Class Listener Interface Description

An event that indicates that a component-


defined action occurred like a button click or
ActionEvent ActionListener
selecting an item from the menu-item list.

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.

An event that indicates that a component


ComponentEvent ComponentListener
moved, the size changed or changed its
Event Class Listener Interface Description

visibility.

When a component is added to a container


ContainerEvent ContainerListener (or) removed from it, then this event is
generated by a container object.

These are focus-related events, which


FocusEvent FocusListener
include focus, focusin, focusout, and blur.

An event that indicates whether an item


ItemEvent ItemListener
was selected or not.

An event that occurs due to a sequence of


KeyEvent KeyListener
keypresses on the keyboard.

The events that occur due to the user


MouseListener &
MouseEvent interaction with the mouse (Pointing Device).
MouseMotionListener

An event that specifies that the mouse


MouseWheelEvent MouseWheelListener
wheel was rotated in a component.

An event that occurs when an object’s text


TextEvent TextListener
changes.

An event which indicates whether a


WindowEvent WindowListener
window has changed its status or not.

Different interfaces consists of different methods which are specified below.

Listener Interface Methods

ActionListener • actionPerformed()

AdjustmentListener • adjustmentValueChanged()
Listener Interface Methods

• componentResized()
• componentShown()
ComponentListener
• componentMoved()
• componentHidden()

• componentAdded()
ContainerListener
• componentRemoved()

• focusGained()
FocusListener
• focusLost()

ItemListener • itemStateChanged()

• keyTyped()
KeyListener • keyPressed()
• keyReleased()

• mousePressed()
• mouseClicked()
MouseListener • mouseEntered()
• mouseExited()
• mouseReleased()

• mouseMoved()
MouseMotionListener
• mouseDragged()

MouseWheelListener • mouseWheelMoved()

TextListener • textChanged()

• windowActivated()
• windowDeactivated()
• windowOpened()
WindowListener • windowClosed()
• windowClosing()
• windowIconified()
• windowDeiconified()
Flow of Event Handling

1. User Interaction with a component is required to generate an event.


2. The object of the respective event class is created automatically after event generation,
and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.

Code-Approaches

The three approaches for performing event handling are by placing the event handling
code in one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class

Events

➢ An Event is an object representing an occurrence within a program that the


application can respond to.
➢ In Java, events are objects of classes in the [Link] package.
➢ Some common types of events include:

1. ActionEvent: Triggered by actions such as button clicks, menu selections, or pressing


"Enter" in a text field.
2. MouseEvent: Generated by mouse actions, such as clicks, movements, and releases.
3. KeyEvent: Occurs when a key on the keyboard is pressed, released, or typed.
4. FocusEvent: Triggered when a component gains or loses focus, like when a text field
becomes active.
5. WindowEvent: Triggered by actions on a window, such as opening, closing,
minimizing, or maximizing it.

Each event has specific methods to provide information about the event, such as its type, the
component that triggered it, and details like the mouse coordinates or which key was pressed.

Event Sources

➢ An Event Source is an object that generates events. When an event occurs (e.g., a
user clicks a button), the event source notifies any event listeners that are registered to
handle that event. Some common event sources include:

1. Button: A button is an event source for ActionEvent, triggered when the button is
clicked.
2. Text Field: A text field generates ActionEvent (when "Enter" is pressed) and
FocusEvent (when it gains or loses focus).
3. Window: Windows, such as frames or dialogs, generate WindowEvent (e.g., on
opening or closing).
4. Mouse: Components that are sensitive to mouse actions, like panels, generate
MouseEvent and MouseMotionEvent.
5. Keyboard: Components that accept keyboard input generate KeyEvent.

The event source holds a list of listeners that are registered to receive notifications about
specific events. When an event occurs, the event source invokes the appropriate method on
each registered listener.

Working with Event Sources and Listeners in Java

To make a component respond to an event, you:

1. Register the Event Listener: Use methods like addActionListener,


addMouseListener, etc., to register a listener with an event source.
2. Implement the Listener Interface: Define methods to handle the event, usually
within an inner class or with lambda expressions.

import [Link].*;
import [Link];
import [Link];
public class EventSourceExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Source Example");
JButton button = new JButton("Click Me");
// Register the button (event source) with an ActionListener (event listener)
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
}
});
[Link](button);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

How Event Sources and Events Work Together

1. Event Creation: When an action occurs, the event source (e.g., button) generates an
event object (ActionEvent).
2. Event Dispatching: The event is dispatched to the registered listeners. The
actionPerformed method in ActionListener is called automatically.
3. Event Handling: The listener executes the code within the event handler method,
creating the response (in this case, printing to the console).
Examples of Event Sources in Different UI Components

• JButton (Button): Generates ActionEvent when clicked.


• JTextField (Text Field): Generates ActionEvent when Enter is pressed and
FocusEvent when it gains/loses focus.
• JFrame (Window): Generates WindowEvent for window state changes.
• JPanel (Panel): Generates MouseEvent for mouse actions.

Event Sources and the Observer Pattern

Event-driven programming often follows the Observer Pattern, where the event source acts
as a subject, notifying registered observers (listeners) of changes (events). The listeners can
then react independently, making the UI more interactive and modular.

Best Practices in Event Handling with Event Sources

• Keep Event Handlers Lightweight: Avoid time-intensive tasks in event handlers to


maintain responsiveness.
• Use Lambda Expressions: In Java 8+, lambda expressions simplify event listener
code, especially for simple actions.
• Unregister Unused Listeners: Remove listeners when they’re no longer needed to
prevent memory leaks.
• Separate Logic from UI Code: Use methods or classes to keep event handling code
organized and maintainable.

Event Listeners

➢ Event Listeners are interfaces in Java (and other languages with similar patterns) that
handle various types of events, such as user actions (clicks, key presses, etc.).
➢ In Java, event listeners belong to the [Link] and [Link] packages.
They "listen" for specific events on UI components and execute code in response.
Here’s an overview of how event listeners work, some common event listener types, and an
example of implementing them.

How Event Listeners Work

1. Define and Register the Listener: An event listener is an interface with one or more
methods related to a specific type of event. You register a listener to a component
using methods like addActionListener, addMouseListener, etc.
2. Event Triggering: When an event occurs (e.g., a button is clicked), the registered
listener(s) is notified.
3. Handle the Event: The listener’s event handling method(s) are automatically called,
executing any code inside.

Common Event Listener Types in Java

Here are some frequently used event listener interfaces, along with their related events and
methods:

1. ActionListener
o Purpose: Handles ActionEvent, typically used for buttons, menu items, and
other actions.
o Method: void actionPerformed(ActionEvent e)
o Example Usage: Clicking a button or pressing "Enter" in a text field.

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
}
});

2. MouseListener

• Purpose: Handles mouse events (e.g., clicks, entry, exit).


• Methods:
o void mouseClicked(MouseEvent e)
o void mousePressed(MouseEvent e)
o void mouseReleased(MouseEvent e)
o void mouseEntered(MouseEvent e)
o void mouseExited(MouseEvent e)

java
Copy code
[Link](new MouseListener() {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked on button");
}
// Implement other methods if needed
});
3. MouseMotionListener

• Purpose: Handles mouse movements, such as dragging and moving.


• Methods:
o void mouseDragged(MouseEvent e)
o void mouseMoved(MouseEvent e)

4. KeyListener

• Purpose: Responds to keyboard actions.


• Methods:
o void keyPressed(KeyEvent e)
o void keyReleased(KeyEvent e)
o void keyTyped(KeyEvent e)

java
Copy code
[Link](new KeyListener() {
public void keyPressed(KeyEvent e) {
[Link]("Key pressed: " + [Link]());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});

5. WindowListener
o Purpose: Handles events related to window state (e.g., open, close, minimize).
o Methods:

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)
java
Copy code
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link]("Window is closing");
[Link](0);
}
});

6. FocusListener
o Purpose: Responds to focus events, like gaining or losing focus.
o Methods:
1. void focusGained(FocusEvent e)
2. void focusLost(FocusEvent e)
7. ItemListener
o Purpose: Handles item selection events (e.g., checkboxes, combo boxes).
o Method: void itemStateChanged(ItemEvent e)

java
Copy code
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if ([Link]() == [Link]) {
[Link]("Checkbox selected");
}
}
});

8. ChangeListener
o Purpose: Handles change events, used with components like sliders or
spinners.
o Method: void stateChanged(ChangeEvent e)

Using Adapter Classes for Convenience

➢ Some listeners have multiple methods, but sometimes you only need one or two.
Adapter classes provide default implementations, so you only override the methods
you need. Common adapters include:

• MouseAdapter: Implements MouseListener and MouseMotionListener.


• WindowAdapter: Implements WindowListener.

Example with WindowAdapter:

java
Copy code
[Link](new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
[Link]("Window closing");
}
});

Lambda Expressions for Simplifying Event Handling

➢ Since Java 8, lambda expressions can be used to write shorter code for single-method
listeners (like ActionListener or ItemListener):

java
Copy code
[Link](e -> [Link]("Button clicked!"));
[Link](e -> [Link]("Checkbox state changed"));
Example Program: Using Multiple Event Listeners

This example program creates a GUI with a button, a text field, and a checkbox, each with
their own event listeners:

import [Link].*;
import [Link].*;
public class EventListenerExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Listener Example");
JButton button = new JButton("Click Me");
JTextField textField = new JTextField(20);
JCheckBox checkBox = new JCheckBox("Check Me");

// Button click event


[Link](e -> [Link]("Button was clicked!"));

// Text field key event


[Link](new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
[Link]("Key pressed: " + [Link]());
}
});

// Checkbox item event


[Link](e -> {
if ([Link]() == [Link]) {
[Link]("Checkbox selected");
} else {
[Link]("Checkbox deselected");
}
});

JPanel panel = new JPanel();


[Link](button);
[Link](textField);
[Link](checkBox);

[Link](panel);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

Best Practices for Event Listeners

• Keep Handlers Lightweight: Minimize code inside listeners to keep the UI


responsive.
• Separate Complex Logic: Use methods to separate event-handling code from main
logic.
• Unregister Listeners if Needed: To avoid memory leaks, unregister listeners when
no longer needed.

Event Delegation Model (EDM)

➢ The Event Delegation Model (EDM) is a design approach used in Java (and other
event-driven frameworks) to handle events in a more organized and efficient way.
➢ The model is built around three core concepts: event sources, events, and event
listeners.
➢ Rather than every UI component processing its own events, the Event Delegation
Model delegates responsibility for handling events to a dedicated listener object.
➢ This approach enhances code modularity, scalability, and performance.

Overview of the Event Delegation Model

➢ In the EDM, when an event occurs (e.g., a button is clicked), the event source
generates an event object that contains information about the event.
➢ This event object is then passed to one or more listeners that are registered to handle
the event.
➢ The model follows the Observer pattern, where listeners (observers) "listen" for
events from event sources (subjects) and respond accordingly.

Key Components of the Event Delegation Model

1. Event Source
o The component that generates the event, such as a button, text field, or
window.
o Registers listeners to notify them when a specific event occurs.
2. Event Object
o An object that encapsulates information about an event, such as its type (e.g.,
ActionEvent, MouseEvent) and additional data (e.g., mouse coordinates or key
codes).
o Provides methods to access event details and identify the event source.
3. Event Listener
o An interface or class with methods to respond to specific event types.
o Listens to events generated by the event source and defines how to handle
them.
o Registered with an event source through methods like addActionListener,
addMouseListener, etc.

How the Event Delegation Model Works

1. Registration: An event listener is registered with an event source (e.g., JButton,


JTextField). The event source stores a reference to the listener.
2. Event Generation: When an action occurs (e.g., a button click), the event source
creates an event object (e.g., ActionEvent) containing details of the event.
3. Event Notification: The event source calls the relevant method(s) on all registered
listeners, passing the event object.
4. Event Handling: The event listener’s method(s) execute any code needed to handle
the event, often modifying the UI or performing other actions based on user input.

Example of the Event Delegation Model

Here’s a simple Java example demonstrating the Event Delegation Model using JButton as an
event source and ActionListener as an event listener:

java
Copy code
import [Link].*;
import [Link];
import [Link];
public class EventDelegationExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Delegation Model Example");
JButton button = new JButton("Click Me");

// Registering the ActionListener with the JButton (Event Source)


[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
}
});

[Link](button);
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Explanation:

• button is the event source. It generates ActionEvent when clicked.


• The ActionListener listens to ActionEvent. When the button is clicked, the
actionPerformed method in ActionListener executes the specified code.

Advantages of the Event Delegation Model

1. Modularity: By separating event handling code from UI components, EDM allows


for a modular design where listeners handle events independently from the component
generating them.
2. Reusability: Listeners can be reused across different components, reducing code
duplication.
3. Efficiency: Rather than embedding event handling in each component, EDM
delegates it to listeners, allowing components to focus on their primary function and
reducing system load.
4. Scalability: Adding new event handling logic is straightforward, as new listeners can
be registered or added without modifying the existing event source.

Key Principles in Implementing EDM

1. Separation of Concerns: Listeners handle events, and components only generate


them. This makes the code cleaner and maintains a separation between UI elements
and business logic.
2. Single Responsibility: Each listener is responsible for handling a specific type of
event, keeping the code organized.
3. Event Adapter Classes: Use adapter classes (e.g., MouseAdapter, WindowAdapter)
to handle only required methods, reducing code complexity when working with
listeners that have multiple methods.
4. Using Anonymous Classes or Lambdas: For single-use listeners, Java’s anonymous
classes or lambdas (Java 8+) can simplify code.

java
Copy code

[Link](e -> [Link]("Button clicked!"));

Other Examples of Event Delegation in UI Frameworks

➢ Java Swing and AWT aren’t the only UI frameworks that use EDM. Other
frameworks with similar models include:

• JavaScript DOM Events: In JavaScript, events such as click or keyup use an event
delegation model. Event listeners are registered with DOM elements, and event
handlers respond when events are triggered.
• Android: In Android, events are handled by [Link],
[Link], and similar interfaces for touch and sensor events.
Best Practices in the Event Delegation Model

1. Unregister Listeners: In some cases, unregister listeners when they’re no longer


needed, especially in applications where components are created and removed
frequently, to avoid memory leaks.
2. Avoid Complex Logic in Listeners: Keep event handling code lightweight. If
necessary, delegate heavy tasks to separate methods or classes.
3. Organize Listeners for Clarity: For complex applications, create separate classes or
methods for handling specific types of events to keep code organized and
maintainable.
4. Use Lambda Expressions (Java 8+): For concise event handling, lambdas can
reduce boilerplate code in simple listeners.

HandlingMouse and Keyboard Events

1. Handling Mouse Events

Java provides two main interfaces for handling mouse events:

• MouseListener: Handles basic mouse actions such as clicks, presses, releases,


entering, and exiting a component.
• MouseMotionListener: Handles mouse movement, including dragging and moving.

MouseListener Interface

This interface has five methods, which respond to specific mouse actions:

• mouseClicked(MouseEvent e): Invoked when the mouse button is clicked (pressed


and released).
• mousePressed(MouseEvent e): Invoked when a mouse button is pressed.
• mouseReleased(MouseEvent e): Invoked when a mouse button is released.
• mouseEntered(MouseEvent e): Invoked when the mouse enters a component’s area.
• mouseExited(MouseEvent e): Invoked when the mouse leaves a component’s area.

MouseMotionListener Interface

This interface has two methods:

• mouseDragged(MouseEvent e): Invoked when the mouse is pressed and dragged.


• mouseMoved(MouseEvent e): Invoked when the mouse is moved (without pressing).

Example of Handling Mouse Events


import [Link].*;
import [Link].*;

public class MouseEventExample extends JFrame {


public MouseEventExample() {
JButton button = new JButton("Click or Hover");
// MouseListener for click and hover events
[Link](new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked at coordinates: " + [Link]() + ", " +
[Link]());
}

@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse released");
}

@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse entered the button area");
}

@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse exited the button area");
}
});

// MouseMotionListener for mouse movements


[Link](new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
[Link]("Mouse dragged at coordinates: " + [Link]() + ", " +
[Link]());
}

@Override
public void mouseMoved(MouseEvent e) {
[Link]("Mouse moved at coordinates: " + [Link]() + ", " +
[Link]());
}
});

add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new MouseEventExample();
}
}

1. Using MouseAdapter

If you only need to handle some mouse events, you can use the MouseAdapter class, which
provides default implementations for MouseListener and MouseMotionListener methods, so
you can override only the ones you need.

[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked!");
}
});

2. Handling Keyboard Events

The KeyListener interface is used to handle keyboard events. This interface has three
methods:

• keyPressed(KeyEvent e): Invoked when a key is pressed down.


• keyReleased(KeyEvent e): Invoked when a key is released.
• keyTyped(KeyEvent e): Invoked when a key is typed (pressed and released for
characters that generate a character).

KeyEvent Methods

• [Link](): Returns the code of the key pressed (e.g., KeyEvent.VK_ENTER).


• [Link](): Returns the character of the key typed (e.g., 'a').

Example of Handling Keyboard Events


import [Link].*;
import [Link].*;

public class KeyEventExample extends JFrame {


public KeyEventExample() {
JTextField textField = new JTextField(20);

// KeyListener for keyboard events


[Link](new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
[Link]("Key pressed: " +
[Link]([Link]()));
}

@Override
public void keyReleased(KeyEvent e) {
[Link]("Key released: " +
[Link]([Link]()));
}

@Override
public void keyTyped(KeyEvent e) {
[Link]("Key typed: " + [Link]());
}
});

add(textField);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new KeyEventExample();
}
}

Keyboard Shortcuts

In some applications, you may want specific keys to trigger actions. KeyBindings can be a
more modern approach than KeyListener for complex key shortcuts, as it allows assigning
actions directly to components using key-stroke mappings.

[Link](JComponent.WHEN_FOCUSED).put([Link]
e("ctrl Z"), "Undo");
[Link]().put("Undo", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Undo action performed");
}
});

Handling mouse and keyboard events in Java allows you to make applications interactive by
responding to user actions, such as mouse clicks, movements, and keyboard presses. These
events are managed by event listeners, specifically MouseListener, MouseMotionListener,
and KeyListener for mouse and keyboard events, respectively.

1. Handling Mouse Events

Java provides two main interfaces for handling mouse events:

• MouseListener: Handles basic mouse actions such as clicks, presses, releases,


entering, and exiting a component.
• MouseMotionListener: Handles mouse movement, including dragging and moving.
MouseListener Interface

This interface has five methods, which respond to specific mouse actions:

• mouseClicked(MouseEvent e): Invoked when the mouse button is clicked (pressed


and released).
• mousePressed(MouseEvent e): Invoked when a mouse button is pressed.
• mouseReleased(MouseEvent e): Invoked when a mouse button is released.
• mouseEntered(MouseEvent e): Invoked when the mouse enters a component’s area.
• mouseExited(MouseEvent e): Invoked when the mouse leaves a component’s area.

MouseMotionListener Interface

This interface has two methods:

• mouseDragged(MouseEvent e): Invoked when the mouse is pressed and dragged.


• mouseMoved(MouseEvent e): Invoked when the mouse is moved (without pressing).

Example of Handling Mouse Events


java
Copy code
import [Link].*;
import [Link].*;

public class MouseEventExample extends JFrame {


public MouseEventExample() {
JButton button = new JButton("Click or Hover");

// MouseListener for click and hover events


[Link](new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked at coordinates: " + [Link]() + ", " + [Link]());
}

@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse released");
}

@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse entered the button area");
}

@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse exited the button area");
}
});

// MouseMotionListener for mouse movements


[Link](new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
[Link]("Mouse dragged at coordinates: " + [Link]() + ", " + [Link]());
}

@Override
public void mouseMoved(MouseEvent e) {
[Link]("Mouse moved at coordinates: " + [Link]() + ", " + [Link]());
}
});

add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new MouseEventExample();
}
}

Using MouseAdapter

➢ If you only need to handle some mouse events, you can use the MouseAdapter class,
which provides default implementations for MouseListener and
MouseMotionListener methods, so you can override only the ones you need.

java
Copy code
[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked!");
}
});

2. Handling Keyboard Events

The KeyListener interface is used to handle keyboard events. This interface has three
methods:

• keyPressed(KeyEvent e): Invoked when a key is pressed down.


• keyReleased(KeyEvent e): Invoked when a key is released.
• keyTyped(KeyEvent e): Invoked when a key is typed (pressed and released for
characters that generate a character).

KeyEvent Methods

• [Link](): Returns the code of the key pressed (e.g., KeyEvent.VK_ENTER).


• [Link](): Returns the character of the key typed (e.g., 'a').

Example of Handling Keyboard Events


java
Copy code
import [Link].*;
import [Link].*;

public class KeyEventExample extends JFrame {


public KeyEventExample() {
JTextField textField = new JTextField(20);

// KeyListener for keyboard events


[Link](new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
[Link]("Key pressed: " + [Link]([Link]()));
}

@Override
public void keyReleased(KeyEvent e) {
[Link]("Key released: " + [Link]([Link]()));
}

@Override
public void keyTyped(KeyEvent e) {
[Link]("Key typed: " + [Link]());
}
});

add(textField);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new KeyEventExample();
}
}
Keyboard Shortcuts

➢ In some applications, you may want specific keys to trigger actions. KeyBindings can
be a more modern approach than KeyListener for complex key shortcuts, as it allows
assigning actions directly to components using key-stroke mappings.

java
Copy code
[Link](JComponent.WHEN_FOCUSED).put([Link]("ctrl
Z"), "Undo");
[Link]().put("Undo", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Undo action performed");
}
});

Common Applications of Mouse and Keyboard Events

• Mouse Events: Clicking buttons, detecting drag-and-drop actions, drawing programs,


and interactive games.
• Keyboard Events: Typing in text fields, implementing shortcuts (e.g., Ctrl+C for
copy), and game controls (e.g., arrow keys to move a character).

Best Practices for Handling Mouse and Keyboard Events

1. Use Adapters if Needed: For complex listeners, use MouseAdapter and KeyAdapter
to override only necessary methods.
2. Keep Event Handlers Lightweight: Avoid long-running tasks within event methods
to keep the UI responsive.
3. Use Lambda Expressions: In Java 8+, lambdas make it easier to write concise
listener code for simple actions.
4. Consider Accessibility: Ensure that keyboard shortcuts and mouse interactions are
intuitive and that alternative inputs are accessible.

Adapter Classes
➢ Adapter classes are abstract classes in Java that provide empty implementations of all
methods in an interface.
➢ They are commonly used with event listener interfaces that have multiple methods,
such as MouseListener, MouseMotionListener, or WindowListener.
➢ Adapter classes allow you to override only the methods you need, rather than
implementing every method in the interface, even if you don't use them.

Why Use Adapter Classes?

➢ Adapter classes reduce the need to implement all methods in an interface when only a
few are relevant.
➢ They simplify code by providing default implementations for methods you don’t
need, allowing you to focus on those you do.
Examples of Adapter Classes in Java

Java provides several adapter classes for common listener interfaces:

1. MouseAdapter: Implements MouseListener and MouseMotionListener, allowing you


to override only the mouse methods you need.
2. KeyAdapter: Implements KeyListener, allowing you to override only specific
keyboard events.
3. WindowAdapter: Implements WindowListener, allowing you to override only
window-related events you need.
4. FocusAdapter: Implements FocusListener, used for focus-related events.

Example Using MouseAdapter


import [Link].*;
import [Link].*;

public class AdapterExample extends JFrame {


public AdapterExample() {
JButton button = new JButton("Click or Hover");

// Using MouseAdapter to handle only mouseClicked event


[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked on button");
}
});

add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


new AdapterExample();
}
}

Explanation: Here, MouseAdapter allows you to implement only the mouseClicked method
without the need to override mousePressed, mouseReleased, etc., which MouseListener
would require if you implemented it directly.

Inner Classes

➢ Inner classes are classes defined within another class. They have access to the fields
and methods of the outer class, even if they are private. Java supports several types of
inner classes:

1. Non-static Inner Classes (or Regular Inner Classes): These are tied to an instance
of the outer class and can access its instance variables and methods.
2. Static Inner Classes: Defined with the static keyword, they do not require an instance
of the outer class and can only access static members of the outer class.
3. Anonymous Inner Classes: These are inner classes without a name, typically used to
define one-off event listeners or interface implementations.
4. Local Inner Classes: Defined within a method or block, these classes are accessible
only within the scope of that method or block.

Why Use Inner Classes?

➢ Inner classes are useful when you need to create small helper classes, especially for
event handling, that are tightly coupled with an outer class. They help organize code
by keeping classes that are only relevant to a specific part of your application
contained within that scope.

Examples of Inner Classes for Event Handling

1. Regular Inner Class Example

➢ A regular inner class can be useful if you want to handle events in a dedicated listener
class that still has access to the outer class's fields and methods.

import [Link].*;
import [Link].*;

public class InnerClassExample extends JFrame {


private JButton button;

public InnerClassExample() {
button = new JButton("Click Me");
[Link](new ButtonClickListener());

add(button);
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

// Inner class that handles button click events


private class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button was clicked!");
}
}

public static void main(String[] args) {


new InnerClassExample();
}
}
Explanation: ButtonClickListener is an inner class with access to the outer class's private
fields (like button) and can be used directly to handle events.

2. Anonymous Inner Class Example

➢ Anonymous inner classes are often used for quick event handling because they are
concise and only require one-time use.

java
Copy code
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked!");
}
});

In Java 8 and later, you can simplify this further with a lambda expression if the interface has
only one method:

java
Copy code
[Link](e -> [Link]("Button clicked!"));

3. Local Inner Class Example

➢ Local inner classes are defined inside a method, and they’re often used when the logic
is specific to that method.

java
Copy code
public void createButtonWithListener() {
class ButtonClickListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked from a local inner class!");
}
}

JButton button = new JButton("Click Me");


[Link](new ButtonClickListener());
add(button);
}

Adapter Classes vs. Inner Classes

• Adapter Classes are useful for selectively overriding specific methods in interfaces
with multiple methods, like MouseListener. They’re typically used when you want to
simplify code by avoiding the implementation of unnecessary methods.
• Inner Classes are suitable when you want to create a helper class closely tied to the
outer class. They provide access to the outer class's methods and fields, making them
useful for event handling and other tasks that require access to the outer class.

Best Practices

1. Use Adapter Classes for Multi-Method Interfaces: If you’re only interested in a


few methods of an interface like MouseListener, use MouseAdapter instead to avoid
boilerplate code.
2. Use Anonymous Inner Classes for One-Time Listeners: If an event handler is
simple and used only once, an anonymous inner class (or a lambda) keeps the code
concise.
3. Use Inner Classes to Encapsulate Related Logic: For complex events that need
access to the outer class's fields or methods, use a named inner class. This keeps the
event-handling logic organized and accessible only within the outer class.
4. Avoid Overusing Inner Classes: Use inner classes sparingly. They can clutter the
outer class and sometimes lead to code that's hard to maintain. Prefer separate classes
for more complex event handling.

MCQ’S
1. What is the purpose of a Label in AWT?
a) To display text b) To receive user input
c) To perform an action d) To display an image
2. Which method is used to set the text of a Label?
a) setText() b) getText() c) setLabel() d) getLabel()
3. Which class is the superclass of Button and TextField?
a) Component b) Container c) Panel d) Frame
4. What is the purpose of the ActionListener interface?
a) To handle mouse events b) To handle keyboard events
c) To handle button clicks d) To handle text input
5. What is the purpose of a CheckBox?
a) To select multiple options b) To select a single option
c) To display text d) To receive user input
6. Which class is used to group CheckBoxes?
a) CheckboxGroup b) RadioButton c) Choice d) List
7. What is the purpose of a Choice?
a) To select a single option b) To select multiple options
c) To display text d) To receive user input
8. Which method is used to add items to a List?
a) add() b) addItem() c) addElement() d) addList()
9. What is the purpose of a Panel?
a) To group components b) To display text
c) To receive user input d) To perform an action
10. Which class is used to add scrolling capability to a component?
a) ScrollPane b) ScrollBar c) Panel d) Frame
11. What is the purpose of a Menu?
a) To provide options to the user b) To display text
c) To receive user input d) To perform an action
12. Which class is used to create a menu item?
a) MenuItem b) Menu c) MenuBar d) CheckboxMenuItem
13. What is the purpose of a ScrollBar?
a) To add scrolling capability to a component b) To display text
c) To receive user input d) To perform an action
14. Which method is used to set the scroll bar's minimum value?
a) setMinimum() b) setMaximum() c) setValue() d) setUnitIncrement()
15. What is the purpose of a Frame?
a) To provide a window for an application b) To display text
c) To receive user input d) To perform an action
16. Which method is used to set the title of a Frame?
a) setTitle() b) getTitle() c) setLabel() d) getLabel()
17. Which class is used to represent color?
a) Color b) Font c) Graphics d) FontMetrics
18. Which method is used to set the font of a component?
a) setFont() b) getFont() c) setLabel() d) getLabel()
19. What is the purpose of a Layout Manager?
a) To arrange components in a container b) To display text
c) To receive user input d) To perform an action
20. Which layout manager is used to arrange components in a grid?
a) GridLayout b) FlowLayout c) BorderLayout d) CardLayout
21. What is an event in Java?
a) A user interaction with a GUI component b) A system-generated notification
c) A method call d) A variable declaration
22. Which of the following is an example of an event?
a) Button click b) Variable assignment c) Method invocation d) Loop iteration
23. What is an event source in Java?
a) A GUI component that generates events b) A listener interface
c) A handler method d) A event object
24. Which of the following is an example of an event source?
a) JButton b) ActionListener c) actionPerformed() d) ActionEvent
25. What is an event listener in Java?
a) A method that handles events b) A GUI component that generates events
c) An interface that defines event handling methods d) An event object
26. Which of the following is an example of an event listener interface?
a) ActionListener b) ActionEvent c) JButton d) JFrame
27. What is the purpose of the actionPerformed() method?
a) To handle action events b) To handle mouse events
c) To handle keyboard events d) To handle window events
8. Which method is called when a button is clicked?
a) actionPerformed() b) mouseClicked() c) keyTyped() d) windowOpened()
29. How do you register an event listener with a GUI component?
a) Using the addListener() method b) Using the addActionListener() method
c) Using the addMouseListener() method d) Using the addKeyListener() method
30. What happens when an event listener is not registered with a GUI component?
a) The event is ignored b) The event is handled by a default listener
c) The event is propagated to the parent component d) An exception is thrown
31. What is the primary purpose of the Event Delegation Model?
a) To handle events directly by GUI components
b) To delegate event handling to separate objects
c) To propagate events to parent components d) To ignore events
32. Which of the following is a key benefit of using EDM?
a) Improved performance b) Simplified event handling
c) Increased complexity d) Reduced flexibility
33. In EDM, what is the role of an event source?
a) To handle events b) To generate events
c) To delegate events d) To ignore events
34. What is the role of an event listener in EDM?
a) To generate events b) To handle events c) To delegate events d) To ignore events
35. How do you register an event listener with an event source in EDM?
a) Using the addListener() method b) Using the addActionListener() method
c) Using the addMouseListener() method d) Using the registerListener() method
36. What happens when an event is received by an event listener?
a) It is ignored b) It is propagated to the parent component
c) It is handled by the listener d) It is delegated to another listener
37. What is a primary advantage of using EDM?
a) Improved performance b) Simplified event handling
c) Increased complexity d) Reduced flexibility
38. What is a potential disadvantage of using EDM?
a) Increased flexibility b) Improved performance
c) Tight coupling between components d) Reduced complexity
39. How does EDM differ from the Event-Inheritance Model?
a) EDM uses inheritance, while Event-Inheritance Model does not
b) EDM uses delegation, while Event-Inheritance Model uses inheritance
c) EDM is more complex, while Event-Inheritance Model is simpler
d) EDM is less flexible, while Event-Inheritance Model is more flexible
40. What is a key similarity between EDM and the Observer Pattern?
a) Both use inheritance b) Both use delegation
c) Both use event handling d) Both use observer-subject relationships
41. Which interface is used to handle mouse events in Java?
a) MouseListener b) MouseMotionListener c) KeyListener d) ActionListener
42. What method is called when the mouse is clicked?
a) mouseClicked() b) mousePressed() c) mouseReleased() d) mouseEntered()
43. Which method is used to track mouse movements?
a) mouseMoved() b) mouseDragged() c) mousePressed() d) mouseReleased()
44. Which interface is used to handle keyboard events in Java?
a) KeyListener b) MouseListener c) ActionListener d) WindowListener
45. What method is called when a key is pressed?
a) keyPressed() b) keyReleased() c) keyTyped() d) mouseClicked()
46. What is the purpose of an adapter class?
a) To provide a default implementation for an interfaceb) To extend an abstract class
c) To implement multiple interfaces d) To override a method
47. Which adapter class is used for mouse events?
a) MouseAdapter b) KeyAdapter c) WindowAdapter d) ActionListener
48. What is an inner class in Java?
a) A class within another class b) A subclass of another class
c) An interface implementation d) An abstract class
49. What is the benefit of using inner classes?
a) Improved encapsulation b) Increased complexity
c) Reduced flexibility d) Simplified inheritance
50. Which type of inner class is used to handle events?
a) Nested class b) Static inner class
c) Anonymous inner class d) Local inner class
5 MARK QUESTIONS

1. What is the purpose of the FlowLayout layout manager in AWT?


2. Describe the difference between CheckBox and CheckboxGroup in AWT.
3. Write a Java code snippet to create a Label component with the text "Hello
World" and add it to a Frame.
4. Explain the concept of Event Delegation Model (EDM) in AWT event handling.
5. What is the role of adapter classes in AWT event handling? Provide an example.
6. What is the difference between ActionEvent and MouseEvent in AWT?
7. Explain the concept of event sources in AWT.
8. Describe the purpose of the ScrollPane component in AWT.

10-MARK QUESTIONS

1. Create a Java program to demonstrate the use of Button, TextField, and


CheckBox components in AWT.
2. Describe the hierarchy of AWT classes and explain the relationship
between Component, Container, and Window.
3. Implement event handling for mouse clicks on a Button component
using an anonymous inner class. Provide Java code.
4. Compare and contrast BorderLayout and GridLayout layout managers in
AWT. Provide examples.
5. Develop a Java program to create a simple menu bar with options using AWT's
Menu and MenuItem classes.
6. Create a comprehensive Java program demonstrating various AWT
components, including labels, buttons, text fields, checkboxes, and menus.
7. Explain the Event Delegation Model (EDM) in AWT event handling,
including its advantages and disadvantages.

UNIT V
SWING
➢ Swing is a Java Foundation Classes [JFC] library and an extension of the
Abstract Window Toolkit [AWT].
➢ Java Swing offers much-improved functionality over AWT, new components,
expanded components features, and excellent event handling with drag-and-
drop support.

Introduction of Java Swing


➢ Swing has about four times the number of User Interface [UI] components as
AWT and is part of the standard Java distribution.
➢ By today’s application GUI requirements, AWT is a limited implementation,
not quite capable of providing the components required for developing
complex GUIs required in modern commercial applications.
➢ The AWT component set has quite a few bugs and does take up a lot of
system resources when compared to equivalent Swing resources.
➢ Netscape introduced its Internet Foundation Classes [IFC] library for use
with Java.
➢ Its Classes became very popular with programmers creating GUI’s for
commercial applications.

• Swing is a Set of API (API- Set of Classes and Interfaces)


• Swing is Provided to Design Graphical User Interfaces
• Swing is an Extension library to the AWT (Abstract Window Toolkit)
• Includes New and improved Components that have been enhancing the looks
and Functionality of GUIs’
• Swing can be used to build (Develop) The Standalone swing GUI Apps as
Servlets and Applets
• It Employs model/view design architecture.
• Swing is more portable and more flexible than AWT, the Swing is built on top
of the AWT.
• Swing is Entirely written in Java.
• Java Swing Components are Platform-independent, and The Swing Components
are lightweight.
• Swing Supports a Pluggable look and feel and Swing provides more powerful
components.
• such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
• Further Swing Follows MVC.
Difference between Java Swing and Java AWT

➢ There are certain points from which Java Swing is different than Java AWT
as mentioned below:
Java AWT Java Swing

Swing is a part of Java Foundation


Java AWT is an API to develop GUI
Classes and is used to create various
applications in Java.
applications.

Components of AWT are heavy The components of Java Swing are


weighted. lightweight.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.

AWT components require [Link] Swing components requires


package. [Link] package.

What is JFC?
➢ JFC stands for Java Foundation Classes. JFC is the set of GUI components
that simplify desktop Applications.
➢ Many programmers think that JFC and Swing are one and the same thing, but
that is not so.
➢ JFC contains Swing [A UI component package] and quite a number of other
items:
• Cut and paste: Clipboard support.
• Accessibility features: Aimed at developing GUIs for users with disabilities.
• The Desktop Colors Features were first introduced in Java 1.1
• Java 2D: it has Improved colors, images, and text support.

Features Of Swing Class


• Pluggable look and feel.
• Uses MVC architecture.
• Lightweight Components
• Platform Independent
• Advanced features such as JTable, JTabbedPane, JScollPane, etc.
• Java is a platform-independent language and runs on any client machine, the
GUI look and feel, owned and delivered by a platform-specific O/S, simply does
not affect an application’s GUI constructed using Swing components.

• Lightweight Components: Starting with the JDK 1.1, its AWT-supported


lightweight component development. For a component to qualify as lightweight,
it must not depend on any non-Java [O/s based) system classes. Swing
components have their own view supported by Java’s look and feel classes.

• Pluggable Look and Feel: This feature enable the user to switch the look and
feel of Swing components without restarting an application. The Swing library
supports components’ look and feels that remain the same across all platforms
wherever the program runs. The Swing library provides an API that gives real
flexibility in determining the look and feel of the GUI of an application

• Highly customizable – Swing controls can be customized in a very easy way as


visual appearance is independent of internal representation.

• Rich controls– Swing provides a rich set of advanced controls like Tree
TabbedPane, slider, colorpicker, and table controls.

Swing Classes Hierarchy

The MVC Connection


• In general, a visual component is a composite of three distinct aspects:
1. The way that the component looks when rendered on the screen.
2. The way such that the component reacts to the user.
3. The state information associated with the component.
• Over the years, one component architecture has proven itself to be exceptionally
effective: – Model-View-Controller or MVC for short.
• In MVC terminology, the model corresponds to the state information associated
with the Component.
• The view determines how the component is displayed on the screen, including
any aspects of the view that are affected by the current state of the model.
• The controller determines how the component reacts to the user.

The simplest Swing components have capabilities far beyond AWT


components as follows:

• Swing buttons and labels can be displaying images instead of or in addition to


text.
• The borders around most Swing components can be changed easily. For
example, it is easy to put a 1-pixel border around the outside of a Swing label.
• Swing components do not have to be rectangular. Buttons, for example, can be
round.
• Now The Latest Assertive technologies such as screen readers can easily get
information from Swing components. Example: A screen reader tool can easily
capture the text that is displayed on a Swing button or label.

Containers- Top level containers


➢ In Java, top-level containers are the highest-level GUI containers provided by
the Swing and AWT frameworks.
➢ These containers serve as the base for creating graphical user interfaces (GUIs)
and typically host other components like buttons, text fields, and panels.

Here are the top-level containers in Java:

1. JFrame

• Description: A window with title, borders, and buttons (e.g., close, minimize).
• Usage: Used for creating main application windows.
• Key Features:
o Can contain menus, panels, and other components.
o Provides methods like setSize(), setVisible(),
setDefaultCloseOperation().

Example:

java
Copy code
import [Link].*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("My JFrame");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}

2. JApplet

• Description: A container designed to run embedded in a web browser or


applet viewer.
• Usage: Primarily used in older applications for creating applets (deprecated in
modern Java versions).
• Key Features:
o Has lifecycle methods like init(), start(), stop(), and destroy().

Note: Java Applets are obsolete as modern browsers no longer support them.

3. JDialog

• Description: A pop-up window or dialog box for interacting with users.


• Usage: Used for modal or non-modal dialogs like alerts, confirmations, or
custom input dialogs.
• Key Features:
o Can be modal (blocks interaction with other windows) or non-modal.
o Often used with parent windows (e.g., JFrame).

Example:

java
Copy code
import [Link].*;

public class Main {


public static void main(String[] args) {
JDialog dialog = new JDialog();
[Link]("My Dialog");
[Link](200, 100);
[Link](true);
}
}
4. JWindow

• Description: A window without a title bar, menu bar, or borders.


• Usage: Useful for splash screens or floating tool windows.
• Key Features:
o Simplified container compared to JFrame.
o Typically not resizable.

Example:

java
Copy code
import [Link].*;

public class Main {


public static void main(String[] args) {
JWindow window = new JWindow();
JLabel label = new JLabel("Splash Screen", [Link]);
[Link](label);
[Link](300, 200);
[Link](true);
}
}

Comparison Table of Top-Level Containers

Has Title Supports


Container Use Case Key Feature
Bar? Menus?
Main application
JFrame Full-featured window Yes Yes
window
Runs in a browser or
JApplet Embedded GUI No Yes
applet viewer
Modal or non-modal
JDialog Dialog box Yes No
pop-ups
Splash screen, Borderless, lightweight
JWindow No No
tooltips container

These top-level containers act as the foundation for building Java desktop
applications. Each serves different purposes, and their choice depends on the specific
requirements of your GUI.
1. JFrame

• Purpose: Main application window.


• Description: A window with a title bar, minimize/maximize/close buttons, and
a content area.
• Use Case: To create standalone GUI applications.

Example:

java
Copy code
JFrame frame = new JFrame("My JFrame");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);

2. JWindow

• Purpose: Simplified window without a title bar or decorations.


• Description: Borderless container for temporary or lightweight windows.
• Use Case: Splash screens or floating tool windows.

Example:

java
Copy code
JWindow window = new JWindow();
[Link](300, 200);
[Link](true);

3. JDialog

• Purpose: Popup dialog box.


• Description: A secondary window for taking input or displaying messages.
• Use Case: Alerts, confirmations, or custom input forms.

Example:

java
Copy code
JDialog dialog = new JDialog(frame, "My Dialog", true);
[Link](200, 100);
[Link](true);
4. JPanel

• Purpose: Container for organizing components.


• Description: A lightweight container used to group and organize GUI
components.
• Use Case: Layout management and nesting components.

Example:

java
Copy code
JPanel panel = new JPanel();
[Link](new JButton("Click Me"));
[Link](panel);

5. JButton

• Purpose: Button for triggering actions.


• Description: A clickable button with text or an icon.
• Use Case: Submitting forms, executing commands.

Example:

java
Copy code
JButton button = new JButton("Click Me");
[Link](e -> [Link]("Button clicked"));

6. JToggleButton

• Purpose: Button that toggles between selected and unselected states.


• Description: Similar to a switch.
• Use Case: Settings, options toggling.

Example:

java
Copy code
JToggleButton toggleButton = new JToggleButton("Toggle Me");
[Link](e -> [Link]("State changed!"));

7. JCheckBox

• Purpose: Checkbox for selecting/deselecting options.


• Description: A toggleable box with an associated label.
• Use Case: Multi-select options.

Example:

java
Copy code
JCheckBox checkBox = new JCheckBox("Enable Feature");
[Link](e -> [Link]("Checked: " +
[Link]()));

8. JRadioButton

• Purpose: Radio button for mutually exclusive options.


• Description: Works in groups where only one can be selected.
• Use Case: Single-select options.

Example:

java
Copy code
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
ButtonGroup group = new ButtonGroup();
[Link](radioButton1);
[Link](radioButton2);

9. JLabel

• Purpose: Text or icon display.


• Description: Non-interactive component for displaying static text or images.
• Use Case: Labels for input fields or instructions.

Example:

java
Copy code
JLabel label = new JLabel("Enter your name:");

10. JTextField

• Purpose: Single-line text input.


• Description: Allows users to enter text in a single line.
• Use Case: Input for forms or data entry.

Example:
java
Copy code
JTextField textField = new JTextField(20);

11. JTextArea

• Purpose: Multi-line text input.


• Description: Allows for larger text input or display.
• Use Case: Comments, feedback, or logs.

Example:

java
Copy code
JTextArea textArea = new JTextArea(5, 20);

12. JList

• Purpose: List of selectable items.


• Description: Displays a scrollable list where users can select one or more
items.
• Use Case: Selection of items from a predefined list.

Example:

java
Copy code
JList<String> list = new JList<>(new String[] {"Item 1", "Item 2", "Item 3"});

13. JComboBox

• Purpose: Dropdown menu.


• Description: A combo box for selecting an option from a dropdown.
• Use Case: Selecting one item from a compact list.

Example:

java
Copy code
JComboBox<String> comboBox = new JComboBox<>(new String[] {"Option
1", "Option 2", "Option 3"});

14. JScrollPane

• Purpose: Adds scrollbars to components.


• Description: A container that provides scrolling capability to components.
• Use Case: Scrollable text areas, tables, or lists.

Example:

java
Copy code
JTextArea textArea = new JTextArea(5, 20);
JScrollPane scrollPane = new JScrollPane(textArea);
[Link](scrollPane);

MCQ’S
1. Swing is a part of which Java package?
a. [Link] b. [Link] c. [Link] d. [Link]
2. Swing components are:
a. Heavyweight b. Lightweight
c. Both heavyweight and lightweight d. None of the above
3. Which is the parent class of all Swing components?
a. Component b. Container c. JComponent d. Object
4. What is the key difference between AWT and Swing?
a. Swing is platform-dependent.
b. AWT uses a lightweight UI toolkit.
c. Swing provides pluggable look-and-feel.
d. AWT has more components than Swing.
5. Which method is used to make a Swing component visible?
a. setShow(true) b. setVisible(true) c. show(true) d. display(true)
6. Which of these is a top-level container in Swing?
a. JPanel b. JFrame c. JButton d. JLabel
7. The hierarchy of Swing components starts with which class?
a. [Link] b. [Link]
c. [Link] d. [Link]
8. Which of the following is not a Swing top-level container?
a. JFrame b. JDialog c. JWindow d. JToggleButton
9. Which component can hold other components?
a. JLabel b. JButton c. JPanel d. JComboBox
10. What is the purpose of [Link]?
a. Handles layout management.
b. Provides base for building GUI components.
c. Manages event handling.
d. None of the above.
11. JFrame is used for:
a. Pop-up dialogs b. Embedding web content
c. Creating the main window d. Adding scrollable content
12. What method is used to set the default close operation in JFrame?
a. setCloseOperation() b. setDefaultOperation()
c. setDefaultCloseOperation() d. setCloseAction()
13. JDialog is typically used for:
a. Splash screens b. Alerts and confirmations
c. Primary application windows d. Embedding media content
14. What distinguishes JWindow from JFrame?
a. JWindow does not have a title bar. b. JWindow is heavier than JFrame.
c. JWindow supports menus. d. JWindow can be a top-level container.
15. Which method is common in all top-level containers for adding components?
a. setComponent() b. add() c. insert() d. append()
16. JPanel is primarily used for:
a. Displaying text b. Organizing components
c. Handling events d. Creating pop-up menus
17. JButton generates which type of event?
a. FocusEvent b. KeyEvent c. ActionEvent d. MouseEvent
18. To set the label of a JButton, which method is used?
a. setLabel() b. setText() c. setName() d. setTitle()
19. JToggleButton maintains:
a. A single state b. Two states (selected/unselected)
c. A counter d. None of the above
20. Which of the following is true for JCheckBox?
a. It supports only one selection at a time.
b. It can toggle between checked and unchecked states.
c. It is used for radio button groups.
d. None of the above.
21. Which class is used to group JRadioButton components?
a. JPanel b. ButtonGroup c. RadioGroup d. JCheckBoxGroup
22. JLabel is:
a. Clickable b. Editable c. Non-interactive d. Resizable
23. Which method retrieves the text from a JTextField?
a. getInput() b. getValue() c. getText() d. retrieveText()
24. JTextArea supports:
a. Single-line input b. Multi-line input c. Dropdowns d. Checkboxes
25. Which of these can JList display?
a. A single item only b. Multiple items with or without selection
c. A dropdown d. Radio buttons
26. JComboBox combines:
a. Radio buttons and lists b. Dropdowns and checkboxes
c. Editable fields and dropdowns d. Labels and buttons
27. To add scrolling functionality to a JTextArea, which component is used?
a. JScrollPane b. JScrollField c. JScrollArea d. JTextScroll
28. Which layout manager is default in JPanel?
a. FlowLayout b. BorderLayout c. GridLayout d. CardLayout
29. What is the return type of add() method in Swing components?
a. void b. Boolean c. Component d. Container
30. What happens if you set the JFrame layout to null?
a. Components are automatically placed. b. Layout manager is disabled.
c. Program throws an exception. d. Nothing changes.
31. What method is used to set the text of a JLabel?
a. setLabel() b. setText() c. setTitle() d. setValue()
32. To add an icon to a JButton, you use:
a. setIcon() b. setImage() c. setGraphics() d. setPicture()
33. Which of these is not a valid constructor for JTextField?
a. JTextField() b. JTextField(int columns)
c. JTextField(String text) d. JTextField(String text, boolean editable)
34. Which method is used to add items to a JComboBox?
a. insertItem() b. add() c. addItem() d. appendItem()
35. JScrollPane can be added to which of the following components?
a. JTextArea b. JList c. JTable d. All of the above
36. Which listener is used to handle button click events?
a. ActionListener b. FocusListener c. KeyListener d. MouseListener
37. What is the method implemented by the ActionListener interface?
a. action() b. actionPerformed() c. performAction() d. onAction()
38. Which listener handles changes in a JToggleButton state?
a. ActionListener b. ItemListener c. ChangeListener d. KeyListener
39. What type of event does a JCheckBox generate when clicked?
a. ItemEvent b. ActionEvent c. FocusEvent d. KeyEvent
40. How do you add an event listener to a JButton?
a. [Link]() b. [Link]()
c. [Link]() d. [Link]()
41. Which layout manager arranges components in a single row or column?
a. BorderLayout b. FlowLayout c. GridLayout d. BoxLayout
42. What is the default layout for JFrame?
a. FlowLayout b. BorderLayout c. GridLayout d. BoxLayout
43. To divide a container into equal-sized cells, which layout manager is used?
a. FlowLayout b. GridLayout c. BorderLayout d. CardLayout
44. Which component provides a tabbed interface?
a. JTabbedPane b. JTabbedView c. JTabbedPanel d. JTabPane
45. What is JTable primarily used for?
a. Displaying text b. Displaying rows and columns of data
c. Managing layout d. Handling events
46. Which Swing component allows horizontal and vertical splitting of panes?
a. JViewport b. JSplitPane c. JScrollPane d. JPanel
47. Which method is used to pack a JFrame to fit its components?
a. setFit() b. autoResize() c. pack() d. setAutoSize()
48. What does setEditable(false) do for a JTextField?
a. Makes the text field unselectable.
b. Prevents user input but allows text selection.
c. Disables the text field completely.
d. Clears the content of the text field.
49. What is the primary difference between JList and JComboBox?
a. JList supports scrolling, but JComboBox doesn’t.
b. JComboBox is a dropdown, while JList is a scrollable list.
c. JComboBox allows multiple selections.
d. JList can’t be editable.
50. Which Swing component is suitable for displaying a multi-line label or rich text?
a. JTextField b. JLabel c. JTextArea d. JEditorPane

5 MARK QUESTIONS

1. Explain the key features of Swing in Java.


2. What are the differences between AWT and Swing?
3. What are the top-level containers in Swing? Explain briefly.
4. What is the role of JPanel in a Swing application?
5. Explain the hierarchy of Swing components.
10 Mark Questions
1. Explain the architecture of Swing components and the role of JComponent.
2. Describe the use and differences between JFrame, JWindow, and JDialog.
3. How do layout managers work in Swing? Explain with examples.
4. Write a program to create a simple GUI form with a JLabel, JTextField,
JButton, and JCheckBox.
5. Explain how event handling is implemented in Swing.

*****UNIT V COMPLETED*****
UNIT I – SHORT NOTES

Introduction: Review of Object Oriented concepts- History of Java-Java buzz words-JVM


architecture- Data types-Variables-Scope and life time of variables -arrays-operators-control
statements- type conversion and casting-simple java program- constructors-methods-Static block-
Static Data- Static Method String and String Buffer Classes.

Object-Oriented Concepts:
➢ Object-oriented programming (OOP) is a programming paradigm that revolves around the
concept of objects and classes. Here are some key OOP concepts:
1. Classes: A class is a blueprint or a template that defines the properties and behavior of an object.
2. Objects: An object is an instance of a class, and it has its own set of attributes (data) and methods
(functions).
3. Inheritance: Inheritance is the mechanism by which one class can inherit the properties and
behavior of another class.
4. Polymorphism: Polymorphism is the ability of an object to take on multiple forms, depending on
the context.
5. Encapsulation: Encapsulation is the concept of hiding an object's internal details and exposing
only the necessary information.
6. Abstraction: Abstraction is the concept of showing only the essential features of an object and
hiding the internal details.

History of Java:
Java is an object-oriented programming language developed by James Gosling and his team at Sun
Microsystems (now owned by Oracle Corporation). Here's a brief history of Java:
1. 1991: James Gosling begins working on a project called "Oak," which later becomes Java.
2. 1995: Java 1.0 is released, and it quickly gains popularity as a platform-independent language.
3. 1997: Java 1.1 is released, which adds important features like inner classes and reflection.
4. 2000: Java 2 is released, which introduces a new namespace and package system.
5. 2004: Java 5 is released, which adds important features like generics and annotations.
6. 2011: Oracle Corporation acquires Sun Microsystems and takes over Java development.
7. 2017: Java 9 is released, which introduces a new module system and improves performance.

Today, Java is one of the most popular programming languages in the world, widely used in
enterprise software development, Android app development, and web development
Java buzzwords:
1. Platform Independence: Java is known for its "write once, run anywhere" capability, meaning
that Java code can run on any device that has a Java Virtual Machine (JVM) installed.
2. Object-Oriented: Java is an object-oriented language that supports the principles of
encapsulation, inheritance, and polymorphism.
3. Robust Security: Java has built-in security features like memory management and secure class
loading to prevent common programming errors like null pointer exceptions and data corruption.
4. Multithreading: Java has built-in support for multithreading, which allows developers to create
high-performance applications that can run multiple tasks concurrently.
5. Dynamic Loading of Classes: Java's dynamic class loading capability allows classes to be loaded
into memory only when they are needed, which improves performance and reduces memory usage.
6. Autoboxing and Unboxing: Java's autoboxing and unboxing feature allows developers to
automatically convert between primitive types and their corresponding object wrapper classes.
7. Annotations: Java's annotation feature allows developers to add metadata to their code that can
be used by the compiler or other tools to generate code or perform other tasks.
8. Generics: Java's generics feature allows developers to create type-safe collections and other data
structures that can be reused across different types.
9. Lambda Expressions: Java's lambda expression feature allows developers to create concise and
expressive representations of functional interfaces.
10. Functional Programming: Java's functional programming features, such as lambda expressions
and method references, allow developers to write more concise and expressive code.
11. Modular Programming: Java's modular programming feature, introduced in Java 9, allows
developers to create and maintain large-scale applications more easily.
12. Reactive Programming: Java's reactive programming features, such as Reactive Streams and
Flow, allow developers to create applications that can handle high volumes of data and events.
JVMarchitectureDatatypes
JVM Architecture:
1. Class Loader: Loads classes into memory
2. Bytecode Verifier: Checks bytecode for correctness
3. Execution Engine: Executes bytecode
4. Runtime Data Areas: Stores data during execution
❖ Method Area: Stores class and method data
❖ Heap: Stores objects
❖ Stack: Stores method invocation and local variables
❖ PC Register: Stores current instruction address
5. Native Method Interface: Allows Java code to call native methods
Data Types:
1. Primitive Types:
❖ Integer: int, short, byte, long
❖ Floating Point: float, double
❖ Character: char
❖ Boolean: boolean
2. Reference Types:
❖ Class: User-defined classes
❖ Interface: Abstract classes with methods
❖ Array: Collections of primitive or reference types
3. Wrapper Classes:
❖ Integer: int
❖ Byte: byte
❖ Short: short
❖ Long: long
❖ Float: float
❖ Double: double
❖ Character: char
❖ Boolean: boolean

Note: The JVM also has a garbage collector that automatically manages memory and avoids
memory leaks.
Variables
Variables are named locations in memory that store values. In Java, variables are declared with a
specific data type and can be assigned a value. Here are the basics of variables in Java:
Declaration:
❖ Declare a variable by specifying its data type and name.
❖ Example: int x; (declares an integer variable named x)
Assignment:
❖ Assign a value to a variable using the assignment operator (=).
❖ Example: x = 10; (assigns the value 10 to the variable x)
Data Types:
- Java has several data types, including:
❖ Primitive types (int, double, boolean, etc.)
❖ Reference types (String, Array, etc.)
Scope:
❖ Variables have a scope, which determines their visibility and accessibility.
❖ Local variables are declared inside a method and are only accessible within that
method.
❖ Instance variables are declared inside a class and are accessible by all methods in
that class.
❖ Static variables are shared by all instances of a class.

Modifiers:
❖ Variables can have modifiers that affect their behavior.
❖ Final variables cannot be changed once assigned.
❖ Static variables are shared by all instances of a class.
❖ Public variables are accessible from outside the class.
Operations:
❖ Variables can be used in expressions and statements.
❖ Arithmetic operations (+, -, *, /, %)
❖ Comparison operations (==, !=, <, >, <=, >=)
❖ Logical operations (&&, ||, !)
Best Practices:
❖ Use meaningful variable names that indicate their purpose.
❖ Use proper data types to ensure type safety.
❖ Declare variables close to their usage.
❖ Avoid using public variables; use getters and setters instead.
Scope:
❖ Scope refers to the region of the code where a variable is defined and accessible.
❖ Variables can have different scopes, including:
▪ Local scope: Variables declared inside a method or block.
▪ Instance scope: Variables declared inside a class, but outside a method.
▪ Static scope: Variables declared with the static keyword.
▪ Global scope: Variables declared outside any class or method.
Lifetime:

- Lifetime refers to the duration during which a variable exists in memory.


- Variables can have different lifetimes, including:
❖ Local variables: Created and destroyed every time a method is called.
❖ Instance variables: Created when an object is instantiated and destroyed when the object
is garbage collected.
❖ Static variables: Created when the program starts and destroyed when the program ends.
❖ Global variables: Created when the program starts and destroyed when the program
ends.
Here's an example to illustrate the scope and lifetime of variables:
public class MyClass {
// Instance variable
private int x;
// Static variable
private static int y;
public void myMethod() {
// Local variable
int z;
// Assign values
x = 10;
y = 20;
z = 30;
}
public static void main(String[] args) {
// Create an object of MyClass
MyClass obj = new MyClass();
// Access instance variable
[Link](obj.x); // Output: 10
// Access static variable
[Link](MyClass.y); // Output: 20
// Call myMethod()
[Link]();
// Try to access local variable z
// [Link](z); // Error! z is not accessible here
}
}
In this example, the scope and lifetime of the variables are:
- x: Instance variable, accessible only within the MyClass object, lifetime is tied to the object's
lifetime.
- y: Static variable, accessible from any part of the program, lifetime is tied to the program's
lifetime.
- z: Local variable, accessible only within the myMethod() method, lifetime is tied to the method's
execution.
Arrays:
❖ A collection of elements of the same data type stored in contiguous memory locations.
❖ Declared using the type[] arrayName syntax.
❖ Elements accessed using the index [ ] operator.
❖ Examples: int[] myArray = new int[5];, String[] myStringArray = {"hello", "world"}.
Operators:
❖ Arithmetic operators: +, -, *, /, %
❖ Comparison operators: ==, !=, <, >, <=, >=
❖ Logical operators: &&, ||, !
❖ Assignment operators: =, +=, -=, *=, /=, %=, etc.
❖ Example: int x = 5; int y = 3; int sum = x + y;
Control Statements:
- Conditional statements:
▪ If-else statements: if (condition) { code } else { code }
▪ Switch statements: switch (expression) { case value: code; break; default: code; }
- Loops:
▪ For loops: for (init; condition; increment) { code }
▪ While loops: while (condition) { code }
▪ Do-while loops: do { code } while (condition);
- Jump statements:
▪ Break: exits the current loop or switch statement
▪ Continue: skips the current iteration and continues with the next one
▪ Return: exits the current method and returns a value
Type Conversion and Casting:
▪ Type conversion: converting a value from one data type to another.
▪ Casting: explicitly converting a value from one data type to another using a cast
operator.
▪ Example: int x = (int) 5.5; // casting a double to an int
Simple Java Program:
- A Java program with a main method is the entry point for any Java application.
- The main method is called when the program is run.
Example:
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Constructors:
- A constructor is a special method that is called when an object is instantiated.
- It has the same name as the class and no return type.
Example:
public class Person {
private String name;
public Person(String name) {
[Link] = name;
}
}
Methods:
- A method is a block of code that performs a specific task.
- It has a name, return type, and parameters.
Example:
public class Calculator {
public int add(int x, int y) {
return x + y;
}
}
Static Block:
- A static block is a block of code that is executed when the class is loaded.
- It is used to initialize static variables.
Example:
public class Person {
private static String country;
static {
country = "USA";
}
}
Static Data:
- Static data is shared by all objects of a class.
- It is initialized only once when the class is loaded.
Example:
public class Person {
private static int count = 0;
}
Static Method:
- A static method is a method that belongs to a class rather than an object.
- It can be called without creating an object.
Example:
public class Calculator {
public static int add(int x, int y) {
return x + y;
}
}
String and StringBuffer Classes:
- String is an immutable class that represents a sequence of characters.
- StringBuffer is a mutable class that represents a sequence of characters.
Multiple-Choice Questions

1. Which of the following is not a principle of Object- d) Creates Java packages


Oriented Programming (OOP)? **Answer:** b
a) Inheritance
b) Encapsulation 8. Which of the following is not a component of the
c) Polymorphism JVM?
d) Compilation a) Classloader
**Answer:** d b) Execution Engine
c) Garbage Collector
2. What does encapsulation mean in Java? d) Header Files
a) Wrapping up of data and methods into a single unit **Answer:** d
b) Ability to define multiple methods with the same
name 9. Which of the following is not a valid Java primitive
c) Ability of one class to inherit another class data type?
d) Conversion of primitive data types a) byte
**Answer:** a b) integer
c) char
3. Who is known as the creator of Java? d) float
a) Dennis Ritchie **Answer:** b
b) James Gosling
c) Guido van Rossum 10. What is the default value of a `boolean` variable in
d) Bjarne Stroustrup Java?
**Answer:** b a) 0
b) false
4. In which year was Java officially released? c) null
a) 1990 d) true
b) 1991 **Answer:** b
c) 1995
d) 1996 11. What is the scope of a local variable in Java?
**Answer:** c a) Entire program
b) The block in which it is defined
5. Which of the following is not a Java buzzword? c) Entire class
a) Object-oriented d) Across all classes
b) Platform-dependent **Answer:** b
c) Robust
d) Multithreaded 12. Which keyword is used to declare a constant
**Answer:** b variable in Java?
a) static
6. What makes Java platform-independent? b) final
a) JDK c) const
b) Bytecode and JVM d) abstract
c) Compiler **Answer:** b
d) Source code compatibility
**Answer:** b 13. Which of the following correctly initializes an
array in Java?
7. What is the role of the JVM? a) int arr[5] = {1, 2, 3, 4, 5};
a) Compiles Java code to machine code b) int[] arr = new int[5];
b) Converts bytecode into machine-readable code c) int arr = {1, 2, 3, 4, 5};
c) Executes Java source code directly d) int arr(5) = {1, 2, 3, 4, 5};
**Answer:** b **Answer:** b

14. What will be the output of the following code 20. Which statement is true about static methods?
snippet? a) They can access non-static variables.
```java b) They belong to the class rather than an object.
int[] arr = {1, 2, 3, 4}; c) They cannot be called without creating an object.
[Link](arr[4]); d) They cannot have a return value.
``` **Answer:** b
a) 0
b) 4 21. What is inheritance in Java?
c) ArrayIndexOutOfBoundsException a) A way to reuse code from other classes
d) Compilation Error b) A mechanism to access private variables
**Answer:** c c) A way to write multiple classes
d) None of the above
15. Which control statement is used to exit a loop **Answer:** a
prematurely?
a) continue 22. Which type of inheritance is not supported in
b) break Java?
c) exit a) Single inheritance
d) stop b) Multiple inheritance using classes
**Answer:** b c) Multilevel inheritance
d) Hierarchical inheritance
16. What does a `switch` statement use to compare **Answer:** b
values?
a) Floating-point comparisons 23. What does the `this` keyword represent?
b) Integer comparisons a) A reference to the current object
c) String comparisons b) A reference to the parent object
d) Both b and c c) A method to invoke the constructor
**Answer:** d d) None of the above
**Answer:** a
17. What is type casting in Java?
a) Automatic conversion of data types 24. What is the purpose of the `super` keyword?
b) Explicit conversion of one data type to another a) To create a superclass
c) Copying one variable to another b) To call the constructor of the current class
d) Checking data types at runtime c) To access members of the parent class
**Answer:** b d) To create private methods
**Answer:** c
18. Which of the following is an example of implicit
type conversion? 25. Which is true about method overloading in Java?
a) int a = (int) 10.5; a) It allows the same method name with different
b) float b = 5; parameter types
c) String s = (String) object; b) It allows methods in subclasses to override
d) None of the above methods in the superclass
**Answer:** b c) It requires the `final` keyword
d) None of the above
19. What is a constructor in Java? **Answer:** a
a) A method used to destroy objects
b) A method that initializes objects 26. What is dynamic method dispatch?
c) A method to execute static code a) A way to call static methods dynamically
d) None of the above
b) A mechanism to resolve overridden methods at 33. Can an interface extend another interface?
runtime a) Yes, using the `extends` keyword
c) A process to dispatch exceptions dynamically b) No, interfaces cannot extend another interface
d) None of the above c) Yes, using the `implements` keyword
**Answer:** b d) None of the above
**Answer:** a
27. What is the purpose of an abstract class?
a) To provide a blueprint for other classes 34. Which statement is true about implementing an
b) To create concrete methods interface?
c) To bypass inheritance a) A class can implement multiple interfaces
d) None of the above b) A class can implement only one interface
**Answer:** a c) Interfaces cannot be implemented
d) None of the above
28. Which of the following is true about the `final` **Answer:** a
keyword?
a) It can be applied to variables, methods, and classes 35. What is the purpose of the `try` block in Java?
b) It makes a variable mutable a) To catch exceptions
c) It allows method overriding b) To test for exceptions
d) None of the above c) To execute code that might throw exceptions
**Answer:** a d) None of the above
**Answer:** c
29. What is a package in Java?
a) A collection of classes and interfaces 36. What happens if a `finally` block is defined in a
b) A way to organize Java files try-catch structure?
c) Both a and b a) It is executed only if an exception is thrown
d) None of the above b) It is executed always
**Answer:** c c) It is executed only if no exception is thrown
d) None of the above
30. Which keyword is used to import a package in **Answer:** b
Java?
a) `package` 37. Which keyword is used to throw an exception in
b) `import` Java?
c) `include` a) `throws`
d) `extend` b) `throw`
**Answer:** b c) `catch`
d) `try`
31. What is access protection in packages? **Answer:** b
a) Controlling access to members within a package
b) Allowing only private methods 38. What is a built-in exception in Java?
c) Making all methods public a) User-defined exception classes
d) None of the above b) Predefined exceptions in Java libraries
**Answer:** a c) Errors caused by the JVM
d) None of the above
32. What is an interface in Java? **Answer:** b
a) A class that contains concrete methods
b) A class that contains abstract methods 39. What does the `throws` keyword indicate?
c) A blueprint for a class with only abstract methods a) It defines the exception to be thrown in a method
d) None of the above b) It creates a new exception
**Answer:** c c) It catches exceptions
d) None of the above
**Answer:** a A) New
B) Blocked
40. Which method is overridden to create a custom C) Running
exception? D) Destroyed
a) `toString()` Answer: D
b) `getMessage()`
c) Both a and b 47. What is inter-thread communication in Java?
d) None of the above A) Threads sharing their execution time
**Answer:** c B) Mechanism for threads to communicate using
wait(), notify(), notifyAll()
41. Which of the following is a valid way to create a C) Creating multiple threads to run concurrently
thread in Java? D) Deadlock prevention
A) Extending the Thread class Answer: B
B) Implementing the Runnable interface
C) Both A and B 48. Which method is NOT related to thread
D) Using ExecutorService only communication?
Answer: C A) wait()
B) notify()
42. What is the default priority of a thread in Java? C) notifyAll()
A) 1 D) sleep()
B) 5 Answer: D
C) 10
D) 0 49. Which condition can lead to a deadlock in Java?
Answer: B A) One thread releasing a lock while another thread
holds it
43. Which method is used to pause the execution of a B) Two or more threads waiting for each other's lock
thread? C) Only one thread being active
A) stop() D) Threads finishing execution simultaneously
B) yield() Answer: B
C) sleep()
D) pause() 50. What is the use of the synchronized block?
Answer: C A) To improve thread execution speed
B) To lock a specific section of code
44. In Java, what does the join() method do? C) To notify all threads to start execution
A) Joins two threads into one D) To stop a thread
B) Waits for a thread to die Answer: B
C) Stops a thread
D) Terminates all running threads I/O Streams
Answer: B 51. What is the main purpose of I/O streams in Java?
A) To manage threads
45. How can thread synchronization be achieved in B) To handle input and output operations
Java? C) To execute system commands
A) Using the synchronized keyword D) To create files
B) Using volatile keyword Answer: B
C) Using Thread class
D) Using notify() 52. Which of the following is a byte stream class in
Answer: A Java?
A) BufferedReader
46. Which of these is NOT a state in the thread B) FileOutputStream
lifecycle?
C) PrintWriter Answer: A
D) FileReader
Answer: B 59. What does the close() method do in Java I/O
streams?
53. Which of these classes is used for character A) Clears the buffer
streams? B) Terminates the program
A) DataInputStream C) Closes the stream and releases resources
B) FileWriter D) Stops the file from being used again
C) FileInputStream Answer: C
D) BufferedInputStream
Answer: B 60. Which class in Java provides methods to read
primitive data types directly from a stream?
54. What is the correct way to read a single character A) BufferedReader
from the console? B) DataInputStream
A) [Link]().readChar() C) InputStreamReader
B) [Link]() D) ObjectInputStream
C) [Link]() Answer: B
D) [Link]() 61. What does AWT stand for in Java?
Answer: B A) Abstract Window Toolkit
B) Advanced Window Toolkit
55. Which method is used to write to the console in C) Application Window Toolkit
Java? D) Advanced Widget Toolkit
A) [Link]() Answer: A
B) [Link]()
C) [Link]() 62. Which of the following is NOT a component in
D) [Link]().print() the AWT hierarchy?
Answer: B A) Label
B) Button
56. What is the difference between FileReader and C) ArrayList
FileInputStream? D) ScrollPane
A) FileReader is for binary data; FileInputStream is Answer: C
for text data.
B) FileReader is for text data; FileInputStream is for 63. Which AWT component is used to display
binary data. uneditable text?
C) Both handle binary data. A) TextField
D) Both handle text data. B) TextArea
Answer: B C) Label
D) Button
57. How do you create a file in Java? Answer: C
A) Using [Link]()
B) Using [Link]() 64. How do you group a set of CheckBoxes in Java?
C) Using [Link]() A) Using CheckBoxGroup
D) Using [Link]() B) Using GroupLayout
Answer: B C) Using Panel
D) Using List
58. Which class is used to read text files efficiently? Answer: A
A) BufferedReader
B) FileReader 65. Which AWT component allows selecting one
C) Scanner option from a drop-down menu?
D) DataInputStream
A) List C) A method to execute Java programs
B) Choice D) A process to manage layouts
C) Menu Answer: B
D) TextField
Answer: B 72. What is the role of an Event Listener in Java?
A) To generate events
66. What is the difference between List and Choice in B) To handle events
AWT? C) To display events
A) List supports multi-selection; Choice does not. D) To delegate events
B) List is for binary data; Choice is for text data. Answer: B
C) List supports single selection only; Choice
supports multi-selection. 73. What is the Event Delegation Model (EDM)?
D) List and Choice are functionally identical. A) A model for propagating events from source to
Answer: A listener
B) A method for creating events
67. Which class in AWT is used to create a container C) A tool for debugging event-driven applications
for other components? D) A model for synchronizing events across threads
A) Frame Answer: A
B) Panel
C) ScrollPane 74. Which method is called when a button is clicked
D) Menu in AWT?
Answer: B A) buttonClicked()
B) onClick()
68. Which method is used to add a menu to a Frame? C) actionPerformed()
A) setMenu() D) doClick()
B) addMenu() Answer: C
C) setMenuBar()
D) addMenuBar() 75. How do you handle mouse events in AWT?
Answer: C A) Using MouseEvent and MouseListener
B) Using KeyEvent and KeyListener
69. How can you add scrolling functionality to a large C) Using MouseListener and Adapter
component in AWT? D) Using ActionEvent and ActionListener
A) Using ScrollPane Answer: A
B) Using ScrollBar only
C) Using Panel 76. Which of these is NOT a method in the
D) Using Choice MouseListener interface?
Answer: A A) mousePressed()
B) mouseClicked()
70. Which layout manager arranges components in a C) mouseScrolled()
grid with fixed rows and columns? D) mouseReleased()
A) BorderLayout Answer: C
B) FlowLayout
C) GridLayout 77. What is the advantage of using Adapter classes in
D) CardLayout Java?
Answer: C A) To simplify handling only specific events
B) To add multiple listeners to an event
Event Handling C) To extend the functionality of all methods in a
71. What is an Event in Java? listener interface
A) A mechanism to handle exceptions D) To manage event sources efficiently
B) An object that describes a state change in a source Answer: A
B. JCheckBox
78. What are inner classes commonly used for in C. JRadioButton
event handling? D. JToggleButton
A) To increase program size Answer: A
B) To encapsulate event listener implementation
C) To slow down execution 85. What is the purpose of a JPanel in Swing?
D) To avoid using adapters A. To create a top-level container
Answer: B B. To group other components
C. To handle user inputs
79. Which method handles key typing events in the D. To display text
KeyListener interface? Answer: B
A) keyTyped()
B) keyPressed() 86. Which component allows selection of one option
C) keyReleased() from a set?
D) keyInput() A. JCheckBox
Answer: A B. JRadioButton
C. JButton
80. What does the addActionListener() method do in D. JComboBox
AWT? Answer: B
A) Adds an action listener to a component
B) Removes an action listener from a component 87. What does a JScrollPane provide?
C) Executes an action listener A. Text editing
D) Binds an action to multiple components B. Scrollable view for components
Answer: A C. Button functionality
D. Container hierarchy
81. Which of the following is NOT a top-level Answer: B
container in Swing?
A. JFrame 88. Which of the following is used to display a single
B. JWindow line of editable text?
C. JPanel A. JTextArea
D. JDialog B. JLabel
Answer: C C. JTextField
D. JPanel
82. What is the base class for all Swing components? Answer: C
A. Component
B. JComponent 89. What is the main difference between JCheckBox
C. Container and JRadioButton?
D. Object A. JCheckBox is selectable, JRadioButton is not
Answer: B B. JCheckBox allows multiple selections,
JRadioButton does not
83. Which method is used to make a JFrame visible? C. JRadioButton is for text input, JCheckBox is not
A. setShow() D. JCheckBox cannot be deselected, JRadioButton
B. display() can
C. setVisible() Answer: B
D. showFrame()
Answer: C 90. Which method is used to add components to a
JFrame?
84. Which component is used to create a button in A. append()
Swing? B. addComponent()
A. JButton C. add()
D. insert() Answer: B
Answer: C
96. How can you set the text of a JLabel?
91. What does a JLabel component do? A. setText()
A. Displays text or icons B. setLabel()
B. Accepts user input C. setTextValue()
C. Acts as a container D. setContent()
D. Provides scroll functionality Answer: A
Answer: A 97. Which Swing container does NOT require a
parent?
92. How do you create a JComboBox in Swing? A. JPanel
A. new JComboBox() B. JFrame
B. [Link]() C. JLabel
C. new JComboBox[] D. JTextField
D. createComboBox() Answer: B
Answer: A
98. What is the default layout manager for a JPanel?
93. Which component is used for multi-line text A. BorderLayout
editing? B. FlowLayout
A. JTextArea C. GridLayout
B. JTextField D. None
C. JLabel Answer: B
D. JPanel
Answer: A 99. How can you group JRadioButtons?
A. Add them to a JPanel
94. What is the purpose of a JToggleButton? B. Use a ButtonGroup
A. To toggle between enabled and disabled states C. Add them to a JFrame
B. To act as a switch between on and off states D. Use a JCheckBox
C. To display icons Answer: B
D. To scroll content
Answer: B 100. Which method adds an item to a JComboBox?
A. addItem()
95. Which component represents a scrollable list? B. add()
A. JScrollPane C. insertItem()
B. JList D. setItem()
C. JComboBox Answer: A
D. JTextArea

Five Mark Questions:

1. Define Object-Oriented Programming and its concepts.


2. Briefly explain the history of Java.
3. What are Java Buzzwords? Mention any five buzzwords.
4. Explain the architecture of the JVM.
5. What is the difference between type conversion and type casting in Java?
6. Define inheritance and explain its benefits.
7. What is the purpose of the `this` keyword in Java?
8. Differentiate between method overloading and method overriding.
9. What is the significance of the `super` keyword in Java?
10. Define abstract classes and explain their importance.
11. What is a thread? Explain the difference between `Thread` and `Runnable`.
12. Define synchronization and its importance in multithreading.
13. What are byte streams and character streams? Explain with examples.
14. Describe the purpose of `try`, `catch`, and `finally` in exception handling.
15. How do you create a custom exception in Java?
16. What is the role of the AWT class hierarchy in Java?
17. Explain the purpose of layout managers in AWT.
18. What is an event listener? Provide an example.
19. Differentiate between handling mouse events and keyboard events in Java.
20. Explain the concept of adapter classes in event handling.
21. What are the differences between AWT and Swing?
22. Define top-level containers and give examples.
23. What is the role of the `JTextField` component in Swing?
24. Explain the purpose of the `JScrollPane` component in Swing.
25. Describe the use of `JComboBox` in Swing with an example.

Ten Mark Questions:

1. Describe the JVM architecture in detail with a diagram.


2. Explain the differences between type conversion and type casting with examples.
3. Write a Java program to demonstrate the usage of constructors.
4. Discuss the different types of control statements in Java with examples.
5. Explain the differences between `String` and `StringBuffer` classes with examples.
6. Explain the various types of inheritance in Java with examples.
7. Discuss the usage of `this` and `super` keywords with examples.
8. Explain method overloading and method overriding with suitable examples.
9. Define abstract classes and dynamic method dispatch with examples.
10. Explain the concept of packages and access protection in Java.
11. Describe the lifecycle of a thread and its methods with examples.
12. Explain thread synchronization with examples of synchronized methods and statements.
13. What is inter-thread communication? Exp
Discuss the different types of I/O streams in Java with examples.
14. Write a program to demonstrate custom exception handling in Java.
15. Explain the AWT class hierarchy and its components with examples.
16. Discuss the various layout managers in AWT with examples.
17. Explain the Event Delegation Model (EDM) in Java with an example.
18. Write a program to handle mouse and keyboard events in Java.
19. Describe the purpose and usage of adapter classes in event handling.
20. Compare and contrast AWT and Swing components with examples.
21. Explain the hierarchy of Swing components with diagrams.
22. Write a program to demonstrate the use of `JTextField` and `JTextArea` in Swing.
23. Discuss the importance of `JScrollPane` in Swing with examples.
24. Write a program to demonstrate the use of `JComboBox` and `JList` in Swing.
Details
EXCERCISE
Write a Java program that prompts the user for an integer and then prints
1
out all the prime numbers up to that Integer

2 Write a Java program to multiply two given matrices.

Write a Java program that displays the number of characters, lines and
3 words in a text

Generate random numbers between two given limits using Random class
4 and print messages according to the range of the value generated.

Write a program to do String Manipulation using CharacterArray and


perform the following string operations:
a. String length
5
b. Finding a character at a particular position
c. Concatenating two strings

Write a program to perform the following string operations using


String class:

6 a. String Concatenation
b. Search a substring
c. To extract substring from given string
Write a program to perform string operations using String Buffer
class:
a. Length of a string
7
b. Reverse a string
c. Delete a substring from the given string

Write a java program that implements a multi-thread application that has


three threads. First thread generates random integer every 1 secondand if
the value is even, second thread computes the square of the number and
8
prints. If the value is odd, the third thread will print the value of cube of
the number.

Write a threading program which uses the same method asynchronously

9 to print the numbers 1to10 using Thread1 and to print90 to100 using
Thread2.

Write a program to demonstrate the use of following exceptions.

a. Arithmetic Exception

10 b. Number Format Exception

c. ArrayIndexOutofBoundException

d. NegativeArraySizeException

Write a Java program that reads on file name from the user, then
displays information about whether the file exists, whether the file is
11 readable, whether the file is writable, the type of file and the length of
the file in bytes

Write a program to accept a text and change its size and font. Include
12 bold italic options. Use frames and controls.

Write a Java program that handles all mouse events and shows the

13 event name at the center of the window when a mouse event is fired.
(Use adapter classes).
14 Write a Java program that works as a simple calculator. Use a grid

layout to arrange buttons for the digits and for the +, -,*, % operations.
Add a text field to display the result. Handle any possible exceptions
like divide by zero.

Write a Java program that simulates a traffic light. The program lets
theuser select one of three lights: red, yellow, or green with radio
buttons. On selecting a button, an appropriate message with ―stop or
15
―ready or
―go should appear above the buttons in a selected color. Initially
there is no message shown.
[Link] NUMBERS

AIM:
To write a Java program that prompts the user for an integer and prints all prime numbers up
to that integer.

ALGORITHM:
1. Get User Input: Prompt user to enter an integer n.
2. Check Input Validity: Verify that n is a positive integer.
3. Initialize Prime List: Create an empty list to store prime numbers.
4. Check for Prime Numbers:
- Iterate from i = 2 to n.
- For each i, call the isPrime function to check if i is prime.
- If i is prime, add it to the prime list.
5. Print Prime List: Display the list of prime numbers up to n.
6. Exit: Terminate the program.
PROGRAM:
import [Link];

public class PrimeNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Prompt the user for an integer


[Link]("Enter an integer: ");
int n = [Link]();

if (n < 2) {
[Link]("There are no prime numbers up to " + n);
} else {
[Link]("Prime numbers up to " + n + ":");
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
[Link](i + " ");
}
}
[Link](); // Add a newline after the primes
}

[Link](); // Close the scanner


}

// Function to check if a number is prime


public static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}

OUTPUT:
Enter an integer: 20
Prime numbers up to 20:
2 3 5 7 11 13 17 19
[Link] TWO MATRICES

AIM:
To multiply two given matrices using Java.

ALGORITHM:
1. Get Dimensions: Get the dimensions of matrices A and B (m, n, p)
2. Validate Dimensions: Check if the number of columns in A equals the number of rows in B
(n == n)
3. Create Result Matrix: Create a result matrix C (m x p) filled with zeros
4. Perform Matrix Multiplication:
- For each element C[i][j] in the result matrix
- Iterate over corresponding elements of A and B
- Multiply and accumulate products: C[i][j] += A[i][k] * B[k][j]
5. Return Result Matrix: Return the resulting product matrix C
PROGRAM:
import [Link];

public class MatrixMultiplication {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input dimensions for the first matrix


[Link]("Enter the number of rows in the first matrix: ");
int rows1 = [Link]();
[Link]("Enter the number of columns in the first matrix: ");
int cols1 = [Link]();

// Input dimensions for the second matrix


[Link]("Enter the number of rows in the second matrix: ");
int rows2 = [Link]();
[Link]("Enter the number of columns in the second matrix: ");
int cols2 = [Link]();

// Validate matrix dimensions for multiplication


if (cols1 != rows2) {
[Link]("Matrix multiplication is not possible. Number of columns in the
first matrix must equal the number of rows in the second matrix.");
return;
}

// Input first matrix


int[][] matrix1 = new int[rows1][cols1];
[Link]("Enter elements of the first matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = [Link]();
}
}

// Input second matrix


int[][] matrix2 = new int[rows2][cols2];
[Link]("Enter elements of the second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = [Link]();
}
}

// Perform matrix multiplication


int[][] product = new int[rows1][cols2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Display the product matrix


[Link]("The product of the matrices is:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
[Link](product[i][j] + " ");
}
[Link]();
}

[Link]();
}
}

OUTPUT:
Enter the number of rows in the first matrix: 2
Enter the number of columns in the first matrix: 3
Enter the number of rows in the second matrix: 3
Enter the number of columns in the second matrix: 2
Enter elements of the first matrix:
123
456
Enter elements of the second matrix:
78
9 10
11 12
The product of the matrices is:
58 64
139 154
3. DISPLAYS THE NUMBER OF CHARACTERS, LINES AND
WORDS IN A TEXT

AIM:
To displays the number of characters, lines and words in a text using Java Programming.

ALGORITHM:
1. Initialize the following variables:
• characterCount = 0 (To store the total number of characters)

• wordCount = 0 (To store the total number of words)


• lineCount = 0 (To store the total number of lines)
2. Display a prompt asking the user to enter text and inform them to type "END" on a
new line to finish.
3. Repeat the following steps for each line of input until the user enters the word
"END":
4. Read a line of text from the user.
5. Check if the input line equals "END":
a. If true, exit the loop and proceed to the next step.
b. If false, continue processing the line.
6. Increment lineCount by 1 (since each line is counted).
7. Add the number of characters in the line to characterCount using [Link]().
8. Split the line into words by using spaces or whitespace characters as delimiters
([Link]("\\s+")) and increment wordCount by the number of words in the line.
9. Display the total counts:
• Print the value of lineCount (number of lines).
• Print the value of wordCount (number of words).
• Print the value of characterCount (number of characters).
PROGRAM:
import [Link];

public class TextStatistics {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter the text (type 'END' on a new line to finish):");

int characterCount = 0;
int wordCount = 0;
int lineCount = 0;

while (true) {
String line = [Link]();

// Exit condition
if ([Link]("END")) {
break;
}

lineCount++;
characterCount += [Link]();
wordCount += [Link]("\\s+").length; // Split by whitespace
}

// Display the results


[Link]("Text Statistics:");
[Link]("Number of lines: " + lineCount);
[Link]("Number of words: " + wordCount);
[Link]("Number of characters: " + characterCount);
[Link]();
}
}

OUTPUT:
Enter the text (type 'END' on a new line to finish):
Hello, how are you?
I am doing fine.
Java programming is fun.
END
Text Statistics:
Number of lines: 3
Number of words: 10
Number of characters: 56
4. RANDOM NUMBER GENERATOR

AIM:
To generate random numbers between two given limits using Random class and print
messages according to the range of the value generated.

ALGORITHM:
Step 1: Import Necessary Libraries
1. Import [Link] for generating random numbers
2. Import [Link] for reading user input
Step 2: Initialize Variables
1. Initialize a Scanner object to read user input
2. Initialize a Random object to generate random numbers
Step 3: Get User Input
1. Prompt user to enter the lower limit
2. Read the lower limit using [Link]()
3. Prompt user to enter the upper limit
4. Read the upper limit using [Link]()
Step 4: Validate Input
1. Check if the lower limit is less than or equal to the upper limit
2. If invalid, display an error message and exit
Step 5: Generate Random Number
1. Use [Link]() to generate a random integer within the given range (inclusive)
2. Calculate the random number using the formula: randomNumber =
[Link](upperLimit - lowerLimit + 1) + lowerLimit
Step 6: Display Random Number
1. Print the generated random number to the console
Step 7: Determine Range
1. Calculate the range of the generated number
2. Check which range the generated number falls into (lower, middle, or upper)
3. Print a message indicating the range of the generated number
Step 8: Close Scanner
1. Close the Scanner object to prevent resource leaks

PROGRAM:
import [Link];
import [Link];

public class RandomNumberGenerator {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Random random = new Random();

// Take input for the lower and upper limits


[Link]("Enter the lower limit: ");
int lowerLimit = [Link]();
[Link]("Enter the upper limit: ");
int upperLimit = [Link]();

// Generate a random number within the given range (inclusive)


int randomNumber = [Link](upperLimit - lowerLimit + 1) + lowerLimit;

// Display the generated random number


[Link]("Generated Random Number: " + randomNumber);

// Print messages based on the range of the generated number


if (randomNumber < lowerLimit + (upperLimit - lowerLimit) / 3) {
[Link]("The generated number is in the lower range.");
} else if (randomNumber < lowerLimit + 2 * (upperLimit - lowerLimit) / 3) {
[Link]("The generated number is in the middle range.");
} else {
[Link]("The generated number is in the upper range.");
}
[Link]();
}
}

OUTPUT:
Enter the lower limit: 10
Enter the upper limit: 30
Generated Random Number: 17
The generated number is in the middle range.
5. STRING MANIPULATION

AIM:
The aim of this program is to perform basic string manipulations using CharacterArray in
Java. The program will:
1. Calculate the length of a given string by converting it into a character array.
2. Find a character at a specific position within the string using the character array.
3. Concatenate two strings and display the result.

ALGORITHM:
Step 1: Import Necessary Libraries
1. Import [Link] for reading user input
Step 2: Initialize Variables
1. Initialize a Scanner object to read user input
Step 3: Input Two Strings
1. Prompt user to enter the first string
2. Read the first string using [Link]()
3. Prompt user to enter the second string
4. Read the second string using [Link]()
Step 4: Convert Strings to Character Arrays
1. Convert the first string to a character array using toCharArray()
2. Convert the second string to a character array using toCharArray()
Step 5: Find the Length of the Strings
1. Print the length of the first string using length property
2. Print the length of the second string using length property
Step 6: Find a Character at a Particular Position
1. Prompt user to enter the position (index) to find the character
2. Read the position using [Link]()
3. Check if the position is valid for the first string
4. If valid, print the character at the specified position in the first string
5. Repeat steps 3-4 for the second string
Step 7: Concatenate Two Strings
1. Concatenate the first and second strings using the + operator
2. Print the concatenated string
Step 8: Close Scanner
1. Close the Scanner object to prevent resource leaks.

PROGRAM:
import [Link];

public class StringManipulation {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input two strings


[Link]("Enter the first string: ");
String firstString = [Link]();

[Link]("Enter the second string: ");


String secondString = [Link]();

// Convert strings to character arrays


char[] firstCharArray = [Link]();
char[] secondCharArray = [Link]();

// 1. Finding the length of the first string


[Link]("\nString Length:");
[Link]("Length of the first string: " + [Link]);
[Link]("Length of the second string: " + [Link]);

// 2. Finding a character at a particular position


[Link]("\nEnter the position (index) to find the character: ");
int position = [Link]();
if (position >= 0 && position < [Link]) {
[Link]("Character at position " + position + " in the first string: " +
firstCharArray[position]);
} else {
[Link]("Invalid position for the first string.");
}

if (position >= 0 && position < [Link]) {


[Link]("Character at position " + position + " in the second string: " +
secondCharArray[position]);
} else {
[Link]("Invalid position for the second string.");
}

// 3. Concatenating two strings


String concatenatedString = firstString + secondString;
[Link]("\nConcatenated String:");
[Link](concatenatedString);

[Link]();
}
}
OUTPUT:
Enter the first string: Hello
Enter the second string: World
Enter the position (index) to find the character: 2
String Length:
Length of the first string: 5
Length of the second string: 5

Character at position 2 in the first string: l


Character at position 2 in the second string: r

Concatenated String:
HelloWorld
6. STRING OPERATIONS USING STRING CLASS

AIM:
To perform the following string operations using String class:
a. String Concatenation
b. Search a substring
c. To extract substring from given string

ALGORITHM:
Step 1: Import Necessary Libraries
1. Import [Link] for reading user input.
Step 2: Initialize Variables
1. Initialize a Scanner object to read user input.
Step 3: Input Strings
1. Prompt user to enter the first string.
2. Read the first string using [Link]().
3. Prompt user to enter the second string.
4. Read the second string using [Link]().
Step 4: String Concatenation
1. Concatenate the first and second strings using the concat() method.
2. Print the concatenated string.
Step 5: Search a Substring
1. Prompt user to enter a substring to search.
2. Read the substring using [Link]().
3. Check if the first string contains the substring using the contains() method.
4. Print the result of the search.
Step 6: Extract a Substring
1. Prompt user to enter the starting index for the substring extraction.
2. Read the starting index using [Link]().
3. Prompt user to enter the ending index for the substring extraction.
4. Read the ending index using [Link]().
5. Check if the indices are valid.
6. Extract the substring using the substring() method.
7. Print the extracted substring.

PROGRAM:
import [Link];

public class StringOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input strings
[Link]("Enter the first string: ");
String firstString = [Link]();

[Link]("Enter the second string: ");


String secondString = [Link]();

// 1. String Concatenation
String concatenatedString = [Link](secondString);
[Link]("\nConcatenated String:");
[Link](concatenatedString);

// 2. Search a Substring
[Link]("\nEnter a substring to search: ");
String substringToSearch = [Link]();

if ([Link](substringToSearch)) {
[Link]("The substring '" + substringToSearch + "' is found in the first
string.");
} else {
[Link]("The substring '" + substringToSearch + "' is not found in the first
string.");
}

// 3. Extract a Substring
[Link]("\nEnter the starting index for the substring extraction: ");
int startIndex = [Link]();

[Link]("Enter the ending index for the substring extraction: ");


int endIndex = [Link]();

// Check if indices are valid


if (startIndex >= 0 && endIndex <= [Link]() && startIndex < endIndex) {
String extractedSubstring = [Link](startIndex, endIndex);
[Link]("\nExtracted Substring: ");
[Link](extractedSubstring);
} else {
[Link]("Invalid indices for substring extraction.");
}

[Link]();
}
}
OUTPUT:
Enter the first string: HelloWorld
Enter the second string: Java
Enter a substring to search: World
Enter the starting index for the substring extraction: 5
Enter the ending index for the substring extraction: 10
Concatenated String:
HelloWorldJava

The substring 'World' is found in the first string.

Extracted Substring:
World
1. 7. STRING OPERATIONS USING STRING BUFFER
CLASS

AIM:
The aim of this program is to demonstrate the use of the StringBuffer class in Java to perform
basic string operations, including:
1. Finding the length of a string.
2. Reversing the string.
3. Deleting a substring from the string.

ALGORITHM:
1. Input a string from the user.
2. Create a StringBuffer object from the input string.
3. Find the length of the string using the length() method.
4. Reverse the string using the reverse() method.
5. Delete a substring from the string:
- Input the start and end indices for deletion.
- Check if the indices are valid.
- Use the delete() method to delete the substring.
6. Print the results of each operation.
PROGRAM:
import [Link];

public class StringBufferOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Input the string


[Link]("Enter a string: ");
String inputString = [Link]();

// Create a StringBuffer object


StringBuffer stringBuffer = new StringBuffer(inputString);

// 1. Find the length of the string


[Link]("\nLength of the string: " + [Link]());

// 2. Reverse the string


[Link]("\nReversed string: " + [Link]());

// 3. Delete a substring from the string


[Link](); // To consume the newline left by nextInt()
[Link]("\nEnter the start index to delete a substring: ");
int startIndex = [Link]();

[Link]("Enter the end index to delete a substring: ");


int endIndex = [Link]();

// Check if indices are valid


if (startIndex >= 0 && endIndex <= [Link]() && startIndex < endIndex) {
[Link](startIndex, endIndex);
[Link]("\nString after deletion: " + stringBuffer);
} else {
[Link]("Invalid indices for substring deletion.");
}

[Link]();
}
}

OUTPUT:
Enter a string: HelloWorld
Enter the start index to delete a substring: 5
Enter the end index to delete a substring: 10
Length of the string: 10
Reversed string: dlroWolleH
String after deletion: Hello
8. MULTI-THREADED APPLICATION FOR RANDOM
NUMBER GENERATION AND PROCESSING

AIM:
The aim of this program is to demonstrate a multi-threaded application.

ALGORITHM:
Step 1: Create Shared Object
1. Create a shared object RandomNumberGenerator to generate random numbers.
Step 2: Create Threads
1. Create three threads:
i. generatorThread: generates random numbers every 1 second.
ii. squareThread: computes the square of the generated number if
it's even.
iii. cubeThread: computes the cube of the generated number if it's
odd.
Step 3: Start Threads
1. Start all three threads.
Step 4: Generate Random Numbers
1. In generatorThread:
i. Generate a random integer between 1 and 100.
ii. Notify the other threads using [Link]().
iii. Wait 1 second before generating the next number.
Step 5: Compute Square and Cube
1. In squareThread and cubeThread:
I. Wait until a random number is generated using [Link]().
II. Get the generated number using getRandomNumber().
III. Compute the square or cube of the number based on its parity.
IV. Print the result.
Step 6: Repeat
1. Repeat steps 4-5 indefinitely.
PROGRAM:

import [Link];

public class MultiThreadApplication {


public static void main(String[] args) {
// Creating the shared object to pass the random number between threads
RandomNumberGenerator randomGenerator = new RandomNumberGenerator();

// Creating and starting threads


Thread generatorThread = new Thread(randomGenerator);
Thread squareThread = new Thread(new SquareTask(randomGenerator));
Thread cubeThread = new Thread(new CubeTask(randomGenerator));

[Link]();
[Link]();
[Link]();
}
}

// Thread 1: Generates random numbers every 1 second


class RandomNumberGenerator implements Runnable {
private int randomNumber;
private final Object lock = new Object();

public void run() {


Random random = new Random();
while (true) {
try {
// Generate a random integer between 1 and 100
randomNumber = [Link](100) + 1;
[Link]("Generated Number: " + randomNumber);

// Notify the other threads


synchronized (lock) {
[Link]();
}

// Wait 1 second before generating the next number


[Link](1000);
} catch (InterruptedException e) {
[Link]();
}
}
}

public int getRandomNumber() {


return randomNumber;
}
public Object getLock() {
return lock;
}
}

// Thread 2: Computes the square of the number if it's even


class SquareTask implements Runnable {
private final RandomNumberGenerator randomGenerator;

public SquareTask(RandomNumberGenerator randomGenerator) {


[Link] = randomGenerator;
}

public void run() {


while (true) {
synchronized ([Link]()) {
try {
// Wait until a random number is generated
[Link]().wait();

int num = [Link]();


if (num % 2 == 0) {
[Link]("Square of " + num + ": " + (num * num));
}
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}

// Thread 3: Computes the cube of the number if it's odd


class CubeTask implements Runnable {
private final RandomNumberGenerator randomGenerator;

public CubeTask(RandomNumberGenerator randomGenerator) {


[Link] = randomGenerator;
}

public void run() {


while (true) {
synchronized ([Link]()) {
try {
// Wait until a random number is generated
[Link]().wait();

int num = [Link]();


if (num % 2 != 0) {
[Link]("Cube of " + num + ": " + (num * num * num));
}
} catch (InterruptedException e) {
[Link]();
}
}
}
}
}

OUTPUT:

Generated Number: 52
Square of 52: 2704
Generated Number: 19
Cube of 19: 6859
Generated Number: 37
Cube of 37: 50653
Generated Number: 40
Square of 40: 1600
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
9. THREADING PROGRAM TO PRINT NUMBERS
ASYNCHRONOUSLY USING TWO THREADS

AIM:
The aim of this program is to demonstrate asynchronous execution using two threads, where
Thread1 prints numbers from 1 to 10 and Thread2 prints numbers from 90 to 100.

ALGORITHM:

Step 1: Create two NumberPrinter objects with different ranges:


I. thread1: prints numbers from 1 to 10
II. thread2: prints numbers from 90 to 100
Step 2: Create two threads
Step 3: Start both threads.
Step 4: Print Numbers Asynchronously
1. In each thread:
• Print numbers in the given range using a for loop.
• Sleep for 500 milliseconds between each print statement using [Link]().

Step 5: Repeat step 4 until all numbers in the range have been printed.
PROGRAM:
class NumberPrinter implements Runnable {
private int start;
private int end;

// Constructor to initialize the start and end of the range


public NumberPrinter(int start, int end) {
[Link] = start;
[Link] = end;
}

// Overriding the run() method to print numbers in the given range


public void run() {
for (int i = start; i <= end; i++) {
[Link](i);
try {
// Sleep for a while to simulate asynchronous behavior
[Link](500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
[Link]();
}
}
}
}

public class AsyncNumberPrinter {


public static void main(String[] args) {
// Creating two threads to print numbers asynchronously
Thread thread1 = new Thread(new NumberPrinter(1, 10)); // Prints 1 to 10
Thread thread2 = new Thread(new NumberPrinter(90, 100)); // Prints 90 to 100

// Starting both threads


[Link]();
[Link]();
}
}

OUTPUT:
1
90
2
91
3
92
4
93
5
94
6
95
7
96
8
97
9
98
10
99
100
10. DEMONSTRATING DIFFERENT EXCEPTIONS

AIM:
To demonstrate the use of following exceptions.
a. Arithmetic Exception
b. Number Format Exception
c. ArrayIndexOutofBoundException
d. NegativeArraySizeException

ALGORITHM:
1. Demonstrate ArithmeticException:
I. Attempt to divide by zero.
II. Catch ArithmeticException and print error message.

2. Demonstrate NumberFormatException:
I. Attempt to parse a string to an integer.
II. Catch NumberFormatException and print error message.

3. Demonstrate ArrayIndexOutOfBoundsException:
I. Create an array with a fixed size.
II. Attempt to access an index outside the array bounds.
III. Catch ArrayIndexOutOfBoundsException and print error message.

4. Demonstrate NegativeArraySizeException:
I. Attempt to create an array with a negative size.
II. Catch NegativeArraySizeException and print error message.
PROGRAM:
public class ExceptionDemo {

public static void main(String[] args) {

// Demonstrating ArithmeticException
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
[Link]("ArithmeticException: " + [Link]());
}

// Demonstrating NumberFormatException
try {
int number = [Link]("abc"); // Invalid number format
} catch (NumberFormatException e) {
[Link]("NumberFormatException: " + [Link]());
}

// Demonstrating ArrayIndexOutOfBoundsException
try {
int[] arr = new int[3];
arr[5] = 10; // Trying to access an invalid index
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException: " + [Link]());
}

// Demonstrating NegativeArraySizeException
try {
int[] arr = new int[-5]; // Trying to create an array with negative size
} catch (NegativeArraySizeException e) {
[Link]("NegativeArraySizeException: " + [Link]());
}
}
}

OUTPUT:
ArithmeticException: / by zero
NumberFormatException: For input string: "abc"
ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
NegativeArraySizeException: Capacity cannot be negative
11. FILE INFORMATION VIEWER

AIM:
To read on file name from the user, then displays information about whether the file exists,
whether the file is readable, whether the file is writable, the type of file and the length of the
file in bytes using Java Programming.

ALGORITHM:
1. Create a scanner object to read input from the user.
2. Prompt the user to enter a file name.
3. Create a File object with the provided file name.
4. Check if the file exists using the exists() method.
5. If the file exists, perform the following checks:
I. Readability using the canRead() method.
II. Writability using the canWrite() method.
III. File type (directory or regular file) using the isDirectory() method.
IV. File length using the length() method.
6. If the file does not exist, print a message indicating that the file does not exist.
7. Close the scanner object.
PROGRAM:
import [Link];
import [Link];

public class FileInfo {

public static void main(String[] args) {


// Create a scanner object to read input from the user
Scanner scanner = new Scanner([Link]);

// Prompt the user to enter a file name


[Link]("Enter the file name (with path if needed): ");
String fileName = [Link]();

// Create a File object with the provided file name


File file = new File(fileName);

// Check if the file exists


if ([Link]()) {
[Link]("File exists: Yes");

// Check if the file is readable


[Link]("File is readable: " + [Link]());

// Check if the file is writable


[Link]("File is writable: " + [Link]());

// Check if the file is a directory or a file


if ([Link]()) {
[Link]("The file is a directory.");
} else {
[Link]("The file is a regular file.");
}

// Get the length of the file in bytes


[Link]("File size: " + [Link]() + " bytes");
} else {
[Link]("File does not exist.");
}

// Close the scanner


[Link]();
}
}
OUTPUT:
Enter the file name (with path if needed): [Link]
File exists: Yes
File is readable: true
File is writable: false
The file is a regular file.
File size: 12345 bytes
12. TEXT EDITOR

AIM:
To accept a text and change its size and font. Include bold italic options. Use frames and
controls.

ALGORITHM:
1. Create a GUI application with a text area and controls for font size, font family, bold, and
italic.
2. Initialize the text area with a default font.
3. Create combo boxes for font size and font family.
4. Add action listeners to the combo boxes to update the font when a selection is made.
5. Create check boxes for bold and italic.
6. Add action listeners to the check boxes to update the font when a selection is made.
7. Create a method to update the font based on the current selections.
8. Use the [Link]() method to create and display the GUI application.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class TextEditor extends JFrame {


private JTextArea textArea;
private JComboBox<String> fontSizeComboBox;
private JComboBox<String> fontFamilyComboBox;
private JCheckBox boldCheckBox, italicCheckBox;

public TextEditor() {
// Set the title and layout of the frame
setTitle("Text Editor - Change Font and Size");
setLayout(new BorderLayout());

// Initialize the text area where the text will be entered


textArea = new JTextArea(10, 30);
[Link](new Font("Arial", [Link], 14));
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, [Link]);

// Create a panel for controls (font size, font family, bold, italic)
JPanel controlsPanel = new JPanel();

// Font size combo box


String[] fontSizes = {"12", "14", "16", "18", "20", "22", "24"};
fontSizeComboBox = new JComboBox<>(fontSizes);
[Link]("14");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateFont();
}
});

// Font family combo box


String[] fontFamilies = {"Arial", "Verdana", "Times New Roman", "Courier New"};
fontFamilyComboBox = new JComboBox<>(fontFamilies);
[Link]("Arial");
[Link](new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateFont();
}
});

// Bold and Italic checkboxes


boldCheckBox = new JCheckBox("Bold");
italicCheckBox = new JCheckBox("Italic");

// Add components to the controls panel


[Link](new JLabel("Font Size:"));
[Link](fontSizeComboBox);
[Link](new JLabel("Font Family:"));
[Link](fontFamilyComboBox);
[Link](boldCheckBox);
[Link](italicCheckBox);

add(controlsPanel, [Link]);

// Set up frame options


setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

// Method to update font based on selections


private void updateFont() {
String fontFamily = (String) [Link]();
int fontSize = [Link]((String) [Link]());

int fontStyle = [Link];


if ([Link]()) {
fontStyle |= [Link];
}
if ([Link]()) {
fontStyle |= [Link];
}

Font font = new Font(fontFamily, fontStyle, fontSize);


[Link](font);
}

public static void main(String[] args) {


[Link](new Runnable() {
@Override
public void run() {
new TextEditor().setVisible(true);
}
});
}
}
OUTPUT:
13. MOUSE EVENT DEMO PROGRAM

AIM:
To handles all mouse events and shows the event name at the center of the window when a
mouse event is fired using Java programming.

ALGORITHM:
1. Create a GUI application with a custom panel to handle and display mouse events.
2. Set up the frame with a title, size, and default close operation.
3. Create a custom panel (MousePanel) to handle and display mouse events.
4. Add mouse listeners to the panel using adapter classes (MouseAdapter and
MouseMotionAdapter).
5. Handle mouse events (e.g., clicked, pressed, released, entered, exited, moved, dragged) and
update the displayed event name.
6. Use the repaint() method to update the displayed event name.
7. Use the [Link]() method to create and display the GUI application.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link].*;

public class MouseEventDemo extends JFrame {


private String eventName = "No Event";

public MouseEventDemo() {
// Set up the frame
setTitle("Mouse Event Handler");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Create a custom panel to handle and display mouse events


MousePanel panel = new MousePanel();
add(panel);

// Add mouse listeners using adapter classes


[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}

@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}

@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}

@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
});

[Link](new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
[Link]("Mouse Moved");
}

@Override
public void mouseDragged(MouseEvent e) {
[Link]("Mouse Dragged");
}
});
}

// Custom JPanel class to handle and display the event name


class MousePanel extends JPanel {
private String eventName = "No Event";
public void setEventName(String eventName) {
[Link] = eventName;
repaint(); // Repaint the panel to update the displayed event name
}

@Override
protected void paintComponent(Graphics g) {
[Link](g);
[Link](new Font("Arial", [Link], 20));
[Link]([Link]);
// Draw the event name at the center of the panel
FontMetrics fm = [Link]();
int x = (getWidth() - [Link](eventName)) / 2;
int y = (getHeight() + [Link]()) / 2;
[Link](eventName, x, y);
}
}

public static void main(String[] args) {


[Link](() -> {
MouseEventDemo demo = new MouseEventDemo();
[Link](true);
});
}
}
OUTPUT:
14. SIMPLE CALCULATOR WITH GUI USING JAVA SWING

AIM:
To design and implement a Java program for a simple calculator using a graphical user
interface (GUI) with Java Swing. The program should handle basic arithmetic operations (+, -
, *, /, %) and display the results in a text field, while also managing exceptions such as
division by zero. The layout should utilize a GridLayout for arranging the buttons.

ALGORITHM:
1. Create a GUI application with a text field for display and a panel for buttons.
2. Define the buttons for digits 0-9, operators (+, -, *, /, %), and equals (=).
3. Handle button clicks:
1. For digit buttons, append the digit to the current number.
2. For operator buttons, store the operator and the current number.
3. For equals button, perform the calculation using the stored operator and numbers.
4. Display the result of the calculation in the text field.
5. Handle errors:
1. For invalid numbers, display an error message.
2. For arithmetic exceptions (e.g., division by zero), display an error message.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class SimpleCalculator extends JFrame {


private JTextField display;
private String currentNumber = "";
private String operator = "";
private double firstOperand = 0;

public SimpleCalculator() {
// Set up the frame
setTitle("Simple Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new BorderLayout());

// Create a display text field


display = new JTextField();
[Link](new Font("Arial", [Link], 24));
[Link]([Link]);
[Link](false);
add(display, [Link]);

// Create a panel for buttons


JPanel buttonPanel = new JPanel();
[Link](new GridLayout(4, 4, 5, 5));

// Define button labels


String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "%", "=", "+"
};

// Add buttons to the panel


for (String label : buttons) {
JButton button = new JButton(label);
[Link](new Font("Arial", [Link], 20));
[Link](new ButtonClickListener());
[Link](button);
}

add(buttonPanel, [Link]);
}

private class ButtonClickListener implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
String command = [Link]();

try {
if ("0123456789".contains(command)) {
// Append digit to the current number
currentNumber += command;
[Link](currentNumber);
} else if ("+-*/%".contains(command)) {
// Handle operator input
if (![Link]()) {
firstOperand = [Link](currentNumber);
currentNumber = "";
operator = command;
}
} else if ([Link]("=")) {
// Perform calculation
if (![Link]() && ![Link]()) {
double secondOperand = [Link](currentNumber);
double result;

switch (operator) {
case "+":
result = firstOperand + secondOperand;
break;
case "-":
result = firstOperand - secondOperand;
break;
case "*":
result = firstOperand * secondOperand;
break;
case "/":
if (secondOperand == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
result = firstOperand / secondOperand;
break;
case "%":
result = firstOperand % secondOperand;
break;
default:
throw new IllegalStateException("Unexpected operator: " + operator);
}
[Link]([Link](result));
currentNumber = ""; // Clear for the next calculation
operator = ""; // Clear operator
}
}
} catch (NumberFormatException ex) {
[Link]("Error: Invalid Number");
currentNumber = "";
operator = "";
} catch (ArithmeticException ex) {
[Link]("Error: " + [Link]());
currentNumber = "";
operator = "";
}
}
}

public static void main(String[] args) {


[Link](() -> {
SimpleCalculator calculator = new SimpleCalculator();
[Link](true);
});
}
}
OUTPUT:
[Link] LIGHT SIMULATOR

AIM:
To design and implement a Java program that simulates a traffic light system using GUI
components. The program should allow the user to select one of the three lights (Red, Yellow,
or Green) using radio buttons, and display an appropriate message ("Stop", "Ready", or "Go")
in the corresponding color. The initial state of the program should show no message.

ALGORITHM:
1. Create a GUI application with radio buttons for red, yellow, and green traffic lights.
2. Create a label to display the message corresponding to the selected traffic light.
3. Group the radio buttons to ensure only one can be selected at a time.
4. Add action listeners to the radio buttons to handle selection events.
5. When a radio button is selected:
- Update the message label with the corresponding message (e.g., "Stop", "Ready", "Go").
- Update the color of the message label to match the selected traffic light.
6. Display the GUI application.
PROGRAM:
import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class TrafficLightSimulator extends JFrame {


private JLabel messageLabel; // Label to display the message
private JRadioButton redButton, yellowButton, greenButton; // Radio buttons for traffic
lights
private ButtonGroup buttonGroup; // Group for radio buttons

public TrafficLightSimulator() {
// Set up the frame
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create the message label


messageLabel = new JLabel("", [Link]);
[Link](new Font("Arial", [Link], 16));
add(messageLabel, [Link]);

// Create the radio buttons


redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");

// Group the radio buttons


buttonGroup = new ButtonGroup();
[Link](redButton);
[Link](yellowButton);
[Link](greenButton);

// Add ActionListener to radio buttons


[Link](new TrafficLightAction("Stop", [Link]));
[Link](new TrafficLightAction("Ready", [Link]));
[Link](new TrafficLightAction("Go", [Link]));

// Add the radio buttons to a panel


JPanel buttonPanel = new JPanel();
[Link](new FlowLayout());
[Link](redButton);
[Link](yellowButton);
[Link](greenButton);

add(buttonPanel, [Link]);

// Center the frame on the screen


setLocationRelativeTo(null);
}

// Inner class to handle radio button actions


private class TrafficLightAction implements ActionListener {
private String message;
private Color color;

public TrafficLightAction(String message, Color color) {


[Link] = message;
[Link] = color;
}

@Override
public void actionPerformed(ActionEvent e) {
[Link](message);
[Link](color);
}
}

public static void main(String[] args) {


[Link](() -> {
TrafficLightSimulator simulator = new TrafficLightSimulator();
[Link](true);
});
}
}
OUTPUT:

You might also like