AIET/IQAC/Aca/24-25/CFF
AKASH INSTITUTE OF ENGINEERING AND TECHNOLOGYDEVANAHALLI,
BENGALURU-562110
OOPS WITH JAVA[BCS306A]
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
By.
Madhu N
Assistant professor
Department of Computer Science Engineering
AKASH INSTITUTE OF ENGINEERING AND TECHNOLOGY
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Module 1
Principles of java, Data types, Variables, Arrays and Operators
The statement "compile once, run anywhere" is a key feature of Java, which reflects its platform
independence. This means that Java programs, once compiled, can run on any device or operating system
that has a Java Virtual Machine (JVM), without needing to be recompiled. Here's how this works:
Explanation:
Java Source Code:
Java source code is written in .javafiles using the Java programming language.
This source code is then compiled by the Java compiler (javac) into anintermediate bytecode.
Java Bytecode:
The compiled bytecode is saved in .classfiles.
Bytecode is a highly optimized, platform-independent set of instructions that is not tied to any specific
machine architecture.
It is neither machine code nor high-level source code, but something in between.
Java Virtual Machine (JVM):
Bytecode is executed by the Java Virtual Machine (JVM), which acts as an interpreter and runtime
environment for the Java program.
The JVM translates the bytecode into machine code, specific to the platform (e.g., Windows, macOS,
Linux) on which it is running.
Each platform has its own JVM implementation, but the bytecode remains thesame across platforms.
Platform Independence:
Since the JVM handles the translation from bytecode to platform-specific machine code, the Java
program can run on any platform (e.g., Windows, macOS, Linux, mobile devices) as long as that
platform has a compatible JVM.
This means that the same Java bytecode can be run on any system, without recompiling the source code
for each platform.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Key Elements Behind "Compile Once, Run Anywhere":
Java Compiler (javac): The Java compiler converts Java source code into platform-independent
bytecode.
Java Virtual Machine (JVM): The JVM is the platform-specific component thatinterprets
bytecode into machine code for the underlying operating system.
Bytecode: The platform-independent bytecode enables the program to be compiledonce and run on
any system with a JVM.
Object oriented principles:
Object-Oriented Programming (OOP) in Java is based on four fundamental principles: Encapsulation,
Inheritance, Polymorphism, and Abstraction. These principles allow Java to create modular, reusable,
and maintainable code.
Encapsulation
Encapsulation is the principle of bundling data (fields) and methods that operate on that data within
a single unit, or class. It also restricts direct access to certain details of an object’s data, often using
private access modifiers. This keeps internal data safe from external modifications and allows control
over how data is accessed or modified.
Getters and Setters: To access or modify private fields, public methods called getters and
setters are often provided.
Benefits: Encapsulation promotes modularity, code reusability, and data security.
Inheritance
Inheritance allows a class to inherit properties and methods from another class, enabling code reuse
and the establishment of a hierarchy. The class that inherits is called the subclass or derived class, and
the class it inherits from is called the superclass or base class.
Syntax: In Java, inheritance is achieved using the extendskeyword.
Single Inheritance: Java supports single inheritance, meaning each class can inherit from onlyone
superclass.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Polymorphism:
Polymorphism allows one interface to be used for different data types, so objects of different classes
can be treated as objects of a common superclass. This enables a single action to behave differently
based on the object that it’s acting upon.
Polymorphism is achieved through method overriding (runtime polymorphism) and method
overloading (compile-time polymorphism).
Method Overloading: Allows a class to have multiple methods with the same name butdifferent
parameters.
Method Overriding: Allows a subclass to provide a specific implementation of a methodalready
defined in its superclass.
Abstraction:
Abstraction is the process of hiding the complex implementation details of a system and exposing only
the necessary parts. In Java, abstraction is achieved using abstract classes and interfaces.
Abstract Class: A class that cannot be instantiated and may contain abstract methods(methods without
implementation).
Interface: A completely abstract class that defines methods but does not implement them,allowing
different classes to implement these methods as needed.
Data Types
In Java, primitive data types are the most basic types of data. They are not objects, and theyhold their
values directly in memory.
There are two types of data types in java:
Primitive Data type
Non-primitive Data type
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Java provides eight primitive data types, each with a specific size and a corresponding value range:
byte
Size: 1 byte (8 bits)
Value range: -128 to 127
Usage: Useful for saving memory in large arrays where the memory savings actually matter. It can also
be used in place of int where the values are small enough to fit in a byte.
short
Size: 2 bytes (16 bits)
Value range: -32,768 to 32,767
Usage: Used to save memory in large arrays, especially where the data is small enoughto fit within this
range.
Int:
Size: 4 bytes (32 bits)
Value range: -2^31 to 2^31 - 1 (around -2.1 billion to 2.1 billion)
Usage: Most commonly used integer type to store whole numbers.
long
Size: 8 bytes (64 bits)
Value range: -2^63 to 2^63 - 1 (around -9.2 quintillion to 9.2 quintillion)
Usage: Used when a wider range of values than intis needed.
float
Size: 4 bytes (32 bits)
Value range: Approximately ±3.40282347E+38F (7 significant decimal digits)
Usage: Used to save memory in large arrays of floating-point numbers and when you need fractional
values with less precision.
double:
Size: 8 bytes (64 bits)
Value range: Approximately ±1.79769313486231570E+308 (15 significant decimaldigits)
Usage: Default data type for decimal values, generally used for high precision.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
boolean
Size: Depends on the JVM (typically 1 bit, but JVM may store it as 1 byte for efficiency)
Value range: trueor false
Usage: Used for simple flags that track true/false conditions.
char
Size: 2 bytes (16 bits)
Value range: 0 to 65,535 (Unicode character set)
Usage: Used to store a single character/letter or ASCII values.
Key points:
Default Values: Each primitive data type has a default value. For example, intdefaultsto 0, boolean
defaults to false, etc.
Efficiency: Since they are not objects, they are stored more efficiently and processed faster.
No Methods: Primitive types do not have methods. However, Java provides wrapper classes (Byte,
Short, Integer, Long, Float, Double, Boolean, and Character) whichallow primitive types to be treated like
objects when needed.
Primitive data types form the backbone of data storage and manipulation in Java.
Example:
Java program to print default values for all primitive data types:
public class DefaultValues {
// Declaring instance variables for all primitive data types
byte byteValue;
short shortValue;
int intValue;
long longValue;
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
float floatValue;
double doubleValue;
char charValue;
boolean booleanValue;
public static void main(String[] args) {
// Create an instance of the DefaultValues class
DefaultValues defaults = new DefaultValues();
// Print the default values of the data types
[Link]("Default value of byte: " + [Link]);
[Link]("Default value of short: " + [Link]);
[Link]("Default value of int: " + [Link]);
[Link]("Default value of long: " + [Link]);
[Link]("Default value of float: " + [Link]);
[Link]("Default value of double: " + [Link]);
[Link]("Default value of char: '" + [Link]);
[Link]("Default value of boolean: " + [Link]);
Output:
The default values for each data type in Java are as follows:
byte: 0
short: 0
int: 0
long: 0L
float: 0.0f
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
double: 0.0d
char: '\u0000' (null character)
boolean: false
Java program to print specific values for all primitive data types:
public class DataTypesValues {
public static void main(String[] args) {
// Assigning values to all primitive data types
byte byteValue = 100;
short shortValue = 30000;
int intValue = 123456;
long longValue = 123456789L;
float floatValue = 12.34f;
double doubleValue = 123.456;
char charValue = 'A';
boolean booleanValue = true;
// Printing values of each data type
[Link]("Value of byte: " + byteValue);
[Link]("Value of short: " + shortValue);
[Link]("Value of int: " + intValue);
[Link]("Value of long: " + longValue);
[Link]("Value of float: " + floatValue);
[Link]("Value of double: " + doubleValue);
[Link]("Value of char: " + charValue);
[Link]("Value of boolean: " + booleanValue);
}}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Output:
Value of byte: 100
Value of short: 30000
Value of int: 123456
Value of long: 123456789L
Value of float: 12.35f
Value of double: 12.254776532
Value of char: A
Value of Boolean: true
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Lexical issues:
In Java, lexical issues are related to how the Java compiler processes the source code and converts it into
tokens, which are the basic building blocks of the language. Lexical issues dealwith identifiers, keywords,
literals, comments, and other elements that form the syntax of Javacode. Some common lexical issues
include:
Whitespace:
Java uses whitespace (spaces, tabs, newlines) to separate tokens like keywords, variables, operators, etc.
However, whitespace is generally ignored beyond this role.
Example of correct usage:int a = 5;
Issue: Misplacement or omission of necessary spaces may cause syntax errors, likewriting:
Int a=5; // Causes an error because the identifier is not properly separated from the type
Comments:
Java supports two types of comments:
Single-line comments: Start with // and extend to the end of the line.
Multi-line comments: Start with /* and end with */. These can spanmultiple lines.
Document comments: Start with /** and end with */.
Comments Description
The compiler ignores everything from // tothe
//single line comment end of the line
/*text*/ multi-line comments The compiler ignores everything from /* to*/
This is a documentation comment and ingeneral
/**documentation*/ it's called doc comment.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Lexical issue: Unclosed or improperly nested comments may lead to compilation errorsor unintended
behaviour.
Example:
/* This is a comment /* Nested comment */ // This is invalid
Identifiers:
Identifiers are names for variables, methods, classes, etc. Lexical issues arise whenidentifiers violate
Java’s rules:
Must start with a letter, $, or _.
Cannot be a keyword (e.g., int, class).
Cannot be a number (e.g., 2Bike, 5Triangle)
Cannot contain spaces or special characters like !, #, %.
Issue: Using an invalid identifier name.
Example of invalid usage
int 2num = 5; // Error: identifier cannot start with a number
Keywords:
Java has a set of reserved keywords that cannot be used as identifiers. These includeint, class, if, else,
for, etc.
Issue: Using a keyword as a variable or method name.
Example of incorrect usage
int class = 10; // Error: 'class' is a reserved keyword
Separators:
In java, there are a few characters that are used as separators. The most used separatorin java is the
semicolon. As you have seen, it is used to terminate statements.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
symbol Name purpose
{} parentheses Define blocks of code, such as class bodies, method bodies, and loop
() Braces Used for method calls, defining parameters, and grouping expressions
[] Brackets Used to declare array types. Also used when dereferencing array values
; semicolon Terminates statements
, comma Separates consecutive identifiers in a variable declaration. Also used to
chain statements together inside a for statement.
Example of an error:
if (a > b // Missing closing parenthesis
[Link]("a is greater") //missing semicolon
//missing curly braces
Java Variable:
A variable in Java is a named location in memory that stores data. Variables are used to holdinformation
that can be referenced and manipulated in a program. Each variable has:
Data type: Determines the kind of data the variable will store (e.g., int, float, String).
Name: A unique identifier used to access the variable.
Scope: The part of the program where the variable can be accessed.
Value: The data stored in the variable.
Types of Variables in Java
Java variables are classified into three main categories based on where they are declared andhow they are
used:
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
1. Local Variables
2. Instance Variables
3. Static (or Class) Variables
Local Variables:
Definition: A local variable is declared inside a method, constructor, or block of code. It is only
accessible within that block of code.
Lifetime: The variable exists only during the execution of the method or block. Oncethe method or
block ends, the local variable is destroyed.
Default Value: Local variables do not have a default value, so they must beinitialized before use.
public class LocalVariableExample {
public void printNumber() {
int number = 10; // Local variable
[Link]("Number: " + number);
public static void main(String[] args) {
LocalVariableExample obj = new LocalVariableExample();
[Link]();
In this example, the variable number is a local variable because it is declared inside the printNumber
method.
Instance Variables
Definition: Instance variables are declared inside a class but outside any method orblock. They are
associated with an instance of the class.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Lifetime: They exist for as long as the instance of the class (the object) exists. Eachobject of the class
has its own copy of instance variables.
Default Value: Instance variables have default values if not initialized explicitly (e.g.,0 for integers, null
for objects).
public class InstanceVariableExample {
int age; // Instance variable
public static void main(String[] args) {
InstanceVariableExample obj1 = new InstanceVariableExample();
[Link] = 25;
[Link]("Age of obj1: " + [Link]);
InstanceVariableExample obj2 = new InstanceVariableExample();
[Link] = 30;
[Link]("Age of obj2: " + [Link]);
In this example, age is an instance variable, and each object (obj1 and obj2) has its own copyof age.
Static (Class) Variables
Definition: Static variables are declared with the static keyword inside a class but outside any method or
block. They belong to the class, not to any specific instance,and there is only one copy of the variable
shared among all instances.
Lifetime: Static variables are created when the program starts and destroyed when theprogram ends.
Default Value: Like instance variables, static variables also have default values if notinitialized
explicitly.
public class StaticVariableExample {
static String companyName = "TechCorp"; // Static variable
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
public static void main(String[] args) {
StaticVariableExample obj1 = new StaticVariableExample();
[Link]("Company Name (obj1): " + [Link]);
StaticVariableExample obj2 = new StaticVariableExample();
[Link]("Company Name (obj2): " + [Link]);
// Changing static variable value
[Link] = "NewTech";
[Link]("Updated Company Name: " + [Link]);
Typecasting in java:
Type casting in Java is the process of converting one data type into another. It is used when you want to
assign a value of one type to a variable of another type. Java supports two typesof type casting:
1. Widening (Implicit) Casting
2. Narrowing (Explicit) Casting
Widening (Implicit) Type Casting
Definition: Widening type casting happens automatically when a smaller data type isassigned to a larger
data type. It is safe because there is no data loss.
Types: The conversion happens in the following direction:
byte → short → int → long → float → double
public class WideningCasting {
public static void main(String[] args) {int myInt = 9; // 32-bit integer
double myDouble = myInt; // Implicit casting: int to double (64-bit)
[Link]("Integer value: " + myInt);
[Link]("Double value: " + myDouble);
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
In this example, the intvariable myInt is automatically cast to a doublewithout any explicit instruction,
because double has a larger size and can safely hold the integer value.
Narrowing (Explicit) Type Casting
Definition: Narrowing type casting must be done manually when you are trying to convert a larger data
type into a smaller one. It is not done automatically because itmay result in data loss.
Types: The conversion happens in the opposite direction:
double → float → long → int → short → byte
Syntax:
dataType variableName = (dataType) value;
Example:
public class NarrowingCasting {
public static void main(String[] args) {
double myDouble = 9.78; // 64-bit floating-point
int myInt = (int) myDouble; // Explicit casting: double to int (32-bit)
[Link]("Double value: " + myDouble);
[Link]("Integer value: " + myInt);
In this example, the double value 9.78 is explicitly cast to an int, resulting in the loss of the decimal
portion (9.78 becomes 9).
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Detailed Explanation of the Types of Casting:
Widening Casting (Automatic / Implicit)
How it works: The smaller data type is automatically converted into a larger datatype.
Why it’s safe: There is no loss of information because the larger data type cancontain all the values of
the smaller data type.
Example (byte to int)
byte smallNumber = 10;
int largerNumber = smallNumber; // No need for explicit casting
Narrowing Casting (Manual / Explicit)
How it works: The larger data type is converted into a smaller data type, but it mustbe done manually.
Why it’s not safe: Narrowing may lead to data loss if the larger value cannot fit intothe smaller type.
Example (double to int)
double largeNumber = 25.99;
int smallerNumber = (int) largeNumber; // Explicit casting is required
Arrays in Java:
An array in Java is a data structure that holds a fixed number of values of the same data [Link] are
used to store multiple values in a single variable, instead of declaring separate variables for each value.
Characteristics of Arrays in Java:
Arrays are fixed in size: The size of an array is determined when the array iscreated and cannot be
changed later.
Arrays store homogeneous data: All elements in an array must be of the samedata type (e.g., int, float,
String).
Arrays are indexed: The elements of an array are accessed using an index,with the first element at index
0.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Array Declaration and Initialization:
Declaration: Arrays are declared with the following
syntax:
dataType[] arrayName; // Recommended
dataType arrayName[]; // Also valid
Initialization: Arrays are initialized with the new keyword, specifying the size orproviding initial
values:
arrayName = new dataType[size]; // Initializing with size
arrayName = new dataType[]{value1, value2}; // Initializing with values
Types of Arrays in Java:
1. Single-Dimensional Array
2. Multi-Dimensional Array (2D and higher dimensions)
Single-Dimensional Array
A single-dimensional array stores a list of elements in a linear form. It is the simplest typeof array.
Syntax: dataType[] arrayName = new dataType[size];
Example:
public class SingleDimensionalArray { public static void main(String[] args) {
// Declaration and initialization
int[] numbers = new int[5]; // Array of 5 integersnumbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Accessing array elements
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
}
In this example, the array numbers holds 5 integer values, and they are accessed using theindex.
Multi-Dimensional Array
A multi-dimensional array is an array of arrays, where each element of the array can itself be an array.
The most common form of multi-dimensional array is the 2D array (or matrix),but Java allows arrays of
more than two dimensions.
2D Array (Two-Dimensional Array)
A 2D array can be thought of as a table or matrix with rows and columns.
Syntax:
dataType[][] arrayName = new dataType[rows][columns];
Example:
public class TwoDimensionalArray { public static void main(String[] args) {
// Declaration and initialization
int[][] matrix = new int[3][3]; // 3x3 matrix (2D array)matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;
// Accessing 2D array elementsfor (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) { [Link](matrix[i][j] + " ");
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
[Link]();
}}}
In this example, matrix is a 2D array with 3 rows and 3 columns. The elements are accessedusing two
indices: one for the row and one for the column.
Array Initialization with Values
You can initialize an array directly with values:
Example:
public class ArrayInitialization {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50}; // Declaration and initialization
// Accessing array elements for (int number : numbers) {
[Link](number);
Array Length
The length of an array can be determined using the length property.
Example:
int[] numbers = {10, 20, 30};
[Link]("Array length: " + [Link]); // Output: 3
Operators in java
In Java, operators are special symbols used to perform operations on variables and [Link] are
classified into several categories based on the type of operation they perform.
Here’s a breakdown of the main types of operators in Java:
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Arithmetic Operators
These operators are used to perform basic arithmetic operations:
+ : Addition
- : Subtraction
* : Multiplication
/ : Division
% : Modulus (remainder of division)
int a = 10;
int b = 3;
[Link](a + b); // Output: 13
[Link](a - b); // Output: 7
[Link](a * b); // Output: 30
[Link](a / b); // Output: 3
[Link](a % b); // Output: 1
Unary Operators
These operate on a single operand and change its value.
+ : Unary plus (indicates positive value)
- : Unary minus (negates the value)
++ : Increment operator (increases value by 1)
Pre-increment: ++a (increments first, then uses the value)
Post-increment: a++ (uses the value, then increments)
-- : Decrement operator (decreases value by 1)
Pre-decrement: --a
Post-decrement: a—
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
! : Logical NOT (inverts boolean value)
Example:
int a = 5;
[Link](++a); // Output: 6
[Link](a--); // Output: 6 (uses value, then decrements)
[Link](a); // Output: 5
Relational (Comparison) Operators
These are used to compare two values and return a boolean result (true or false).
== : Equal to
!= : Not equal to
> : Greater than
< : Less than
>= : Greater than or equal to
<= : Less than or equal to
Example:
int x = 5;
int y = 10;
[Link](x == y); // Output: [Link](x < y); // Output: true
Logical Operators
These are used to combine multiple conditions (boolean expressions).
&& : Logical AND (true if both operands are true)
|| : Logical OR (true if at least one operand is true)
! : Logical NOT (inverts the value of the boolean expression)
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Example:
int x = 5;
int y = 10;
[Link](x == y); // Output: false
[Link](x < y); // Output: true
Logical Operators
These are used to combine multiple conditions (boolean expressions).
&& : Logical AND (true if both operands are true)
|| : Logical OR (true if at least one operand is true)
! : Logical NOT (inverts the value of the boolean expression)
Example:
boolean a = true;
boolean b = false;
[Link](a && b); // Output: false
[Link](a || b); // Output: true
[Link](!a); // Output: false
Bitwise Operators
These operate on bits of integers.
& : Bitwise AND
| : Bitwise OR
^ : Bitwise XOR
~ : Bitwise NOT
<< : Left shift
>> : Right shift
>>> : Unsigned right shift
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Example:
int a = 5; // In binary: 0101
int b = 3; // In binary: 0011
[Link](a & b); // Output: 1 (0101 & 0011 = 0001)
[Link](a | b); // Output: 7 (0101 | 0011 = 0111)
In Java, right shift (>>) and left shift (<<) operators are used to shift the bits of a number tothe right or
left, respectively. These are bitwise shift operators, and they manipulate the binary representation of
numbers.
Left Shift (<<) Operator:
The left shift operator shifts all the bits of a number to the left by the specified number ofpositions. It
fills the vacant rightmost positions with zeros (0), and each shift to the left effectively multiplies the
number by 2.
Syntax: number << positions
int a = 5; // Binary representation: 0000 0101
int result = a << 1; // Shifts bits to the left by 1 position
[Link](result); // Output: 10 (Binary: 0000 1010)
result = a << 2; // Shifts bits to the left by 2 positions
[Link](result); // Output: 20 (Binary: 0001 0100)
How it works:
5 in binary is 0000 0101.
When you shift it left by 1 (5 << 1), you get 0000 1010, which is 10 in decimal.
When you shift it left by 2 (5 << 2), you get 0001 0100, which is 20 in decimal.
Key point: Each left shift by 1 position is equivalent to multiplying the number by 2.
Right Shift (>>) Operator:
The right shift operator shifts all the bits of a number to the right by the specified number ofpositions.
The sign bit (the leftmost bit) is preserved, which means it fills the leftmost positions with the value of
the sign bit (0 for positive numbers, 1 for negative numbers).
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Syntax: number >> positions
Example:
int a = 20; // Binary representation: 0001 0100
int result = a >> 1; // Shifts bits to the right by 1 position
[Link](result); // Output: 10 (Binary: 0000 1010)
result = a >> 2; // Shifts bits to the right by 2 positions
[Link](result); // Output: 5 (Binary: 0000 0101)
How it works:
20 in binary is 0001 0100.
When you shift it right by 1 (20 >> 1), you get 0000 1010, which is 10 in decimal.
When you shift it right by 2 (20 >> 2), you get 0000 0101, which is 5 in decimal.
Key point: Each right shift by 1 position is equivalent to dividing the number by 2 (ignoringany
remainder).
Unsigned Right Shift (>>>) Operator
Java also has the unsigned right shift operator (>>>), which is similar to the right shift but without
preserving the sign bit. It always fills the leftmost positions with zeros (0), even if thenumber is negative.
Example:
int a = -20; // Binary representation: 1111 1111 1111 1111 1111 1111 1110 1100 (for 32-bitsigned
integer)
int result = a >> 2; // Signed right shift
[Link](result); // Output: -5 (Binary: 1111 1111 1111 1111 1111 1111 1111
1111)
result = a >>> 2; // Unsigned right shift
[Link](result); // Output: 1073741819 (Binary: 0011 1111 1111 1111 1111 1111
1110 1100)
How it works:
In the signed right shift (>>), the sign bit (1) is preserved for negative numbers, soshifting -20 right by 2
gives -5.
In the unsigned right shift (>>>), the sign bit is not preserved, so it fills with zeros,which produces a
large positive number when shifting -20.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Assignment Operators
These are used to assign values to variables.
= : Simple assignment
+= : Add and assign
-= : Subtract and assign
*= : Multiply and assign
/= : Divide and assign
%= : Modulus and assign
int a = 5;
a += 3; // Equivalent to a = a + 3
[Link](a); // Output: 8
Ternary Operator:
Also known as the conditional operator, it’s a shorthand for an if-else statement.
Syntax: condition ? expression1 : expression2
Example:
int a = 5;
int b = 10;
int result = (a > b) ? a : b;
[Link](result); // Output: 10
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Previous year question paper programming questions
Develop a java program to convert celsius temperature to fahrenheit
import [Link];
public class CelsiusToFahrenheit {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter temperature in Celsius
[Link]("Enter temperature in Celsius: ");
double celsius = [Link]();
// Convert Celsius to Fahrenheit
double fahrenheit = (celsius * 9/5) + 32;
// Display the result
[Link]("%.2f Celsius is equal to %.2f Fahrenheit%n", celsius, fahrenheit);
// Close the scanner
[Link]();
}
}
Output:
Enter temperature in Celsius: 25
25.00 Celsius is equal to 77.00 Fahrenheit
write a java program to add two matrices using command line arguments
public class MatrixAddition {
public static void main(String[] args) {
// Check if the correct number of arguments is provided
if ([Link] != 12) {
[Link]("Please provide 12 values for two 3x2 matrices.");
return;
}
// Initialize two matrices
int[][] matrixA = new int[3][2];
int[][] matrixB = new int[3][2];
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
int[][] sumMatrix = new int[3][2];
// Fill the matrices from command line arguments
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
matrixA[i][j] = [Link](args[(i * 2) + j]);
matrixB[i][j] = [Link](args[(i * 2) + j + 6]); // Next 6 for the second matrix
}
}
// Add the two matrices
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
sumMatrix[i][j] = matrixA[i][j] + matrixB[i][j];
}
}
// Print the resulting sum matrix
[Link]("Sum of the two matrices:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
[Link](sumMatrix[i][j] + " ");
}
[Link]();
}
}
}
Output:
javac [Link]
java MatrixAddition 1 2 3 4 5 6 7 8 9 10 11 12
Matrix A:
1 2
3 4
5 6
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Matrix B:
78
9 10
11 12
Addition Matrix:
8 10
12 14
16 18
Develop a java program to find area of rectangle, area of circle and area of triangleusing method
overloading concept. call these from main method with suitable inputs.
import [Link];
public class AreaCalculator {
// Method to calculate the area of a rectangle
public double area(double length, double width) {
return length * width;
}
// Method to calculate the area of a circle
public double area(double radius) {
return [Link] * radius * radius;
}
// Method to calculate the area of a triangle
public double area(double base, double height) {
return 0.5 * base * height;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
AreaCalculator calculator = new AreaCalculator();
// Calculate area of a rectangle
[Link]("Enter length of rectangle: ");
double length = [Link]();
[Link]("Enter width of rectangle: ");
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
double width = [Link]();
double rectangleArea = [Link](length, width);
[Link]("Area of Rectangle: %.2f%n", rectangleArea);
// Calculate area of a circle
[Link]("Enter radius of circle: ");
double radius = [Link]();
double circleArea = [Link](radius);
[Link]("Area of Circle: %.2f%n", circleArea);
// Calculate area of a triangle
[Link]("Enter base of triangle: ");
double base = [Link]();
[Link]("Enter height of triangle: ");
double height = [Link]();
double triangleArea = [Link](base, height);
[Link]("Area of Triangle: %.2f%n", triangleArea);
// Close the scanner
[Link]();
}
}
Output:
Enter length of rectangle: 5
Enter width of rectangle: 3
Area of Rectangle: 15.00
Enter radius of circle: 4
Area of Circle: 50.27
Enter base of triangle: 6
Enter height of triangle: 4
Area of Triangle: 12.00
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Develop a java program to create a class called "Employee" which contains
'name','designation','empid' and 'salaryid' as instance variables and read() and write as methods.
using this class, read and write 5 employee information from main() method.
import [Link];
class Employee {
// Instance variables
private String name;
private String designation;
private String empid;
private double salaryid;
// Method to read employee information
public void read() {
Scanner scanner = new Scanner([Link]);
[Link]("Enter Employee Name: ");
[Link] = [Link]();
[Link]("Enter Designation: ");
[Link] = [Link]();
[Link]("Enter Employee ID: ");
[Link] = [Link]();
[Link]("Enter Salary ID: ");
[Link] = [Link]();
[Link](); // Consume the newline character
}
// Method to write employee information
public void write() {
[Link]("Employee Name: %s%n", name);
[Link]("Designation: %s%n", designation);
[Link]("Employee ID: %s%n", empid);
[Link]("Salary ID: %.2f%n", salaryid);
}
}
public class Main {
public static void main(String[] args) {
Employee[] employees = new Employee[5]; // Array to hold 5 employees
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
// Read information for 5 employees
for (int i = 0; i < 5; i++) {
[Link]("Enter details for Employee " + (i + 1) + ":");
employees[i] = new Employee();
employees[i].read();
}
// Write the information of all employees
[Link]("\nEmployee Information:");
for (int i = 0; i < 5; i++) {
[Link]("\nDetails of Employee " + (i + 1) + ":");
employees[i].write();
}
}
}
Output:
Enter details for Employee 1:
Enter Employee Name: Alice
Enter Designation: Software Engineer
Enter Employee ID: E001
Enter Salary : 75000
Enter details for Employee: 2
Enter Employee Name: Bob
Enter Designation: Project Manager
Enter Employee ID: E002
Enter Salary : 90000
Employee Information:
Details of Employee 1:
Employee Name: Alice
Designation: Software Engineer
Employee ID: E001
Salary : 75000.00
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Details of Employee 2:
Employee Name: Bob
Designation: Project Manager
Employee ID: E002
Salary : 90000.00
Write a java program to sort the elements using form loop
import [Link];
public class SortArray {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt user for the number of elements
[Link]("Enter the number of elements: ");
int n = [Link]();
// Create an array to hold the elements
int[] array = new int[n];
// Read the elements from the user
[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
array[i] = [Link]();
}
// Sort the array using Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (array[j] > array[j + 1]) {
// Swap array[j] and array[j + 1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
// Display the sorted array
[Link]("Sorted array:");
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
for (int i = 0; i < n; i++) {
[Link](array[i] + " ");
}
}
}
Output:
Enter the number of elements: 5Enter 5 elements:
34
12
5
78
23
Sorted array:
5 12 23 34 78
Write a recursive program to find the n th fibonacci number
import [Link];
public class Fibonacci {
// Recursive method to find the nth Fibonacci number
public static int fibonacci(int n) {
if (n <= 1) {
return n; // Base case: fib(0) = 0, fib(1) = 1
}
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt user for the value of n
[Link]("Enter a positive integer n to find the nth Fibonacci number: ");
int n = [Link]();
if (n < 0) {
[Link]("Please enter a non-negative integer.");
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
else {
int result = fibonacci(n);
[Link]("The n th Fibonacci number is: "+ result);
}
}
Output:
Enter a positive integer n to find the nth Fibonacci number: 6
The 6th Fibonacci number is: 8
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Module 2
Class, objects, Methods & Constructors
Class is a template/blueprint for an object, and an object is an instance of a class.
When you define a class, declare its exact form and nature.
A class is declared by use of Class keyword.
Syntax:
<Access_Specifiers> Class <class_name>{type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}}
Declaring an object:
when you create a class, you are creating a new data type. You can use this type to declare objects of that
type.
First, you must declare a variable of the class type. This variable does not define anobject. Instead, it is
simply a variable that can refer to an object.
Second, you must acquire an actual, physical copy of the object and assign it to that variable
The new operator dynamically allocates (that is, allocates at run time) memory for anobject and returns a
reference to it.
In the preceding sample programs, a line similar to the following is used to declare anobject of type Box:
Box mybox = new Box();
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
This statement combines the two steps just described. It can be rewritten like this toshow each step more
clearly:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
A closer view at new:
As just explained, the new operator dynamically allocates memory for an object. It has this general form:
class-var = new class_name ( );
Assigning Object Reference Variables
Object reference variables act differently than you might expect when an assignment takesplace. For
example, what do you think the following fragment does?
Box b1 = new Box();
Box b2 = b1;
Although b1 and b2 both refer to the same object, they are not linked in any other way
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Constructors
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e, providesdata for the
object that is why it is known as constructor.
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1 Default constructor (no-arg constructor)
2. Parameterized constructor
java Default Constructor
A constructor that have no parameter is known as default constructor
Syntax of default constructor:
1. <class name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked atthe time of
object creation.
class Bikel {Bikel(){
[Link]("Bike is created");
}
public static void main(String args[]){Bikel b=new Bikel();
}}
Output: Bike is created
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. Wecan have
any number of parameters in the constructor
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
void display(){
[Link](id+" "+name);
}
public static void main(String args[]) {
Student4 s1=new Student4(111,"Karan");
Student4 s2 new Student4(222,"Aryan");
[Link]();
[Link]();
}}
Output: 111 Karan
222 Aryan
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists. The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id=i;
name = n;}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){
[Link](id+" "+name+" "+age);
}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Student5 s2 = new Student5(222, "Aryan", 25);
[Link]();
[Link]();
}}
Output: 111 Karan 0
222 Aryan 25
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to another likecopy
constructor in C++
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another using javaconstructor
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name=n;
}
Student6(Student6 s){
id=[Link]:
name=[Link];
void display(){
[Link](id+" "+name);
}
public static void main(String args[]) {
Student6 s1=new Student6(111,"Karan");
Student6 s2= new Student6(s1);
[Link]();
[Link]();
}}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Output: 111 Karan
111 Karan
Java-Methods
A Java method is a collection of statements that are grouped together to perform an [Link] you
call the [Link]() method, for example, the system actually executes several statements in
order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke amethod
with or without parameters, and apply method abstraction in the program design.
Creating Method
Considering the following example to explain the syntax of a method -
Syntax
public static int methodName(int a, int b) {
// body
}
Here,
public static - modifier
int - return type
methodName - name of the method
a, b - formal parameters
int a, int b - list of parameters
Method definition consists of a method header and a method body. The same is shown in thefollowing
syntax
Syntax
<Access modifier> <returnType> <nameOfMethod>(Parameter List) {
// method body
}
The syntax shown above includes -
modifier - It defines the access type of the method and it is optional to use.
returnType - Method may return a value.
nameOfMethod -This is the method name. The method signature consists of themethod name and
the parameter list.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Parameter List - The list of parameters, it is the type, order, and number of parametersof a method. These
are optional, method may contain zero parameters.
method body - The method body defines what the method does with the statement.
Method returning a Value
In Java, a method can return a value to the caller. This allows you to perform calculations oroperations
within a method and provide the result back to the part of the program that invoked the method. Here's a
breakdown of how this works, along with examples.
Key Concept
Return Type: The method declaration specifies the type of value that it returns. Thiscould be any valid
data type, including primitive types (like int, double, etc.) or reference types (like String, Object, etc.).
Return Statement: The return statement is used to specify the value that will be returned from the
method. The value must match the method's declared return type.
Method Invocation: When you call a method that returns a value, you can assign the result to a variable
or use it directly in expressions.
Example of method returning a value
public class Calculator {
int a=25,b=75;
// Method that returns the sum of two integers
public int add() //Method with Zero Parameters
{
return a + b; // Return the sum
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
// Call the add method and store the result
int sum = [Link]();
// Display the result
[Link]("The sum is: " + sum);
}
}
Output: The sum is: 100
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Adding a method that take parameters
While some methods don’t need parameters, most do.
a parameterized method can operate on a variety of data and/or be used in a number ofslightly different
situations.
Here is a method that returns the square of the number 10:
int square() {
return 10 * 10;
}
While this method does, indeed, return the value of 10 squared, its use is very limited.
int square(int i) {
return i * i;
}
Now, square( ) will return the square of whatever value it is called with.
That is, square( ) is now a general-purpose method that can compute the square of anyinteger value,
rather than just 10. Here is an example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81y = 2;
x = square(y); // x equals 4
public class MathOperations {
// Method that takes two integers as parameters and returns their sum
public int add(int a, int b) {
return a + b; // Return the sum of a and b
}
// Method that takes two double values and returns their product
public double multiply(double x, double y) {
return x * y; // Return the product of x and y
}
public static void main(String[] args) {
MathOperations operations = new MathOperations();
// Call the add method and store the result
int sum = [Link](5, 10);
[Link]("Sum: " + sum);
//Call the multiply method and store the result
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
double product = [Link](3.5, 2.0);
[Link]("Product: " + product);
Output:
Sum: 15.0
Product 7.0
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known
as call by value. The changes being done in the called method, is not affected in the calling method
Example of call by value in java
In case of call by value original value is not changed. Let's take a simple example
Class Operation{
int data=50;
void change(int data){
data data+100; //changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System out println("before change "+[Link]);
[Link](500);
[Link]("after change "+op data);
Output:
before change 50after change 50
In Java, parameters are always passed by value.
For example, following program prints i=10,j=20.
// [Link]
class Test{
// swap() doesn't swap i and
public static void swap(Integer i, Integer j) {
Integer temp = new Integer(i);
i=j;
j = temp;
}
public static void main(String[] args) {
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Integer i= new Integer(10);
Integer = new Integer(20);
swap(i, j);
[Link](" i= "+ i +", j="+ j);
}}
Static Fields and Methods
The static keyword in java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of
the class.
The static can be:
variable (also known as class variable)
method (also known as class method)
block
nested class
Java static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is notunique for each
object) e.g. company name of employees, college name of students etc.
The static variable gets memory only once in class area at the time of class loading
Advantage of static variable
It makes your program memory efficient (Le it saves memory).
Understanding problem without static variable
class Student{
int rollno;
String name;
String college "ITS";
}
Example of static variable
//Program of static variableclass Student8{
int rollno;
String name;
static String college "ITS";Student8(int r,String n){ Rollno=r;
name=n;
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
}
void display (){
[Link](rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student8 sl=new Student8(111,"Karan");
Student8 s2=new Student8(222, "Aryan");
[Link](),
[Link]();
}}
Output: 111 Karan ITS
222 Aryan ITS
java static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a [Link] method
can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
Student9(int r, String n){
rollno = r.
name=n;
}
void display () {
[Link](rollno+" "+name+" "+college);
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
public static void main(String args[]){
[Link]();
Student9 sl=new Student9 (111,"Karan");
Student9 s2 new Student9 (222, "Aryan");
Student9 $3= new Student9 (333, "Sonoo");
[Link]();
[Link]();
[Link]();
}}
Output: 111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Java static block
Is used to initialize the static data member
It is executed before main method at the time of class loading.
Example of static block
class A2{
static {
[Link]("static block is invoked");
}
public static void main(String args[]){
[Link]("Hello main");
}
Output: static block is invoked
Hello main
Access Control
Access Modifiers in java
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method,constructor or
class
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
There are 4 types of java access modifiers:
private
default
protected
public
private access modifier
The private access modifier is accessible only within [Link] example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile time
error.
class A{
private int data=40;
private void msg(){
[Link]("Hello java");
}}
public class Simple{
public static void main(String args[]) {
A obj=new A();
[Link]([Link]); //Compile Time Error
[Link](); //Compile Time Error
}}
default access modifier
If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only
within package.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A classfrom
outside its package, since A class is not public, so it cannot be accessed from outside the
package
//save by A java
package pack;
class A{
void msg(){
[Link]("Hello");
}}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
//save by B. java
package mypack,import pack.*;
class B{
public static void main(String args[]){
A obj = new A(); //Compile Time Error
[Link](); //Compile Time Error
}}
In the above example, the scope of class A and its method msg() is default so it cannot beaccessed
from outside the package.
protected access modifier
The protected access modifier is accessible within package and outside the package but throughinheritance
only.
The protected access modifier can be applied on the data member, method and constructor. Itcan't be
applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance
//save by A java
package pack;
public class A{
protected void msg(){
[Link]("Hello");
}}
//save by B java
package mypack;import pack.":
class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}}
Output: Hello
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all othermodifiers.
Example of public access modifier
//save by A java package pack,
public class A{
public void msg() {
[Link]("Hello");
}}
//save by [Link]
package mypack;
import pack.*.
class B{
public static void main(String args[]){
A obj new A();
[Link]();
}}
Output: Hello
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
Outside
Access modifiers Within package package by Outsidepackage
Within class
subclass only
private Y N N N
default Y Y N N
protected Y Y Y N
public Y Y Y Y
Usage of java this keyword
Here is given the 6 usage of java this keyword
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call,
this can be used to return the current class instance from the method.
class Student{
int rollno;
String name;
float fee;
Student(int rollno, String name, float fee){
[Link]-rollno;
[Link] name;
this fee fee;
}
void display(){
[Link](rollno+" "+name+" "+fee);
}
class TestThis2{
public static void main(String args[]) {
Student sl=new Student(111,"ankit", 5000f);
Student s2=new Student(112,"sumit",6000f);
s1 display();
[Link]();
}}
Output:
ankit 5000
sumit 6000
Difference between constructor and method in java
There are many differences between constructors and methods. They are given below.
Constructor Method
Constructor is used to initialize the state of Method is used to expose behavior of an
an object. object.
Constructor must not have a return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
The java compiler provides Method is not provided by your compiler at
a defaultconstructor if any case.
you don’t have any
constructor.
Constructor name must be same as the class Method name may or may not be same.
name.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
Example of Constructor Overloading
class Students{
int id;
String = name;
int = age,
Students(int i, String n){
id = i;
name = n;
}
Student5(int i,String n, int a) {
id = i
name = n;age=a;
}
void display() ([Link](id+" "+name+" "+age);
}
public static void main(String args[]){
Students s1 new Student5(111, "Karan");
Student5s2 new Student5(222,"Aryan",25);
sl display();
[Link]();
}}
Output:
111 Karan 0
222 Aryan 25
Method Overloading in java
If a class has multiple methods having same name but different in parameters, it is known asMethod
Overloading.
If we have to perform only one operation, having same name of the methods increases thereadability
of the program.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method performs addition of twonumbers
and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance forcalling
methods.
class Adder{
static int add(int a, int b){
return a+b;
}
static int add(int a, int b,int c){
return a+b+c;
}}
class TestOverloading (){
public static void main(String[] args) {
[Link]([Link](11,11));
[Link]([Link](11,11,11)),
output:
22 33
Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add methodreceives
two integer arguments and second add method receives two double arguments
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in javathat calls
itself is called recursive method.
Java Recursion Example 1: Factorial Number
public class RecursionExample3{
static int factorial(int n){
if (n ==1)
return 1;
else
return(n *factorial(n-1));
}}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
public static void main(String[] args) {
[Link]("Factorial of 5 is: "+factorial(5));
}}
Output:
Factorial of 5 is: 120
java Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. Inother
words, it is a way to destroy the unused objects
To do so, we were using free() function in C language and delete() in C++. But, in java it isperformed
automatically. So, java provides better memory management.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced objectsfrom heap
memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to makeextra efforts.
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing Thegc() is
found in System and Runtime classes.
public static void gc(){}
Simple Example of garbage collection in java
public class TestGarbagel {
public void finalize() {
[Link]("object is garbage collected");
}
public static void main(String args[]){
TestGarbagel sl=new TestGarbage1();
TestGarbagel s2=new TestGarbagel();
sl=null;
s2=null;
[Link]();
}}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Output:
object is garbage collectedobject is garbage collected.
Java String
string is basically an object that represents sequence of char values. An array of characters works same
as java string. For example:
1. char[] ch=(‘j’,’a’,’v’,’a’,’a’,’t’,’p’,’o’,’i’,’n’,t);
2. String s=new String(ch);same as
String s="javatpoint";
Java String class provides a lot of methods to perform operations on string such as compare(),concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The [Link] class implements serializable, comparable and charSequence
interfaces.
Serializable Comparable CharSequence
Implements
String
CharSequence interface
The CharSequence interface is used to represent sequence of characters. It is implemented by String,
StringBuffer and StringBuilder classes. means, we can create string in java by using these 3 classes.
CharSequence
String StringBuffer StringBuilder
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
The java String is immutable i.e. it cannot be changed. Whenever we change any string, a newinstance is
created. For mutable string, you can use StringBuffer and StringBuilder classes.
There are two ways to create String object:
By string literal
By new keyword
String Literal
Java String literal is created by using double quotes.
For Example:
1. String s="welcome":
Each time you create a string literal, the JVM checks the string constant pool first. If the stringalready
exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
String sl="Welcome",
String s2="Welcome"; //will not create new instance
By new keyword
1. String s=new String("Welcome"); //creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap (non
pool).
Java String Example
public class StringExample {
public static void main(String args[]){
String s1="java"; //creating string by java string literal
char ch[]={‘s’,’t’,’r’,’i’,’n’,’g’,’s’};
String s2=new String(ch); //converting char array to string
String s3=new String("example"); //creating java string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}}
Output:
Java strings example
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable orunchangeable.
Once string object is created its data or state can't be changed but a new string object is [Link]'s try to
understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s=”Sachin";
[Link](" Tendulkar"); //concat() method appends the string at the end
[Link](s); //will print Sachin because strings are immutable
}}
Output:
Sachin
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
[Link](" Tendulkar");
[Link](s):
}}
Output:
Sachin Tendulkar
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Module 3
Inheritance, Abstract class and Interface
Inheritance in Java
Inheritance in Java is a fundamental concept of Object-Oriented Programming (OOP) that allows a class
(called the child class or subclass) to inherit the properties and behaviors (i.e., fields and methods) of
another class (called the parent class or superclass). This promotes code reuse and establishes a
relationship between the parent and child classes.
Key Concepts in Java Inheritance:
Parent Class (Superclass): The class whose properties and methods are inherited.
Child Class (Subclass): The class that inherits from the parent class and can add or override
functionality.
Method Overriding: A subclass can provide its own implementation of a method that is already defined
in the parent class.
Types of Inheritance in Java:
Single Inheritance:
A class inherits from only one superclass.
class Parent {
void speak() {
[Link]("Hello from Parent!");
}
}
class Child extends Parent {
void greet() {
[Link]("Hello from Child!");
}
}
public class Main {
public static void main(String[] args) {
Child childObj = new Child();
[Link](); // Inherited from Parent class
[Link](); // Defined in Child class
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Output:
Hello from Parent!
Hello from Child!
Creating a Multilevel Hierarchy:
Multilevel Inheritance:
A class inherits from a subclass, creating a chain of inheritance.
class Grandparent {
void wisdom() {
[Link]("Grandparent's wisdom.");
}
}
class Parent extends Grandparent {
void advice() {
[Link]("Parent's advice.");
}
}
class Child extends Parent {
void learning() {
[Link]("Child is learning.");
}
}
public class Main {
public static void main(String[] args) {
Child childObj = new Child();
[Link](); // Inherited from Grandparent
[Link](); // Inherited from Parent
[Link](); // Defined in Child
}
}
Output:
Grandparent's wisdom.
Parent's advice.
Child is learning.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Hierarchical Inheritance:
Multiple subclasses inherit from a single superclass.
class Animal {
void sound() {
[Link]("Animal makes a sound.");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog barks.");
}
}
class Cat extends Animal {
void meow() {
[Link]("Cat meows.");
}
}
public class Main {
public static void main(String[] args) {
Dog dogObj = new Dog();
[Link](); // Inherited from Animal
[Link](); // Defined in Dog
Cat catObj = new Cat();
[Link](); // Inherited from Animal
[Link](); // Defined in Cat
}
}
Output:
Animal makes a sound.
Dog barks.
Animal makes a sound.
Cat meows.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Member Access and Inheritance in Java
In Java, inheritance allows a subclass (child class) to inherit fields and methods from a superclass
(parent class). However, the accessibility of these inherited members (fields, methods) depends on their
access modifiers and whether they are overridden or not. The concept of member access is critical to
understand how members of a superclass are accessed or modified by subclasses or other classes.
1. Understanding Inheritance in Java
Inheritance enables a subclass to inherit both fields (attributes) and methods from its superclass.
Superclass: The class that is inherited from.
Subclass: The class that inherits from the superclass.
In Java, a class inherits all non-private fields and methods from its superclass, but the access to these
members is determined by their access modifiers (e.g., public, protected, private, or default).
Member Access in Inheritance:
Public Members:
Inherited by subclass and accessible from anywhere.
Protected Members:
Inherited by subclass and accessible within the same package or by subclass outside the package.
Default (Package-Private) Members:
Inherited by subclass but accessible only within the same package (not accessible from subclasses in
other packages).
Private Members:(Not inherited by subclasses)
private fields and methods of the superclass are not accessible in the subclass. However, they exist in the
memory of the subclass (you just cannot directly access them).
Example of Member Access in Inheritance:
Let's consider the following example to illustrate the concepts of member access and inheritance:
Example 1: Public, Protected, Default, and Private Members
class Parent {
public String publicField = "Public Field";
protected String protectedField = "Protected Field";
String defaultField = "Default Field"; // Package-private
private String privateField = "Private Field";
public void publicMethod() {
[Link]("Public Method in Parent");
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
protected void protectedMethod() {
[Link]("Protected Method in Parent");
}
void defaultMethod() {
[Link]("Default Method in Parent");
}
private void privateMethod() {
[Link]("Private Method in Parent");
}
}
class Child extends Parent {
public void displayFields() {
// Accessible from Child
[Link](publicField); // Accessible
[Link](protectedField); // Accessible
[Link](defaultField); // Accessible within the same package
// The following line will cause a compilation error because privateField is private to Parent
// [Link](privateField); // Not accessible
}
public void displayMethods() {
publicMethod(); // Accessible
protectedMethod(); // Accessible
defaultMethod(); // Accessible
// The following line will cause a compilation error because privateMethod is private to Parent
// privateMethod(); // Not accessible
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
[Link]();
[Link]();
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Output:
Public Field
Protected Field
Default Field
Public Method in Parent
Protected Method in Parent
Default Method in Parent
Usage of super in Java
In Java, super is a keyword used within a subclass to refer to its immediate superclass. It is commonly
used to call:
The constructor of the superclass
Methods of the superclass
Access superclass fields (variables)
The super keyword is essential when a subclass needs to interact with the parent class's methods,
constructors, or variables, particularly in the case of method overriding and constructor chaining.
Using super to Call the Superclass Constructor.
When a subclass constructor is called, the constructor of the superclass is called automatically, but you
can also explicitly call it using the super() keyword. This is especially useful when the superclass has a
parameterized constructor
Syntax:
super(); // Calls the superclass's no-argument constructor
super(arg1, arg2); // Calls the superclass's parameterized constructor
class Vehicle {
String color;
int speed;
// Constructor of Vehicle class
Vehicle(String color, int speed) {
[Link] = color;
[Link] = speed;
[Link]("Vehicle created with color: " + color + " and speed: " + speed);
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
class Car extends Vehicle {
String brand;
// Constructor of Car class
Car(String color, int speed, String brand) {
super(color, speed); // Calling the constructor of the Vehicle class
[Link] = brand;
[Link]("Car created with brand: " + brand);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Red", 150, "Toyota");
}
}
Output:
Vehicle created with color: Red and speed: 150
Car created with brand: Toyota
Dynamic Method Dispatch in Java:
Dynamic Method Dispatch (also known as Runtime Polymorphism or Late Binding) is a mechanism
in Java where a method call is resolved at runtime based on the object type (not the reference type) that
the method is invoked on. This is particularly important when you are dealing with method overriding in
inheritance and allows Java to determine which version of an overridden method should be called at
runtime.
Example of Dynamic Method Dispatch
Consider the scenario where you have a superclass called Animal and several subclasses like Dog, Cat,
etc. Each subclass overrides the sound() method. Now, you want to call the sound() method using a
reference of the superclass type Animal, but at runtime, Java will call the overridden method of the
actual object type (Dog, Cat, etc.) that the reference is pointing to.
// Superclass
class Animal {
// Method that will be overridden in subclasses
void sound() {
[Link]("Animal makes a sound");
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
}
}
// Subclass Dog
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
// Subclass Cat
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of Dog and Cat
Animal myAnimal = new Animal(); // Reference to Animal class
Animal myDog = new Dog(); // Reference to Dog class
Animal myCat = new Cat(); // Reference to Cat class
// Calling sound() on different references
[Link](); // Animal makes a sound
[Link](); // Dog barks
[Link](); // Cat meows
}
}
Output:
Animal makes a sound
Dog barks
Cat meows
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Explanation of Example:
Animal Class: The Animal class has a method sound() which is intended to be overridden by subclasses.
Dog and Cat Classes: Both Dog and Cat are subclasses of Animal. Each class overrides the sound()
method to provide its own implementation.
Dynamic Method Dispatch:
In the main method, we create objects of Dog and Cat, but the reference types are of class Animal.
Even though the reference type is Animal, the actual method that gets called is based on the actual
object type (Dog or Cat) at runtime.
Method Overriding in Java
Method overriding in Java is a feature that allows a subclass to provide its specific implementation of a
method that is already defined in its superclass. The overridden method in the subclass must have the
same signature (method name, return type, and parameter list) as the method in the superclass. This
allows the subclass to modify or extend the behaviour of the method defined in the superclass.
Key Points of Method Overriding:
Same Signature: The method in the subclass must have the same name, return type, and parameter list
as the method in the superclass.
Runtime Polymorphism: Method overriding is a key feature of runtime polymorphism (or dynamic
method dispatch), where the method to be executed is determined at runtime based on the object type.
The @Override Annotation: Although not required, it's good practice to use the @Override annotation
to indicate that a method is being overridden. It helps to catch errors if the method signature does not
exactly match the superclass method.
Example of Method Overriding
Let’s consider a simple example with a Shape superclass and its subclasses Circle and Rectangle. The
superclass defines a method draw(), and the subclasses override this method to provide their own
specific implementations.
// Superclass
class Shape {
// Method in superclass
void draw() {
[Link]("Drawing a shape");
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
// Subclass Circle
class Circle extends Shape {
// Overriding the draw() method
@Override
void draw() {
[Link]("Drawing a circle");
}
}
// Subclass Rectangle
class Rectangle extends Shape {
// Overriding the draw() method
@Override
void draw() {
[Link]("Drawing a rectangle");
}
}
public class Main {
public static void main(String[] args) {
// Creating objects of subclasses
Shape shape = new Shape();
Shape circle = new Circle();
Shape rectangle = new Rectangle();
// Calling the overridden methods
[Link](); // Output: Drawing a shape
[Link](); // Output: Drawing a circle
[Link](); // Output: Drawing a rectangle
}
}
Output:
Drawing a shape
Drawing a circle
Drawing a rectangle
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Abstract Class
An abstract class is a class that cannot be instantiated on its own. It is meant to be subclassed by other
classes. You can use abstract classes to provide common functionality for related classes and to define
methods that must be implemented in subclasses.
Key Points:
Abstract classes can have both abstract and concrete methods.
Abstract methods are methods that do not have a body (i.e., no implementation) and must be
implemented by subclasses.
Concrete methods are methods that have an implementation, and can be optionally overridden by
subclasses.
An abstract class can have instance variables, constructors, and non-abstract methods like a
regular class.
An abstract class cannot be instantiated directly (i.e., you can't create an object of an abstract class).
Abstract Method
An abstract method is a method that is declared without an implementation in an abstract class or
interface. Any class that inherits from the abstract class must provide an implementation for these
abstract methods, unless the subclass is also abstract.
Key Points:
Abstract methods have no body; only their signature (name, return type, and parameters) is provided.
Abstract methods must be implemented by any subclass of the abstract class, unless that subclass is
abstract as well.
Example:
// Abstract class for Vehicle
abstract class Vehicle {
// Concrete method (can be shared by all vehicles)
void startEngine() {
[Link]("Engine is starting...");
}
// Abstract method (to be implemented by subclasses)
abstract void drive();
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
// Concrete class for Car
class Car extends Vehicle {
// Implementing the abstract method
void drive() {
[Link]("The car is driving on the road.");
}
}
// Concrete class for Truck
class Truck extends Vehicle {
// Implementing the abstract method
void drive() {
[Link]("The truck is driving on the highway.");
}
}
// Concrete class for Bike
class Bike extends Vehicle {
// Implementing the abstract method
void drive() {
[Link]("The bike is riding on the path.");
}
}
public class Main {
public static void main(String[] args) {
// Polymorphism: Using the abstract class type for references
Vehicle car = new Car();
Vehicle truck = new Truck();
Vehicle bike = new Bike();
// Using shared method
[Link]();
[Link]();
[Link]();
// Using specific methods for each vehicle
[Link]();
[Link]();
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
[Link]();
}
}
Output:
Engine is starting...
Engine is starting...
Engine is starting...
The car is driving on the road.
The truck is driving on the highway.
The bike is riding on the path.
Using final with inheritance:
In Java, the final keyword is used to indicate that a class, method, or variable cannot be modified in
certain ways. Specifically, when used with inheritance, final has the following effects:
Final Class: A class declared as final cannot be sub classed (inherited).
Final Method: A method declared as final cannot be overridden in subclasses.
Final Variable: A variable declared as final cannot be reassigned after it is initialized.
Final class cannot be sub classed:
final class Vehicle {
void startEngine() {
[Link]("Vehicle engine started.");
}
}
// This will cause a compile-time error because Vehicle is final
// class Car extends Vehicle {
// void honk() {
// [Link]("Car horn honked.");
// }
// }
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
[Link]();
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Local Variable Type Inference in Java (with var)
Local variable type inference, introduced in Java 10 with the var keyword, allows you to declare
variables without explicitly specifying their type. Instead, the type is inferred by the compiler based on
the initializer (the value assigned to the variable).
Rules for Using var:
Only for Local Variables: The var keyword is only allowed for local variables (variables inside
methods, constructors, or blocks of code). It cannot be used for fields or method parameters.
Must be Initialized: When you use var, the variable must be initialized with a value because the type is
inferred from that value.
Cannot Change the Type: Once the type of a variable is inferred, it is fixed and cannot be changed. For
example, you cannot reassign a variable declared with var to a different type.
public class Main {
public static void main(String[] args) {
var name = "Alice"; // String type is inferred
var age = 25; // int type is inferred
var pi = 3.14; // double type is inferred
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Pi: " + pi);
}
}
What Happens Behind the Scenes?
When you write var name = "Alice";, Java’s compiler infers that name is of type String because the
initializer ("Alice") is a string literal. Similarly, for age, the compiler infers that it’s an int because the
initializer is an integer.
The Object Class in Java
The Object class is the root class of the Java class hierarchy. Every class in Java inherits, either directly
or indirectly, from the Object class. If you do not explicitly extend a class, it implicitly extends Object.
This class is defined in [Link] package, which is automatically imported in every Java program. The
Object class provides a set of methods that are available to every Java object, regardless of the class from
which it is derived.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Common Methods in the Object Class
The Object class provides several methods that can be used by any object in Java. These methods are
fundamental to the behavior of all Java objects.
Here is a list of some important methods from the Object class:
Method name Description
Object clone() Creates a new object that is the same as the object being cloned
boolean equals(Object obj) Determines whether one object is equal to another
Class<?> getClass( ) Obtains the class of an object at run time.
Int hashCode() Returns the hash code associated with the invoking object.
String toString() Returns a string that describes the object
Void finalize() Called before an unused object is recycled.
Causes the current thread to wait until another thread invokes notify()
Void wait()
or notifyAll() on the object.
Causes the current thread to wait for the specified amount of time (in
Void wait(long)
milliseconds) until it is awakened.
Causes the current thread to wait for the specified amount of time (in
Void wait(long, int)
milliseconds) until it is awakened.
Void notify() Wakes up a single thread that is waiting on the object's monitor.
Void notifyAll() Wakes up all threads that are waiting on the object's monitor.
Interface:
In Java, interfaces are used to define a contract that classes can implement. Interfaces specify a set of
methods that the implementing classes must provide. They allow for abstraction and help achieve loose
coupling in the design of your application. Below is an explanation of how to declare interfaces,
implement them, and access implementations through interface references.
Declaring an Interface 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 cannot have
instance variables or concrete methods (except default or static methods).
Syntax to declare an interface:
interface InterfaceName {
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
// Abstract method (no body)
returnType methodName(parameterList);
// Default method (with body)
default returnType defaultMethodName() {
// method body
}
// Static method (with body)
static returnType staticMethodName() {
// method body
}
}
Example:
// Declaring an interface
interface Animal {
// Abstract method (no body)
void makeSound();
// Default method
default void eat() {
[Link]("This animal eats food.");
}
// Static method
static void sleep() {
[Link]("This animal sleeps.");
}
}
Implementing an Interface in Java
To implement an interface in a class, you use the implements keyword. A class can implement multiple
interfaces.
Syntax to implement an interface:
class ClassName implements InterfaceName {
// Providing the implementation of abstract methods
@Override
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
public void methodName() {
// method implementation
}
}
// Implementing the Animal interface
class Dog implements Animal {
// Implementing the makeSound() method from Animal interface
@Override
public void makeSound() {
[Link]("Bark!");
}
// Dog class inherits the default method 'eat' from Animal interface
}
class Main {
public static void main(String[] args) {
// Creating an object of Dog class
Dog dog = new Dog();
[Link](); // Outputs: Bark!
[Link](); // Outputs: This animal eats food.
}
}
Accessing Implementations Through Interface References
In Java, you can refer to an object using an interface reference, even though the object is an instance of a
class that implements the interface. This allows you to use polymorphism where you refer to an object
by its interface type rather than its class type.
Syntax:
InterfaceName obj = new ClassName();
Example:
// Interface
interface Animal {
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
void makeSound();
default void eat() {
[Link]("This animal eats food.");
}
}
// Implementing the Animal interface
class Dog implements Animal {
@Override
public void makeSound() {
[Link]("Bark!");
}
}
// Implementing the Animal interface
class Cat implements Animal {
@Override
public void makeSound() {
[Link]("Meow!");
}
}
public class Main {
public static void main(String[] args) {
// Using Interface references to refer to different objects
Animal myDog = new Dog();
Animal myCat = new Cat();
// Calling the makeSound() method
[Link](); // Outputs: Bark!
[Link](); // Outputs: Meow!
// Calling the inherited default method
[Link](); // Outputs: This animal eats food.
[Link](); // Outputs: This animal eats food.
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Nested interface:
In Java, nested interfaces are interfaces that are defined inside another class or interface. Like nested
classes, nested interfaces allow you to logically group interfaces that are only used within the context of
a particular class or interface.
Nested interfaces can be either static or non-static. However, in most cases, nested interfaces are static,
because they can be accessed without needing an instance of the enclosing class. This is similar to how
static methods work.
// A nested interface example.
// This class contains a member interface.
class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements [Link] {
public boolean isNotNegative(int x) {
return x < 0 ? false: true;
}
}
class NestedIFDemo {
public static void main(String args[]) {
// use a nested interface reference
[Link] nif = new B();
if([Link](10))
[Link]("10 is not negative");
if([Link](-12))
[Link]("this won't be displayed");
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Interface can be extended:
In Java, interfaces can be extended in a manner similar to how classes are extended. When one interface
extends another, it inherits all the abstract methods of the parent interface. This allows you to create
more specific, hierarchical structures of interfaces. A class that implements the child interface must
provide implementations for all abstract methods declared in both the child and parent interfaces.
Interface A{
Void meth1();
Void meth2();
}
//Interface to interface inheritance via “extends”
Interface B extends A{
Void meth3();
}
Class C implements B{
@Override
Public void meth1(){
[Link](“Executing meth1”);
}
@Override
Public void meth2(){
[Link](“Executing meth2”);
}
@Override
Public void meth3(){
[Link](“Executing meth3”);
}
Class InterfaceDemo{
Public static void main(String args[]){
C c=new C();
c.meth1();
c.meth2();
c.meth3();
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Output:
Executing Meth1
Executing Meth2
Executing Meth3
Default interface methods
In Java, default methods in interfaces were introduced in Java 8. These allow developers to add new
methods to interfaces without breaking the existing implementations of classes that implement the
interface.
Key Features:
Definition: A default method is a method in an interface with a default implementation.
Purpose:
To provide backward compatibility when new methods are added to an interface.
To reduce the need for utility/helper classes.
public interface InterfaceName {
default void methodName() {
// Default implementation
}
}
Classes implementing the interface can:
Use the default implementation.
Override the default method.
Example 1: Basic Usage of Default Methods
interface MyInterface {
void abstractMethod(); // Abstract method
default void defaultMethod() {
[Link]("This is the default implementation of the method.");
}
}
public class DefaultMethodExample implements MyInterface {
public void abstractMethod() {
[Link]("Implementation of the abstract method.");
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
public static void main(String[] args) {
DefaultMethodExample obj = new DefaultMethodExample();
[Link](); // Output: Implementation of the abstract method.
[Link](); // Output: This is the default implementation of the method.
}
}
Example 2: Overriding Default Methods in Implementing Class
interface MyInterface {
default void defaultMethod() {
[Link]("Default implementation in the interface.");
}
}
public class OverrideDefaultMethodExample implements MyInterface {
@Override
public void defaultMethod() {
[Link]("Overridden implementation in the class.");
}
public static void main(String[] args) {
OverrideDefaultMethodExample obj = new OverrideDefaultMethodExample();
[Link](); // Output: Overridden implementation in the class.
}
}
Private interface methods
In Java, private methods in interfaces were introduced in Java 9. They allow interfaces to encapsulate
code by defining private methods that can be reused within other default or static methods of the
interface.
Key Features of Private Methods in Interfaces:
Purpose:
To avoid code duplication in default or static methods of the interface.
To improve code organization within the interface.
Scope:
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Private methods: Accessible only within the interface.
Private static methods: Accessible only within the interface's static context.
Access Modifiers:A private method cannot be accessed by implementing classes or outside the interface.
Syntax:
Private Instance Method:
private void methodName() {
// Implementation
}
Private static method:
private static void methodName() {
// Implementation
}
Example 1: using a private method
interface MyInterface {
// Default method
default void defaultMethod1() {
[Link]("Default Method 1");
commonMethod();
}
// Another default method
default void defaultMethod2() {
[Link]("Default Method 2");
commonMethod();
}
// Private method to avoid duplication
private void commonMethod() {
[Link]("This is a common operation.");
}
}
public class PrivateMethodExample implements MyInterface {
public static void main(String[] args) {
PrivateMethodExample obj = new PrivateMethodExample();
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
obj.defaultMethod1();
obj.defaultMethod2();
}
}
Output:
Default Method 1
This is a common operation.
Default Method 2
This is a common operation.
Example 2: Using a Private Static Method
interface MyInterface {
static void staticMethod1() {
[Link]("Static Method 1");
helperMethod();
}
static void staticMethod2() {
[Link]("Static Method 2");
helperMethod();
}
// Private static method
private static void helperMethod() {
[Link]("This is a helper method for static methods.");
}
}
public class PrivateStaticMethodExample {
public static void main(String[] args) {
MyInterface.staticMethod1();
MyInterface.staticMethod2();
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Output:
Static Method 1
This is a helper method for static methods.
Static Method 2
This is a helper method for static methods.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Module 4
Packages, Exceptional handling
Packages:
In Java, packages are used to group related classes and interfaces together. A package helps in
organizing the code, avoiding name conflicts, and providing access control. Think of a package as a
folder in which related files (classes or interfaces) are stored.
Key Benefits of Using Packages:
Organizing Code: Group related classes into packages to keep your project structured.
Name Collision Avoidance: Two classes with the same name can exist in different packages.
Access Control: Packages help control access to classes, methods, and variables using access modifiers
like public, protected, and private.
Reusability: Packages make it easier to reuse code because you can import classes from other packages.
Types of Packages in Java:
Built-in Packages: Java provides several built-in packages like [Link]/[Link], [Link],
etc.
User-defined Packages: You can create your own packages to organize your classes.
How to Create and Use Packages
1. Creating a Package:
To create a package, you use the package keyword at the top of your Java file, followed by the
package name. This is the general form of the package statement:
package pkg_Name;
A Short Package Example:
Keeping the preceding discussion in mind, you can try this simple package: // A simple package package
MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal < 0)
[Link]("--> ");
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
[Link](name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i = 0; i < 3; i++)
current[i].show();
}
}
Access Protection:
In Java, access protection refers to the mechanism that determines how and where variables, methods,
and classes can be accessed. Java provides a set of access modifiers that control the visibility of class
members (fields, methods, constructors, etc.) within and across different classes and packages.
There are four access modifiers in Java, each defining a different level of visibility:
1. public
2. protected
3. default (no modifier)
4. private
Here is a table summarizing the access levels for each access modifier (private, default/no modifier,
protected, and public) in various scenarios:
private default protected public
Same class Yes Yes Yes Yes
Same package sub class No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package Non-subclass No No No Yes
An Access Example:
The following example shows all combinations of the access control modifiers. This example has two
packages and five classes. Remember that the classes for the two different packages need to be stored in
directories named after their respective packages—in this case, p1 and p2.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
The source for the first package defines three classes: Protection, Derived, and SamePackage. The first
class defines four int variables in each of the legal protection modes. The variable n is declared with the
default protection, n_pri is private, n_pro is protected, and n_pub is public.
Each subsequent class in this example will try to access the variables in an instance of this class. The
lines that will not compile due to access restrictions are commented out. Before each of these lines is a
comment listing the places from which this level of protection would allow access.
The second class, Derived, is a subclass of Protection in the same package, p1. This grants Derived
access to every variable in Protection except for n_pri, the private one. The third class, SamePackage, is
not a subclass of Protection, but is in the same package and also has access to all but n_pri. This is file
[Link]:
package p1;
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection() {
[Link]("base constructor");
[Link]("n = " + n);
[Link]("n_pri = " + n_pri);
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
}
}
This is file [Link]:
package p1;
class Derived extends Protection {
Derived() {
[Link]("derived constructor");
[Link]("n = " + n);
// class only
// [Link]("n_pri = "4 + n_pri);
[Link]("n_pro = " + n_pro);
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
[Link]("n_pub = " + n_pub);
}
}
This is file [Link]:
package p1;
class SamePackage {
SamePackage() {
Protection p = new Protection();
[Link]("same package constructor");
[Link]("n = " + p.n);
// class only
// [Link]("n_pri = " + p.n_pri);
[Link]("n_pro = " + p.n_pro);
[Link]("n_pub = " + p.n_pub);
}
}
Following is the source code for the other package, p2. The two classes defined in p2 cover the other two
conditions that are affected by access control. The first class, Protection2, is a subclass of [Link].
This grants access to all of [Link]’s variables except for n_pri (because it is private) and n, the
variable declared with the default protection. Remember, the default only allows access from within the
class or the package, not extrapackage subclasses. Finally, the class OtherPackage has access to only one
variable, n_pub, which was declared public. This is file [Link]
package p2;
class Protection2 extends [Link] {
Protection2() {
[Link]("derived other package constructor");
// class or package only
// [Link]("n = " + n);
// class only
// [Link]("n_pri = " + n_pri);
[Link]("n_pro = " + n_pro);
[Link]("n_pub = " + n_pub);
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
}
}
This is file [Link]:
package p2;
class OtherPackage {
OtherPackage() {
[Link] p = new [Link]();
[Link]("other package constructor");
// class or package only
// [Link]("n = " + p.n);
// class only
// [Link]("n_pri = " + p.n_pri);
// class, subclass or package only
// [Link]("n_pro = " + p.n_pro);
[Link]("n_pub = " + p.n_pub);
}
}
If you want to try these two packages, here are two test files you can use. The one for package p1 is
shown here:
// Demo package p1.
package p1;
// Instantiate the various classes in p1.
public class Demo {
public static void main(String args[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}}
The test file for p2 is shown next:
// Demo package p2.
package p2;
// Instantiate the various classes in p2.
public class Demo {
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
public static void main(String args[]) {
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
Importing packages:
In Java, importing packages allows you to include pre-defined classes and methods from Java libraries
or user-defined packages into your program. This helps avoid the need to rewrite code and provides
access to extensive functionality.
Key Points:
Packages are collections of related classes and interfaces.
You can import specific classes or an entire package.
Syntax for importing:
To import a specific class:
import [Link];
To import all classes in a package:
import packageName.*;
package MyPack;
/* Now, the Balance class, its constructor, and its show() method are public. This means that they can be
used by non-subclass code outside their package. */
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b; }
public void show() {
if(bal<0)
[Link]("--> ");
[Link](name + ": $" + bal);
}
}
As you can see, the Balance class is now public. Also, its constructor and its show( )
method are public, too. This means that they can be accessed by any type of code outside
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
the MyPack package. For example, here TestBalance imports MyPack and is then able to
make use of the Balance class:
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
[Link](); // you may also call show()
}
}
As an experiment, remove the public specifier from the Balance class and then try
compiling TestBalance. As explained, errors will result.
Exception Handling
Exception: An exception is an unwanted or unexpected event that disrupts the normal flow of a
program.
Exception Handling in Java is a mechanism used to handle runtime errors, ensuring that the normal flow
of the application is maintained.
Instead of terminating the program abruptly when an error occurs, Java allows the program to catch and
handle exceptions, making it robust and error-resistant.
It provides a structured way to manage these errors using specific keywords like try, catch, finally,
throw and throws.
Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute, whether an exception occurred or not
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Exception Hierarchy:
Key Concepts in Exception Handling:
Exception: An event that disrupts the normal flow of a program during runtime.
Checked Exceptions: Must be handled at compile-time (e.g., IOException, SQLException).
Unchecked Exceptions: Occur at runtime and do not require explicit handling (e.g.,
ArithmeticException, NullPointerException).
Errors: Indicate serious problems (e.g., OutOfMemoryError).
Exception Handling Keywords:
try: Defines a block of code to test for exceptions.
catch: Handles the exception if one occurs.
finally: Defines a block of code that executes regardless of whether an exception occurs.
throw: Used to explicitly throw an exception.
throws: Declares exceptions a method might throw.
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the
exception class hierarchy. Immediately below Throwable are two subclasses that partition exceptions
into two distinct branches. One branch is headed by Exception. This class is used for exceptional
conditions that user programs should catch. This is also the class that you will subclass to create your
own custom exception types. There is an important subclass of Exception, called RuntimeException.
Exceptions of this type are automatically defined for the programs that you write and include things such
as division by zero and invalid array indexing.
The other branch is topped by Error, which defines exceptions that are not expected to be caught under
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
normal circumstances by your program. Exceptions of type Error are used by the Java run-time system to
indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such
an error. This chapter will not be dealing with exceptions of type Error, because these are typically
created in response to catastrophic failures that cannot usually be handled by your program.
Uncaught Exception:
An uncaught exception in Java occurs when an exception is thrown during program execution but is not
handled by a try-catch block. When this happens, the Java Virtual Machine (JVM) halts the
program and prints an error message, including the type of exception, the cause, and a stack trace
showing where the exception occurred.
Example of Uncaught Exception
Public class UncaughtExceptionExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 0;
// This will throw ArithmeticException, which is not handled
int result = num1 / num2;
[Link]("Result: " + result); // This line will not execute
}
}
Output:
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
Using try and catch
The try and catch block in Java is used for handling exceptions. Code that might throw an exception
is placed inside the try block, and the catch block is used to handle the exception if it occurs. This
ensures that the program does not crash and can recover gracefully.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
try block: Contains code that might throw an exception.
catch block: Handles the exception. It specifies the type of exception it can catch.
Exception parameter (e): Provides details about the exception.
Example 1: Basic Usage of try-catch
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
}
}
Output:
Error: Division by zero is not allowed.
Multiple catch Clause
In Java, a multiple catch clause allows handling different types of exceptions that may occur in a
single try block. Each catch block can handle a specific type of exception. This mechanism ensures
that the program does not terminate abruptly when an exception occurs and allows appropriate handling
based on the exception type.
Key Points:
Order of catch Blocks: More specific exceptions must come before more general ones (e.g.,
ArithmeticException before Exception), as Java checks them in sequence.
Only One catch Block Executes: When an exception occurs, only the first matching catch block
executes, and the remaining ones are ignored.
Multiple Exceptions in One catch: From Java 7 onward, you can handle multiple exceptions in a
single catch block using the | operator.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Syntax:
try {
// Code that may throw multiple exceptions
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} catch (Exception e) {
// Handle other exceptions (optional)
}
Example 1: Handling Multiple Exceptions with Separate catch Blocks
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 10; // Throws ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Out of Bounds Exception occurred.");
} catch (Exception e) {
[Link]("Some other exception occurred: " + e);
}
}
}
Output:
Array Index Out of Bounds Exception occurred.
Example 2: Handling Multiple Exceptions in a Single catch Block
From Java 7 onwards, you can use the | operator to handle multiple exceptions in a single catch block.
public class MultiCatchExample {
public static void main(String[] args) {
try {
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
int[] arr = new int[3];
arr[5] = 10; // Throws ArrayIndexOutOfBoundsException
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
[Link]("Exception occurred: " + e);
}
}
}
Output:
Exception occurred: [Link]: Index 5 out of bounds for length 3
Nested try Statements:
In Java, you can nest try statements within each other. This means that you can have a try block inside another
try block, each potentially with its own catch and finally [Link] try blocks can be useful when you
want to handle specific exceptions in different parts of your code with different handling logic.
The outer try block handles exceptions from a larger portion of the code, while the inner try blocks are used for
more specific parts that might throw [Link]’s an example of how you can use nested try-catch blocks
in Java:
Example: Nested try-catch blocks
// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = [Link];
/* If no command-line args are present, the following statement will generate a divide-by-zero
exception. */
int b = 42 / a;
[Link]("a = " + a);
try {
// nested try block
/* If one command-line arg is used, then a divide-by-zero exception will be generated by the following
code. */
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
if(a==1)
a = a/(a-a); // division by zero
/* If two command-line args are used, then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}}
catch(ArrayIndexOutOfBoundsException e) {
[Link]("Array index out-of-bounds: " + e);
}}
catch(ArithmeticException e) {
[Link]("Divide by 0: " + e);
}}}
Output:
C:\>java NestTry
Divide by 0: [Link]: / by zero
C:\>java NestTry One
a = 1 Divide by 0: [Link]: / by zero
C:\>java NestTry One Two
a = 2 Array index out-of-bounds: [Link]
throw
In Java, the throw keyword is used to explicitly throw an exception from a method or block of code.
When you use throw, you're essentially telling the Java runtime to interrupt the normal flow of
execution and pass control to an appropriate catch block (if one exists), or terminate the program if no
handler is found.
Syntax of throw:
throw new ExceptionType("Error message");
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
How throw works:
1. Explicit Exception: When you use throw, you manually create an exception object and throw it.
2. Exception Propagation: Once the exception is thrown, the current method’s execution is
stopped, and control is passed up the call stack to find a matching catch block (if any). If no catch
block is found, the program terminates and the exception is printed to the console (unless you
handle it somewhere higher in the call stack).
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
}
catch(NullPointerException e) {
[Link]("Caught inside demoproc.");
throw e; // rethrow the exception
}}
public static void main(String args[]) {
try {
demoproc();
}
catch(NullPointerException e) {
[Link]("Recaught: " + e);
}}}
This program gets two chances to deal with the same error. First, main( ) sets up an exception context
and then calls demoproc( ). The demoproc( ) method then sets up another exceptionhandling context and
immediately throws a new instance of NullPointerException, which is caught on the next line. The
exception is then rethrown. Here is the resulting output:
Caught inside demoproc.
Recaught: [Link]: demo
The program also illustrates how to create one of Java’s standard exception objects. Pay close attention
to this line:
throw new NullPointerException("demo");
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
In Java, the throws keyword is used in method declarations to indicate that a method might throw one or
more exceptions during its execution. By using throws, the method explicitly informs the caller that it
could encounter certain exceptions that must either be handled or further propagated.
Syntax of throws:
returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {
// method body
}
When to use throws:
Checked exceptions: The throws keyword is used when a method can throw a checked
exception (any exception that is a subclass of Exception but not RuntimeException). Checked
exceptions are exceptions that are checked at compile time, and the compiler forces you to either
handle them or declare them using throws.
Not for unchecked exceptions: You do not need to declare unchecked exceptions (subclasses
of RuntimeException, such as NullPointerException, ArrayIndexOutOfBoundsException) in the
throws clause, as they are not checked at compile time.
Example of using throws:
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}}
To make this example compile, you need to make two changes. First, you need to declare that throwOne( ) throws
IllegalAccessException. Second, main( ) must define a try/catch statement that catches this exception. The
corrected example is shown here: // This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
[Link]("Inside throwOne.");
throw new IllegalAccessException("demo");
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
[Link]("Caught " + e);
}}}
Here is the output generated by running this example program:
inside throwOne caught
[Link]: demo
finally:
In Java, the finally block is a part of exception handling that is used to execute a block of code regardless
of whether an exception is thrown or not. The finally block is primarily used for resource cleanup, such
as closing files, releasing locks, or closing database connections, to ensure that important cleanup code is
executed no matter what happens in the try block.
Syntax:
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
Example: Usage of finally block
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
[Link]("inside procA");
throw new RuntimeException("demo");
}
finally {
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
[Link]("procA's finally");
}}
// Return from within a try block.
static void procB() {
try {
[Link]("inside procB");
return; }
finally {
[Link]("procB's finally");
}}
// Execute a try block normally.
static void procC() {
try {
[Link]("inside procC");
}
finally {
[Link]("procC's finally");
}}
public static void main(String args[]) {
try {
procA();
}
catch (Exception e) {
[Link]("Exception caught");
}
procB();
procC();
}}
In this example, procA( ) prematurely breaks out of the try by throwing an exception. The finally clause
is executed on the way out. procB( )’s try statement is exited via a return statement. The finally clause is
executed before procB( ) returns. In procC( ), the try statement executes normally, without error.
However, the finally block is still executed.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
REMEMBER: If a finally block is associated with a try, the finally block will be executed upon
conclusion of the try.
Here is the output generated by the preceding program:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
Java’s Built-in Exceptions:
Inside the standard package [Link], Java defines several exception classes. A few have been used by the
preceding examples. The most general of these exceptions are subclasses of the standard type RuntimeException.
As previously explained, these exceptions need not be included in any method’s throws list. In the language of
Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or
throws these exceptions. The unchecked exceptions defined in [Link] are listed in Table 10-1. Table 10-2 lists
those exceptions defined by [Link] that must be included in a method’s throws list if that method can generate
one of these exceptions and does not handle it itself. These are called checked exceptions. Java defines several
other types of exceptions that relate to its various class libraries.
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string
TypeNotPresentException Type not found
UnsupportedOperationException An unsupported operation was encountered.
TABLE 10-1: Java’s Unchecked RuntimeException Subclasses Defined in [Link]
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the
Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or
interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
TABLE 10-2: Java’s Checked Exceptions Defined in [Link]
Creating Your Own Exception Subclasses
Although Java’s built-in exceptions handle most common errors, you will probably want to create your own
exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of
Exception (which is, of course, a subclass of Throwable). Your subclasses don’t need to actually implement
anything—it is their existence in the type system that allows you to use them as exceptions. The Exception class
does not define any methods of its own. It does, of course, inherit those methods provided by Throwable. Thus, all
exceptions, including those that you create, have the methods defined by Throwable available to them. They are
shown in Table 10-3
Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a completed
stack trace. This object can be rethrown.
Throwable getCause( ) Returns the exception that underlies the current
exception. If there is no underlying exception, null is
returned.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
String getLocalizedMessage( ) Returns a localized description of the exception.
String getMessage( ) Returns a description of the exception.
StackTraceElement[ ] getStackTrace( ) Returns an array that contains the stack trace, one
element at a time, as an array of StackTraceElement.
The method at the top of the stack is the last method
called before the exception was thrown. This method is
found in the first element of the array. The
StackTraceElement class gives your program access to
information about each element in the trace, such as its
method name
Throwable initCause(Throwable causeExc) Associates causeExc with the invoking exception as a
cause of the invoking exception. Returns a reference to
the exception.
void printStackTrace( ) Displays the stack trace.
void printStackTrace(PrintStream stream) Sends the stack trace to the specified stream.
void printStackTrace(PrintWriter stream) Sends the stack trace to the specified stream.
void setStackTrace(StackTraceElement elements[ ]) Sets the stack trace to the elements passed in elements.
This method is for specialized applications, not normal
use.
String toString( ) Returns a String object containing a description of the
exception. This method is called by println( ) when
outputting a Throwable object.
Example: creates a custom exception type.
// This program creates a custom exception type.
class MyException extends Exception {
private int detail; MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}}
class ExceptionDemo {
static void compute(int a) throws MyException {
[Link]("Called compute(" + a + ")");
if(a > 10) throw new MyException(a);
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
[Link]("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
}
catch (MyException e) {
[Link]("Caught " + e);
}}}
Build a java program for a banking application to throw an exception where a person tries to
withdraw the amount even though he/she has lesser than minimum balance(create a custom
exception).
// Custom exception for insufficient balance
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
// Bank account class
class BankAccount {
private String accountHolderName;
private double balance;
private static final double MINIMUM_BALANCE = 500.0; // Minimum balance requirement
public BankAccount(String accountHolderName, double initialBalance) {
[Link] = accountHolderName;
[Link] = initialBalance;
}
// Method to withdraw money
public void withdraw(double amount) throws InsufficientBalanceException {
if (balance - amount < MINIMUM_BALANCE) {
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
throw new InsufficientBalanceException("Withdrawal denied! Balance cannot drop below the
minimum balance of " + MINIMUM_BALANCE);
}
balance -= amount;
[Link]("Withdrawal of " + amount + " successful. Remaining balance: " + balance);
}
// Method to deposit money
public void deposit(double amount) {
balance += amount;
[Link]("Deposit of " + amount + " successful. New balance: " + balance);
}
// Method to check balance
public double getBalance() {
return balance;
}
}
// Main class
public class BankingApplication {
public static void main(String[] args) {
BankAccount account = new BankAccount("John Doe", 1000.0);
[Link]("Initial balance: " + [Link]());
try {
[Link](600.0); // This will work
[Link](200.0); // This will throw the custom exception
} catch (InsufficientBalanceException e) {
[Link]("Exception: " + [Link]());
}
[Link](300.0); // Deposit some money
[Link]("Final balance: " + [Link]());
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Build a java program to create a package "balance" containing Account Class with
displayBalance() method and import this package in another program to access method of
Account class.
// Package "balance" containing Account class
package balance;
public class Account {
private String accountHolderName;
private double balance;
public Account(String accountHolderName, double initialBalance) {
[Link] = accountHolderName;
[Link] = initialBalance;
}
public void displayBalance() {
[Link]("Account Holder: " + accountHolderName);
[Link]("Current Balance: " + balance);
}
public void deposit(double amount) {
balance += amount;
[Link]("Deposit of " + amount + " successful. New balance: " + balance);
}
public void withdraw(double amount) {
if (amount > balance) {
[Link]("Insufficient funds for withdrawal of " + amount);
} else {
balance -= amount;
[Link]("Withdrawal of " + amount + " successful. Remaining balance: " + balance);
}
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
// Main class to use the balance package
import [Link];
public class MainApplication {
public static void main(String[] args) {
// Creating an Account object
Account myAccount = new Account("Alice", 2000.0);
// Displaying the balance
[Link]();
// Performing deposit and withdrawal operations
[Link](500.0);
[Link](1000.0);
[Link](3000.0);
// Final balance display
[Link]();
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Module 5
Multi-Threading programming, Auto-boxing, Enumerations
What is Multithreading?
• Multithreading is a programming concept where a program contains multiple parts (threads) that
can run concurrently.
(OR)
• Thread is a lightweight process that allows the program to execute multiple tasks concurrently.
• Each thread represents a separate path of execution within a program.
Multitasking vs. Multithreading:
Multitasking
• Allows multiple tasks to be performed simultaneously by sharing the computer's resources. The
CPU switches between different programs.
Multithreading
• Allows multiple threads of a task to be processed simultaneously by dividing a program into
threads. The CPU switches between threads within a single process.
Here are some other differences between multitasking and multithreading:
• Memory: In multitasking, each program has its own separate memory and resources. In
multithreading, a process has a single memory that is shared by all of its threads.
• Execution speed: Multithreading is faster than multitasking.
• Termination: Terminating a process in multithreading is faster than in multitasking.
• Responsiveness: Multithreading improves responsiveness because if one thread doesn't respond,
another thread can.
• Resource sharing: Multithreading allows threads to share the process's code and data.
There are two distinct types of multitasking:
Process-Based Multitasking: Involves running multiple independent programs. Each program (or
process) has its own memory space and execution context. For example, running a Java compiler and a
text editor simultaneously.
Thread-Based Multitasking: Involves multiple threads within a single program. Threads share the same
memory space, making inter-thread communication efficient. For example, a text editor formatting text
while printing.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Advantages of Multithreading:
• Efficient CPU Usage: Multithreading ensures the CPU is utilized even during I/O or idle times
(e.g., waiting for user input or network data).
• Lightweight: Threads require less overhead compared to processes. They share memory space
and resources, making context switching faster.
• Convenience in Java: Java has built-in support for multithreading, simplifying many details for
developers.
The java thread model:
• The Java Thread Model is a framework that allows Java programs to execute multiple tasks
simultaneously by dividing the tasks into manageable "threads." It is a core part of Java's runtime
system, designed to improve efficiency and responsiveness in applications.
Key Components of the Java Thread Model
Multithreading Basics:
• A thread is the smallest unit of execution in a program.
• Multithreading enables concurrent execution of multiple threads within a single program.
• Threads in Java run independently but share the same process memory space, making
inter-thread communication efficient.
Single-Threaded vs. Multithreaded Environments:
Single-Threaded Environment:
• Relies on an event loop with polling.
• A single thread handles all events and operations sequentially.
• If a thread blocks (e.g., waits for I/O), the entire program halts.
Java's Multithreaded Environment:
• Eliminates the event loop(use animation loops).
• Threads run independently, ensuring that one blocked thread doesn’t affect others.
• Enables responsive applications by utilizing idle CPU time effectively.
Threads exist in several states: A thread can be running. It can be ready to run as soon as it gets CPU
time. A running thread can be suspended, which temporarily suspends its activity. A suspended thread
can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a
resource. At any time, a thread can be terminated, which halts its execution immediately. Once
terminated, a thread cannot be resumed.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Thread Priority:
• Java assigns to each thread a priority that determines how that thread should be treated with
respect to the others.
• Thread priorities are integers that specify the relative priority of one thread to another.
• As an absolute value, a priority is meaningless; a higher-priority thread doesn’t run any faster
than a lower-priority thread if it is the only thread running.
• Instead, a thread’s priority is used to decide when to switch from one running thread to the next.
This is called a context switch.
• A thread can voluntarily relinquish control. This occurs when explicitly yielding, sleeping or
when blocked. In this scenario, all other threads are examined, and the highest-priority thread that
is ready to run is given the CPU.
• A thread can be preempted by a higher priority thread. In this case, a lower – priority thread that
does not yield the processor is simply preempted – no matter what it is doing – by a higher-
priority thread. Basically, as soon as a higher – priority thread wants to run, it does. This is called
preemptive multitasking.
Synchronization:
• For example, if you want two threads to communicate and share a complicated data structure,
such as linked list.
• That is, we must prevent one thread from writing data while another thread is in middle of
reading it.
• For this purpose, java implements an concept called “Synchronization”: the monitor.
• The monitor is a control mechanism, that a monitor as a very small box that can hold only one
thread.
• Once a thread enters a monitor, all other threads must wait until that thread exits the monitor.
• In this way a monitor can be used to protect a shared asset from being manipulated by more than
one thread at a time.
Messaging:
• Java’s messaging system allows a thread to enter a synchronized method on an object, and then
wait there until some other thread explicitly notifies it to come out.
• These methods need to communicate from thread to thread:
Wait(), notify(), and notifyAll()
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
The thread class and the runnable interface:
• Java’s multithreading system is built upon the thread class, it’s methods and it’s companion
interface runnable.
• To create a new thread, your program will either extend Thread or implement the runnable
interface.
Method Meaning
getName Obtain a thread’s name
getPriority Obtain a thread’s priority
isAlive Determine if a thread is still running
Join Wait for a thread to terminate
run Entry point for the thread
Sleep Suspend a thread for a period of time
Start Start a thread by calling its run method
The main thread:
• When a Java program starts up, one thread begins running immediately. This is usually called the
main thread of your program, because it is the one that is executed when your program begins.
• The main thread is important for two reasons:
1. It is the thread from which other “child” threads will be spawned.
2. Often, it must be the last thread to finish execution because it performs various shutdown actions.
Although the main thread is created automatically when your program is started, it can be controlled
through a Thread object. To do so, you must obtain a reference to it by calling the method
currentThread( ), which is a public static member of Thread. Its general form is shown here:
static Thread currentThread( )
This method returns a reference to the thread in which it is called. Once you have a reference to the main
thread, you can control it just like any other thread. Let’s begin by reviewing the following example:
// Controlling the main Thread.
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = [Link]();
[Link]("Current thread: " + t);
// change the name of the thread
[Link]("My Thread");
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
[Link]("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
[Link](n);
[Link](1000);
}}
catch (InterruptedException e) {
[Link]("Main thread interrupted");
}}}
• The sleep( ) method causes the thread from which it is called to suspend execution for the
specified period of milliseconds. Its general form is shown here:
static void sleep(long milliseconds) throws InterruptedException
• The number of milliseconds to suspend is specified in milliseconds. This method may throw an
InterruptedException.
• The sleep( ) method has a second form, shown next, which allows you to specify the period in
terms of milliseconds and nanoseconds:
static void sleep(long milliseconds, int nanoseconds) throws InterruptedException
• you can set the name of a thread by using setName( ). You can obtain the name of a thread by
calling getName( ) (but note that this is not shown in the program). These methods are members
of the Thread class and are declared like this:
final void setName(String threadName)
final String getName( )
Here, threadName specifies the name of the thread.
Ways to Create a Thread in Java:
1. Implementing the Runnable Interface:
Java supports only single inheritance, so if your class already extends another class, you can implement
the Runnable interface instead.
Thread(Runnable threadob, String threadName)
Steps:
• Create a class that implements the Runnable interface.
• Override the run() method.
• Pass an instance of your Runnable class to a Thread object.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
• Call the start() method of the Thread object.
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() { // Create a new, second thread
t = new Thread(this, "Demo Thread");
[Link]("Child thread: " + t);
[Link]();
// Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
[Link]("Child Thread: " + i);
[Link](500);
}}
catch (InterruptedException e) {
[Link]("Child interrupted.");
}
[Link]("Exiting child thread.");
}}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
[Link]("Main Thread: " + i);
[Link](1000);
}}
catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
[Link]("Main thread exiting.");
}}
2. Extending the Thread Class
This approach involves creating a subclass of the Thread class and overriding its run() method, which
contains the code the thread will execute.
Steps:
• Extend the Thread class.
• Override the run() method.
• Create an instance of your thread class.
• Call the start() method to begin execution.
// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
[Link]("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
[Link]("Child Thread: " + i);
[Link](500);
}}
catch (InterruptedException e) {
[Link]("Child interrupted.");
}
[Link]("Exiting child thread.");
}}
class ExtendThread {
public static void main(String args[]) {
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
[Link]("Main Thread: " + i);
[Link](1000); } }
catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("Main thread exiting.");
}}
This program generates the same output as the preceding version. As you can see, the child thread is
created by instantiating an object of NewThread, which is derived from Thread. Notice the call to super(
) inside NewThread. This invokes the following form of the Thread constructor:
public Thread(String threadName)
Here, threadName specifies the name of the thread
Using isAlive() and join():
• How can one thread know when another thread has ended?
• Two ways exist to determine whether a thread has finished. First, you can call is isAlive() on the
thread. This method is defined by thread.
final Boolean isAlive()
• isAlive(): this method checks whether a thread is currently running.
• It returns true if the thread is still executing and false if it has terminated.
• Join(): this method allows one thread to wait for the completion of another thread.
• The calling thread will block until the thread on which join() is called has terminated.
Example: Usage of isAlive() and join()
package ModuleFive;
public class NewThread implements Runnable{
String name;
Thread t;
NewThread(String Threadname)
{
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
name=Threadname;
t=new Thread(this,name);
[Link]();
}
public void run() {
try {
for(int i=9;i>1;i--) {
[Link](name+" : "+i);
[Link](500);
}
}catch(InterruptedException e)
{
[Link]("child intrruption");
}
}
}
package ModuleFive;
public class DemoisAlive {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
[Link]("Thread One is alive: " + [Link]());
[Link]("Thread Two is alive: " + [Link]());
[Link]("Thread Three is alive: " + [Link]());
// wait for threads to finish
try {
[Link]("Waiting for threads to finish.");
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread Interrupted");
}
[Link]("Thread One is alive: " + [Link]());
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
[Link]("Thread Two is alive: " + [Link]());
[Link]("Thread Three is alive: " + [Link]());
[Link]("Main thread exiting.");
}
}
Thread Priority:
• Each thread has a priority.
• Priorities are represented by a number between 1 and 10.
• In most cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling).
• But it is not guaranteed because it depends on JVM specification that which scheduling it
chooses.
Note: that not only JVM a Java programmer can also assign the priorities of a thread explicitly in a Java
program.
Setter & Getter Method of Thread Priority
Let's discuss the setter and getter method of the thread priority.
• public final int getPriority(): The [Link]() method returns the priority of
the given thread.
• public final void setPriority(int newPriority): The [Link]() method
updates or assign the priority of the thread to newPriority.
• The method throws IllegalArgumentException if the value newPriority goes out of the range,
which is 1 (minimum) to 10 (maximum).
3 constants defined in Thread class:
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
Note: Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the
value of MAX_PRIORITY is 10.
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
package ModuleFive;
public class ThreadPriority extends Thread {
// Method 1
// Whenever the start() method is called by a thread
// the run() method is invoked
public void run() {
// the print statement
[Link]("Inside the run() method");
}
// the main method
public static void main(String argvs[]) {
// Creating threads with the help of ThreadPriority class
ThreadPriority th1 = new ThreadPriority();
ThreadPriority th2 = new ThreadPriority();
ThreadPriority th3 = new ThreadPriority();
// We did not mention the priority of the thread.
// Therefore, the priorities of the thread is 5, the default value
// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
[Link]("Priority of the thread th1 is : " + [Link]());
// 2nd Thread
// Display the priority of the thread
[Link]("Priority of the thread th2 is : " + [Link]());
// 3rd Thread
// // Display the priority of the thread
[Link]("Priority of the thread th2 is : " + [Link]());
// Setting priorities of above threads by
// passing integer arguments
[Link](6);
[Link](3);
[Link](9);
[Link]("Priority of the thread th1 is : " + [Link]());
[Link]("Priority of the thread th2 is : " + [Link]());
[Link]("Priority of the thread th3 is : " + [Link]());
// Main thread
// Displaying name of the currently executing thread
[Link]("Currently Executing The Thread : " + [Link]().getName());
[Link]("Priority of the main thread is : " + [Link]().getPriority());
// Priority of the main thread is 10 now
[Link]().setPriority(10);
[Link]("Priority of the main thread is : " + [Link]().getPriority());
}
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Synchronization:
• It is a mechanism that ensures only one thread can access a shared resources at a time, preventing
data inconsistency and race conditions.
The problem:
• When multiple threads access shared data concurrently, they can interfere with each other,
leading to unpredictable results.
• For Example: if tow threads try to update same variable simultaneously, the final value may be
incorrect.
Example: Usage of synchronization
package ModuleFive;
public class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
[Link]();
}
public void run() {
synchronized (target) {
[Link](msg);
}
}
}
package ModuleFive;
public class NewSyncThread {
public static void main(String args[]) {
Callme target = new Callme();
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
[Link]();
[Link]();
[Link]();
} catch(InterruptedException e) {
[Link]("Interrupted");
}
}
}
Inter-thread Communication in Java:
• Inter-thread communication in Java 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
executed.
Note: Inter-thread communication is also known as Cooperation in Java.
What is Polling, and what are the problems with it?
The process of testing a condition repeatedly till it becomes true is known as polling. Polling is usually
implemented with the help of loops to check whether a particular condition is true or not. If it is true, a
certain action is taken. This wastes many CPU cycles and makes the implementation inefficient.
• For example, in a classic queuing problem where one thread is producing data, and the other is
consuming it.
How Java Multi-Threading tackles this problem?
• To avoid polling, Java uses three methods, namely, wait(), notify(), and notifyAll(). All these
methods belong to object class as final so that all classes have them. They must be used within a
synchronized block only.
• wait(): It tells the calling thread to give up the lock and go to sleep until some other thread enters
the same monitor and calls notify().
• notify(): It wakes up one single thread called wait() on the same object. It should be noted that
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
calling notify() does not give up a lock on a resource.
• notifyAll(): It wakes up all the threads called wait() on the same object.
Let’s now work through an example that uses wait( ) and notify( ). To begin, consider the following
sample program that incorrectly implements a simple form of the producer/ consumer problem. It
consists of four classes: Q, the queue that you’re trying to synchronize; Producer, the threaded object that
is producing queue entries; Consumer, the threaded object that is consuming queue entries; and PC, the
tiny class that creates the single Q, Producer, and Consumer.
Example: Usage of Inter-thread communication
package ModuleFive;
public class Q1 {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
[Link]("InterruptedException caught");
}
[Link]("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(valueSet)
try {
wait();
} catch(InterruptedException e) {
[Link]("InterruptedException caught");
}
this.n = n;
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
valueSet = true;
[Link]("Put: " + n);
notify();
}
}
package ModuleFive;
public class Producer1 implements Runnable {
Q q;
Thread t;
Producer1(Q q) {
this.q = q;
t=new Thread(this, "Producer");
}
public void run() {
int i = 0;
while(true) {
[Link](i++);
}
}
}
package ModuleFive;
public class Consumer1 implements Runnable {
Q q;
Thread t;
Consumer1(Q q) {
this.q = q;
t=new Thread(this, "Consumer");
}
public void run() {
while(true) {
[Link]();
} }}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
package ModuleFive;
public class PC1 {
public static void main(String args[]) {
Q q = new Q();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
//start the threads
[Link]();
[Link]();
[Link]("Press Control-C to stop.");
}
}
Creating multi-threading in java
// Example of a Java program to create multiple threads
// Class that implements Runnable
class Task implements Runnable {
private String taskName;
public Task(String taskName) {
[Link] = taskName;
}
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](taskName + " - Count: " + i);
try {
[Link](500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
[Link](taskName + " interrupted.");
}
Madhu N, Dept of CSE, AIET
AIET/IQAC/Aca/24-25/CFF
}
[Link](taskName + " completed.");
}
}
public class MultiThreadExample {
public static void main(String[] args) {
// Create threads using the Runnable implementation
Thread thread1 = new Thread(new Task("Thread 1"));
Thread thread2 = new Thread(new Task("Thread 2"));
// Start the threads
[Link]();
[Link]();
// Main thread work
for (int i = 1; i <= 5; i++) {
[Link]("Main Thread - Count: " + i);
try {
[Link](700); // Pause for 700 milliseconds
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
}
[Link]("Main thread completed.");
}
}
Madhu N, Dept of CSE, AIET