661120d04ec9a 1712398544 Java-Notes
661120d04ec9a 1712398544 Java-Notes
y
platform using the Java Virtual Machine. Because of this, Java is also known as a
WORA (Write Once, Run Anywhere)
m
● Java Version - https://en.wikipedia.org/wiki/Java_version_history
● High Level, Platform independent & Architecture Neutral
de
● Secure, Robus, Multi Thread, Distributed and OOPs language.
ca
⚠️ Why Java is not 100% Object-Oriented?
gA
● Primitive data types.
● Use of Static.
● Wrapper class
tin
Ref - https://www.scaler.com/topics/why-java-is-not-100-object-oriented/
Th
Important Points
● Since Java applications can run on any kind of CPU so it is architecture – neutral.
● Java program can be executed on any kind of machine containing any CPU or any
● operating system.
● Java is robust because of following: Strong memory management(Garbage
Collector) No Pointers Exception handling Type checking mechanism Platform
Independent.
● Using RMI and EJB we can create distributed applications in java
y
m
de
ca
gA
Check the Languages, with the Level of Abstraction
tin
es
eT
Th
Major Features of Java Programming Language
● Simple.
● Object-Oriented.
● Platform Independent.
● Portable.
● Robust.
● Secure.
● Interpreted.
● Multi-Threaded
y
m
⚠️ What is Source Code?
de
Human understandable code written using High Level Programming language is called as
Source Code. (NameOfFile.java)
not run on other OS directly. Window -> exe, Mac -> dmg, Linux, deb, pkg
Java Compiler is a program developed in C or C++ programming language with the name
eT
“javac”. It will check syntactical or grammatical errors of the programs. It converts source
code to byte code.
Java Interpreter is a program developed in C or C++ programming language with the name
“Java”. It will convert byte code to native code line by line. It will execute that native code.
y
1. Download the JDK latest -
m
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile
2. If you're using zsh (which probably means you're running macOS Catalina or
de
newer), then it should instead be:
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.zshrc
ca
3. In either case, restart your shell.
gA
How to Set JAVA_HOME path in Widnows
If you didn't change the path during installation, it'll be something like
C:\Program Files\Java\jdk21
eT
y
Progra~1 = 'Program Files'
m
Progra~2 = 'Program Files(x86)'
7. Click OK and Apply Changes as prompted
de
⚠️ What is JDK (Java Development Kit) / SDK (Software Development Kit)?
ca
It is a set of various utility programs which are required for developing and executing the java
programs.
gA
It is Platform dependent. Various JDKs are provided for various Operating Systems.
Following are various utility programs provided under JDK:
1) Java Development Tools
i. javac
tin
ii. java
iii. javap
iv. Jar
es
etc
2) Source Files
3) JRE
eT
etc
⚠️ What is JRE?
Th
Ans: JRE stands for Java Runtime Environment. It is an implementation of JVM. It contains
class
libraries, Interpreter, JIT Compiler etc. Only JRE is enough to run the Java program
⚠️ What is JVM?
Ans: JVM stands for Java Virtual Machine. It is a specification provided by SUN Microsystem
whose
implementation provides an environment to run our Java applications. JVM becomes an
instance of
JRE at run time.
Sun’s implementations of the Java Virtual Machine (JVM) is itself called as JRE. Sun’s JRE
is availabe
as a part of JDK and also as a separate application.
Many vendors has implemented JVM. Some of them are SUN JRE, IBM JRE, Oracle JRE
etc
y
m
de
ca
gA
JDK Vs JRE
tin
es
eT
Th
Java Editions
y
m
Edition Description
de
Java SE The main edition of Java that is used for desktop and server applications. It
(Standard
Edition) ca includes the Java language, JVM, class libraries, and tools for developing, testing,
Java EE A set of specifications and APIs for developing enterprise applications, including
tin
(Enterprise web and mobile applications, distributed systems, and cloud computing. It
Edition) includes components like servlets, JSPs, EJBs, JMS, JPA, and more.
es
eT
A platform for developing applications for mobile and embedded devices, like
Java ME (Micro phones, PDAs, and set-top boxes. It includes a subset of the Java SE APIs and
Edition) tools, as well as additional libraries for mobile-specific features like user
Th
A platform for developing rich client applications and user interfaces, with features
Java FX like graphics and media support, animation, and web integration. It includes a set
of APIs and tools for developing desktop, mobile, and web applications.
Note that Java EE has been rebranded as Jakarta EE, as Oracle transferred ownership of
the Java EE specification to the Eclipse Foundation.
Java Versions
y
Java Version Key Features
m
de
Java 1.0 Garbage collection, multi-threading, network programming
Java 1.1
Java 1.3 (Java 2) HotSpot JVM, Java Sound API, Bluetooth support
es
Java 1.4 (Java 2) Assertions, regular expressions, Java Web Start, JNI
eT
Java 5 (Java 1.5) Generics, annotations, enhanced for loop, concurrent API
Th
Java 11 HttpClient API, var keyword for lambda parameters, Unicode 10.0 support
y
Java 13 Text blocks, Z Garbage Collector improvements
m
Java 14 Record classes
de
Java 15 Sealed classes and interfaces, garbage collector improvements
ca
gA
Java 16 Pattern matching for instanceof, garbage collector and JFR improvements
Java Comments
Th
A comment that extends from the // marker to the end of the line. It
Single-line
// comment is ignored by the compiler and used for adding notes and
comment
explanations to the code.
A comment that can span multiple lines, starting with the /* marker
Multi-line /* comment
and ending with the */ marker. It is also ignored by the compiler and
comment */
used for adding longer explanations or temporarily disabling code.
A comment that begins with /** and ends with */. It is similar to a
Documentation /** multi-line comment, but it is specifically used for generating API
comment comment */ documentation with tools like Javadoc. It can include tags like
y
@param, @return, @throws, etc.
m
A special type of documentation comment that starts with /** and
de
includes additional Javadoc tags for generating documentation. It
Javadoc comment /** can be used to describe classes, interfaces, methods, fields, etc.
Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly
tin
to replace licensed proprietary parts / replace with more high-performance items that only
work on specific OS] components without breaking the TCK compatibility.
https://stackoverflow.com/questions/22358071/differences-between-oracle-jdk-and-openjdk
es
Setting the PATH is important for the operating system to know where to look for executable
files when a command is executed. In the case of Java, setting the PATH is essential for the
Th
system to locate the Java compiler and runtime environment (JRE) executable files.
⚠️ Which JRE will be used while compiling the Java Source File?
The JRE is not used for compiling Java source files, but rather the Java Development Kit
y
(JDK) is used, specifically the Java compiler (javac) which is included in the JDK.
⚠️ What will happen when I am compiling Java program without PRIVATE JRE?
m
Compiling a Java program does not require a PRIVATE JRE. However, if the program
de
requires a specific version of the JRE to execute, and that version is not installed on the
system, the program may not run properly.
The user will need to install a JRE before the application can be executed.
the full path to the Java executable file every time the command is executed.
JVM (Java Virtual Machine) is a virtual machine that runs Java bytecode, while JRE (Java
Runtime Environment) is a software package that includes the JVM as well as other libraries
and components required to run Java applications.
Th
y
m
de
Explain the main method in Java
● The main method in Java is the entry point for any Java program.
●
ca
It is a predefined method that is executed when a Java program is run, and is
required in every Java program.
● The main method has a specific signature, which includes the keyword "public", the
gA
keyword "static", the return type "void", and a parameter of type "String" array named
"args". Here is an example of the main method signature:
● public static void main(String[] args) {
● // code to be executed
tin
● }
● The main method takes an optional argument, "args", which is an array of strings that
ca
● n be used to pass command-line arguments to the program.
es
● When the main method completes, the JVM terminates the program.
JDK 11
y
m
de
ca
gA
tin
Identifiers - names those will be used to identify the programming elements like classes,
es
1. Identifier can contain Alphabets, Digits, and two special symbol i.e. Dollar ($),
2. Underscore (_).
3. First character of an identifier must be an Alphabet or Dollar ($) or Underscore (_).
4. Keywords or Reserved words can't be used as Identifier.
Th
Types of Variables
y
There are two types of variables based on data type used to declare the variable.
1) Primitive Variables
m
2) Reference Variables
de
ca
gA
tin
es
eT
Th
y
m
de
Some Points
●
ca
A variable is a storage location paired with an associated symbolic name (an
identifier), which contains some known or unknown quantity of information referred to
as a value.
gA
● Variables in Java are strongly typed; thus they all must have a data type declared
with their identifier
(underscore).
Primitive Variables
● Variables declared with primitive data types are called as primitive variables.
● int a; int b = 99; double d1; double d2=9.9;
Reference Variables - Variables declared with user defined data types are called as
reference variables.
String str1;
String str2 = “TheTestingAcademy”;
Based On SCOPE variables are 3 types
● Instance Variables : Variables declared in the class without using static keyword are
called as Instance Variables.
● Static Variables : Variables declared in the class using static keyword are called as
Static variables.
● Local Variables - Variables declared in the member of the class like method etc are
called as Local variables.
y
m
de
ca
gA
tin
es
eT
Th
Data Types
y
m
de
ca
gA
tin
es
eT
Th
There are eight primitive data types in Java, which are categorized into four groups: integer,
floating-point, character, and boolean.
Data Type Size (bits) Default Value Example
y
m
de
int 32 0 int i = 1000;
Internally, the value 10 is represented in binary format as 00001010 (since byte data type is
8 bits in size), and it is stored in memory as a sequence of 8 bits. The JVM allocates a
specific memory location for the variable b, and the binary representation of the value 10 is
stored at that memory location.
To illustrate this, let's assume that the memory location allocated for the variable b is
0x1000. The binary representation of the value 10 is 00001010, which can be stored in a
single byte of memory. Therefore, the value 10 is stored at memory location 0x1000 as
follows:
y
m
de
ca
gA
Reference data types are used to store complex objects, such as arrays and classes. These
data types are created using predefined or custom classes.
tin
● Interface type
● Enum type (From JAVA 5)
● Annotation type (From JAVA 5)
eT
Th
Types of Variables There are two types of variables based on data type used to declare the
variable.
1) Primitive Variables - Variables declared with primitive data types are called as primitive
variables.
2) Reference Variables - Variables declared with reference data types are called as
y
reference variables
m
String str; Hello h;
de
✅ Constants
●
●
ca
Special variable whose value can't be modified during the program execution.
Constant is also called as final variable.
gA
final int A=99;
final String STR="TTA";
final double D1=999.99;
tin
8) Instance variable cannot be accessed directly from Static method (main method).
9) You can't declare multiple variables of different data types in single variable declaration
statement.
10) You can declare multiple variables of same data types in a single statement.
11) You can assign same value to multiple variables in a single statement.
12) You can declare and initialize multiple variables of same data type in a single statement.
13) We can't declare two variables with same name in same scope.
14) Value of the variable can be changed any number of times during program execution.
15) Value of the final variable can not be changed.
16) We can't use const keyword to declare constant.
Q1 How many keywords are available prior to Java 5? 48
y
B) goto
m
Which of the following are valid Java keywords? E) struct
de
Long H) false I) virtual J) signed J) signed
Q4
ca
What are the keywords available which can’t be used in
goto, const
gA
Java Program?
reserved keyword.
types.
Q7 How many primitive data types available? 8
What is the Integral data type that will not allow negative
Q8 char
value?
y
Q9 What is the default value of char data type? '\u0000'
m
de
The range of short and char are
Why the range of short and char are different even both
Q10 different because short is signed
required 2 bytes of memory?
y
Q18 3
scope?
m
de
Primitive variables hold the actual
What are the differences between Primitive variables and values, while reference variables
Q19
ca
Reference variables? hold the memory location of the
object.
gA
There is no default value for a local
Q20 What is the default value of local variable? variable. It must be initialized
before use.
tin
How can I declare multiple variable of same type in one can be declared in one statement
Th
Q22
statement? by separating each variable name
with a comma.
How can I declare and initialize multiple variables of statement by separating each
Q24
same type in one statement? variable name with a comma and
when it is declared.
y
execution?
m
de
Memory for variables is allocated
Q26 When will the memory be allocated for the variables? at runtime, while the program is
executing.
ca
gA
UNICODE Characters
tin
● Syntax:
○ \uXXXX - X will be hexadecimal digit
● Starts with \u followed by four hexadecimal digits.
eT
● UNICODE Range
● \u0000 (0) to \uFFFF (65535)
Th
Th
eT
es
tin
gA
ca
de
m
y
Practice QnA
y
Question 1
int enum=9;
m
System.out.println(enum);
de
Question 2
char char='A'; System.out.println(char);
ca
gA
tin
es
eT
Th
✅ Literals
● Literals are the actual values assigned
● Literals can be Numeric and Non Numeric.
Literal Type Description
y
m
Floating-point literals Numbers with decimal points, such as 3.14 or -0.0025
de
Character literals A single character enclosed in single quotes, such as 'a'
ca
gA
Boolean literals A value of either true or false
tin
String literals A sequence of characters enclosed in double quotes, such as "hello world"
es
Null literals A special literal that represents a null reference or a null value
eT
Th
Types of Literals
1) Boolean Literals - true, false
2) Character Literals -
3) String Literals
4) Integral Literals
5) Floating Literals
6) null Literal
1. Boolean Literals
There are two boolean literals 1) true 2) false
2. Character Literals
A char type variable can hold following:
● Single character enclosed in single quotation marks
● Escape Sequence
● ASCII Value
● UNICODE Character
● Octal Character
y
https://stackoverflow.com/questions/1761051/difference-between-n-and-r
m
de
Escape Sequence - Task_12.java
ca
gA
tin
● Every character enclosed in single quotation marks will have an integer equivalent
value
● called as ASCII value.
eT
061 -> 49
061 = (0 × 8²) + (6 × 8¹) + (1 × 8⁰) = 49
https://www.rapidtables.com/convert/number/octal-to-decimal.html
y
m
de
ca
gA
tin
es
eT
Th
y
m
How many boolean literals are There are only two boolean literals available, which are true and
available? false.
de
When you assign the value 1 to a boolean type variable, it will be
ca
What will happen when I assign 1
UNICODE value is found in String The string "UNICODE of A is A" will be displayed because \u0041
is \u0041";
What will be displayed when Octal
representation is found in String The string "Octal of A is A" will be displayed because \101
\101";
What will happen when Escape The string "Hello" will be displayed on the first line, and "Guys"
Sequence is found in String will be displayed on the next line because \n represents the
y
m
Integer Literals
de
● Decimal Literals- // Base of 10
● Octal Literals - int b=0101; // Base of 8
●
● ca
Hexadecimal Literals - int c=0Xface; // base 16 rather than base 10
Binary Literals (From Java 7) - int b2 = 0b101;
gA
Scientific / Exponent N Literals
float f = 129.8763e2F;
tin
double d1 = 129.8763e+2;
double d2 = 12987.63e-2;
System.out.println(f);
es
System.out.println(d1);
System.out.println(d2);
eT
Null literal
Th
● null is a value.
● It is default value for any reference variable.
● If the value of reference variable is null then it indicates that address/reference is not
● available in the variable.
String str2=null;
System.out.println(str1);
✅ Operators
Operators are used to perform operations by using operands.
There are three types of operator depending on the number of operands required.
● 1) Unary Operator
○ Only one operand is required.
● 2) Binary Operator
y
○ Two operands are required.
● 3) Ternary Operator
m
○ Three Operands are required.
de
Types of operator depending on the operation:
● Arithmetic Operators
○ i. Unary Arithmetic Operators
○ ii. Binary Arithmetic Operators
ca
● String Concatenation Operator
● Assignment Operator
○ i. Simple Assignment Operator
gA
○ ii. Compound Assignment Operators
● Increment & Decrement Operators
● Relational Operators
● Logical Operators
tin
● new Operator
● instanceof Operator
● Conditional or Ternary Operator
es
● Bitwise Operators.
eT
● unary minus(-)
● increment(+)
○ Pre
○ post
● decrement(-)
○ Pre
○ post
● NOT(!) - boolean and condition
● Bitwise Complement (~) - unary operator returns the one’s complement
representation of the input value or operand,
a = 5 [0101 in Binary]
result = ~5
● Addressof operator(&)
● sizeof()
y
m
de
ca
Remember this
gA
tin
es
eT
Th
String Concatenation Operator (+)
+ operator can be used for two purposes:
1) Arithmetic Addition
2) String Concatenation
y
o Operand1 must be a variable.
o Operand2 can be a variable, value or expression.
m
de
ca
Type Casting
gA
Source type is not same as destination type then source type must be converted to
destination type.
o Implicit casting
o Explicit Casting
es
o Explicit Casting
Implicit casting:
When type casting is happening automatically by the compiler then it is called as Implicit
Th
Casting.
Explicit Casting:
When type casting is happening explicitly by the programmer then it is called as Explicit
Casting.
There are two types of conversions:
o Widening
o Narrowing
Widening
Widening is the process of converting lower type to higher type. This is safe conversion.
Ex:
byte b=10;
int a=b; // VALID – Implicit Casting
int a= (int)b; // VALID – Explicit Casting
y
int a=300; -> int means 32 bits memory required
m
00000000000000000000000100101100
byte b1=(byte)a; -> byte means 8 bits memory required
de
00101100
Value is
0 * 27 + 0 * 26 + 1 * 25 + 0 * 24 + 1 * 23 + 1 * 22 + 0 * 21 + 0 * 20
ca
0 + 0 + 32 + 0 + 8 + 4 + 0 + 0 = 44.
gA
Compound Assignment Operators
y
m
Logical Operators
de
ca
gA
tin
es
eT
Th
Logical OR and Logical AND ( || , &&
y
m
de
ca
gA
new Operator
● new operator is used to create the new object for class.
tin
instanceof Operator
● It is used to check whether the given object belongs to specified class or not.
● Result of instanceof operator is boolean value.
eT
Conditional Operator
● It is ternary operator. ? : Operand1 must be of boolean type.
● If Operand1 is true then Operand2 will be returned otherwise Operand3 will be
returned.
Bitwise Operators
y
m
de
ca
Bitwise AND o Bitwise OR o Exclusive OR (XOR)
gA
https://bit-calculator.com/bit-shift-calculator
tin
1. 7+ (6 + 5 *3) - 4/2
2. boolean b = (boolean)1; b)
3. String str=(String)99;
es
eT
Th
y
m
de
ca
Interview QnA
gA
Question Answer
tin
What is the result type of String concatenation The result type of String concatenation operation is
What will happen when I try to assign int type The code will not compile because you cannot assign
to String type variable? Ex: String str=99; an int value to a String variable directly.
What are types of operands allowed for Comparison operators can be used with numeric and
What is type casting and what are the types type to another. The types available are widening
y
(explicit).
m
The new operator is used to create an instance of a
de
What is the use of new operator?
class or an array.
ca
What is the difference between String
What are the bitwise operators available? (bitwise AND), | (bitwise OR), ^ (bitwise XOR), << (left
What is 2's Complement? integers in binary. It involves flipping all the bits and
What are types of operands allowed for Arithmetic operators can be used with numeric
arithmetic operators? operands (int, long, float, double) and char operands.
y
m
What is the difference between unary Unary arithmetic operators act on a single operand,
arithmetic and binary arithmetic operators? while binary arithmetic operators act on two operands.
de
What is the syntax of Explicit casting? The syntax of explicit casting is: (datatype) value.
ca
What are types of operands allowed for Bitwise operators can be used with integer operands
gA
bitwise operators? (int, long, short, char, byte).
tin
Question Answer
y
An operator is a symbol that represents a specific operation
m
What is an operator?
to be performed between operands.
de
What are the valid conditions for Division by a positive number or multiplication by a positive
ca
"Infinity" output? infinity.
gA
Arithmetic operators are used to perform mathematical
What is the use of arithmetic operators?
calculations between operands.
tin
What is the difference between String String concatenation is used to join two or more strings
eT
Concatenation and Arithmetic Addition together, while arithmetic addition is used to add numeric
operator? values.
Th
What is the result of instanceof The instanceof operator returns true if an object is an
y
What will happen when I try to assign int It will result in a compilation error because they are
m
type to String type variable? incompatible types.
de
What is the use of assignment The assignment operator is used to assign a value to a
operator? variable.
ca
What is the difference between unary
gA
Unary operators work on a single operand, while binary
arithmetic and binary arithmetic
operators work on two operands.
operators?
tin
What is the use of Logical NOT The logical NOT operator is used to reverse the truth value of
es
What is the difference between Implicit Implicit casting is done automatically by the compiler, while
casting and Explicit Casting? explicit casting is done manually by the programmer.
Th
What is the syntax of Explicit casting? The syntax of explicit casting is: (target_type) expression.
y
m
What is result type when you add byte
The result type is an int.
de
and int variables?
available? ca
What are the bitwise operators
The bitwise operators are: &,
gA
What is the difference between prefix The prefix form evaluates and returns the value after the
and postfix forms of decrement operation, while the postfix form evaluates and returns the
tin
if(a % 2==0)
System.out.println("Value is EVEN");
y
else
System.out.println("Value is ODD");
m
}
de
Problem to find the MAX three
// switch statement
switch(expression)
y
{
m
// case statements
// values must be of same type of expression
case value1 : expression = value 1 ->
de
// Statements
break; // break is optional
ca
case value2 :
// Statements
break; // break is optional
gA
// We can have any number of case statements
// below is default statement, used when none of the cases is true.
// No break is needed in the default case.
tin
default :
// Statements
}
es
sop("chrome started!!");
break;
Th
switch (itemCode) {
case 001, 002, 003 :
System.out.println("It's an electronic gadget!");
break;
A new keyword yield has been introduced. It returns values from a switch branch only.
We don’t need a break after yield as it automatically terminates the switch expression.
y
case "x", "y" :
m
yield 1;
case "z", "w" :
yield 2;
de
}
ca
Switch can be used as an expression
case 003 :
yield "It's a mobile phone!";
default :
throw new IllegalArgumentException(itemCode + "is an unknown device!");
es
}
eT
switch (itemCode) {
Th
1.
Th
eT
es
tin
gA
ca
de
m
y
While
● condition of while statement is mandatory and must be boolean type
y
m
de
Do While ca
gA
● When you are using for statement or while statement then it verifies the condition
before executing the block.
● So in the case of for statement and while statement, when first time condition is false
tin
In the case of do-while first block of statements will be executed and then condition
will be verified.
eT
Th
y
m
de
ca
gA
● break is a keyword.
● It can be used within switch or any looping statement.
● It is used to terminate the execution of the current looping/switch statement.
● break can be used in two ways:
Th
● break;
● break <label>;
Continue
● continue is a keyword.
● It can be used within any looping statements.
● It is used to continue the execution of the current looping statement with next
iteration.
● continue can be used in two ways:
○ continue;
○ continue <label>;
✅ Arrays
y
● Array is a collection of data which is of similar type.
● Array is also called as Homogeneous data structure.
m
● Elements of an array will be stored in contiguous memory locations.
● Arrays are objects in Java.
de
● Three tasks to remember while you are working with arrays:
○ o Array Declaration
○ o Array Construction
○ o Array Initialization
●
●
●
ca
Arrays can be constructed with multiple dimensions i.e 1-D Array, 2-D Array etc.
length
Use loop to traverse.
gA
● Array size is mandatory while constructing an array object. a. int a[] =new int[3];
//VALID b. int a[] =new int[]; //INVALID
● You can't specify the size of an array at the time of declaration. a. int a[] //VALID b. int
a[1] //INVALID.
tin
Multidimensional Arrays
y
m
● Object class is present in java.lang package.
● Every class in Java is directly or indirectly derived from the Object class.
de
● Object class methods are available to all Java classes.
Ref image - geeksforgeeks
ca
gA
tin
es
toString() method
In Java, the toString() method is a method defined in the Object class that returns a string
representation of an object.
eT
@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}
Person p = new Person("John", 30);
System.out.println(p); // prints "Person[name=John, age=30]"
hashCode() method
In Java, the hashCode() method is a method defined in the Object class that returns an
integer hash code value for an object.
The hashCode() method is implemented by converting the internal address of the object into
y
an integer value. If two objects are equal according to the equals() method, then they should
have the same hash code.
m
public class Person {
de
private String name;
private int age;
ca
public Person(String name, int age) {
this.name = name;
this.age = age;
gA
}
@Override
public int hashCode() {
tin
return result;
}
}
eT
In Java, the equals(Object obj) method is a method defined in the Object class that
compares the current object to the specified object.
The method returns true if the objects are equal, and false if they are not.
The default implementation of the equals() method in the Object class compares the memory
addresses of the objects
y
@Override
m
public boolean equals(Object obj) {
if (obj == this) return true;
de
if (!(obj instanceof Person)) return false;
Person other = (Person) obj;
return name.equals(other.name) && age == other.age;
}
}
ca
Person p1 = new Person("John", 30);
gA
Person p2 = new Person("John", 30);
Person p3 = new Person("Jane", 30);
getClass() method,
eT
Class c = obj.getClass();
System.out.println("Class of Object obj is : "
+ c.getName());
}
}
finalize() method
This method is called just before an object is garbage collected. It is called the Garbage
Collector on an object when the garbage collector determines that there are no more
references to the object.
y
t = null;
m
// calling garbage collector
de
System.gc();
System.out.println("end");
}
ca
@Override protected void finalize()
{
gA
System.out.println("finalize method called");
}
}
tin
clone()method
It returns a new object that is exactly the same as this object. For clone() method refer
es
Clone().
eT
@Override
public Person clone() {
try {
return (Person) super.clone();
} catch (CloneNotSupportedException e) {
// This should never happen, since we are Cloneable
throw new InternalError(e);
}
}
}
Note that the clone() method only creates a shallow copy of the object, which means that it
only copies the references to the object's fields, rather than creating new copies of the
y
objects themselves. If you want to create a deep copy of an object, you need to create a new
copy of each object contained within the original object.
m
📙 Arrays in Java
de
● A group of like-typed variables referred to by a common name.
●
●
●
caArrays are stored in contiguous memory.
The variables in the array are ordered, and each has an index beginning from 0.
The size of an array must be specified by int or short value and not long.
gA
● The size of the array cannot be altered(once initialized).
● JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been
accessed with an illegal index
tin
MyClass myClassArray[];
Object[] ao,
es
// Array of Objects
Student[] arr = new Student[5];
Th
Java program that reads a list of integers from the user and then prints the highest and
lowest values in the list.
Enter a number: 5
Enter a number: 3
y
Enter a number: 8
m
Enter a number: 2
Enter a number: -1
de
The highest number is 8
The lowest number is 2
ca
import java.util.Scanner;
gA
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
tin
do {
System.out.print("Enter a number: " , -1 to stop entering”);
n = scanner.nextInt();
Th
if (n >= 0) {
numbers[size] = n;
size++;
}
} while (n >= 0);
y
m
For Each - For collections and arrays only
de
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other arrays.
ca
int [][] arr= new int[3][3];
gA
tin
es
eT
Th
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
🧵 String in Java
● Sequence of Characters.
y
● String is a built-in class in java.lang package.
m
● String is final class, so you can't define the subclass for String class.
● String class implements the following interfaces:
○ java.io.Serializable
de
○ java.lang.Comparable
○ java.lang.CharSequence
● String class has following variable to hold data.
1) String class
2) StringBuffer
es
3) StringBuilder
4) Array of Characters
5) ArrayList of Characters
eT
Th
The original string str1 remains unchanged, and the new string str2 is assigned the
concatenated value. This demonstrates the immutability of strings in Java.
https://www.digitalocean.com/community/tutorials/string-immutable-final-java
y
m
de
ca
gA
tin
es
eT
Here are some of the most commonly used functions of the String class:
Th
charAt(int index): Returns the character at the specified index in the string.
Example: "hello".charAt(0) returns 'h'.
concat(String str): Concatenates the specified string to the end of the original string.
Example: "hello".concat(" world") returns "hello world".
contains(CharSequence s): Returns true if the string contains the specified sequence of
characters, otherwise false.
Example: "hello world".contains("world") returns true.
equals(Object obj): Returns true if the string is equal to the specified object, otherwise
false.
Example: "hello".equals("world") returns false.
equalsIgnoreCase(String str): Returns true if the string is equal to the specified string,
ignoring case differences, otherwise false.
Example: "HELLO".equalsIgnoreCase("hello") returns true.
indexOf(int ch): Returns the index of the first occurrence of the specified character in the
string, or -1 if the character is not found.
Example: "hello".indexOf('l') returns 2.
y
length(): Returns the length of the string.
Example: "hello".length() returns 5.
m
replace(char oldChar, char newChar): Returns a new string resulting from replacing all
de
occurrences of the specified oldChar with the specified newChar.
Example: "hello".replace('l', 'w') returns "hewwo".
ca
split(String regex): Splits the string into an array of substrings based on the specified
regular expression.
Example: "hello world".split(" ") returns ["hello", "world"].
gA
substring(int beginIndex, int endIndex): Returns a new string that is a substring of the
original string, starting from the specified beginIndex and ending at the endIndex (exclusive).
Example: "hello".substring(1, 3) returns "el".
tin
== operator checks if two string references point to the same memory location.
Th
equals method compares the actual content of the strings, checking if they contain the same
sequence of characters.
y
StringBuffer and StringBuilder
m
● equals() is not overriden in StringBuilder and StringBuffer class.
● hashCode() is not overriden in the StringBuilder and StringBuffer class.
de
●
ca
Table summarizing the most commonly used functions of StringBuilder and StringBuffer
classes in Java:
gA
Function Description
tin
append() Appends the specified character(s) or object to the end of the string.
es
insert() Inserts the specified character(s) or object at the specified index in the string.
eT
Th
Deletes the characters from the string between the specified start and end
delete()
indices.
y
substring() Returns a substring of the string between the specified start and end indices.
m
de
charAt() Returns the character at the specified index in the string.
length()
ca Returns the length of the string.
gA
tin
setCharAt() Sets the character at the specified index in the string to the specified character.
es
Ensures that the capacity of the string builder is at least the specified minimum
ensureCapacity()
capacity.
trimToSize() Trims the capacity of the string builder to its current length.
Note that StringBuilder and StringBuffer share most of their functions and have very similar
syntax. The main difference between them is that StringBuilder is not thread-safe, while
StringBuffer is thread-safe.
Reverse a String
Input - s = abc
y
O/P- s = cba
m
public static void main (String[] args) {
de
String str= "Pramod", nstr="";
char ch;
ca
System.out.print("Original word: ");
System.out.println("Pramod"); //Example word
gA
for (int i=0; i<str.length(); i++)
{
ch= str.charAt(i); //extracts each character
tin
}
eT
Palindrome
Th
y
if (str.equals(rev)) {
ans = true;
m
}
return ans;
de
}
ca
Using the String Builder
class ReverseString {
gA
public static void main(String[] args)
{
String input = "Pramod Sir is Owner of TheTestingAcademy";
tin
input1.append(input);
input1.reverse();
y
temp = str[start];
str[start] = str[end];
m
str[end] = temp;
start++;
de
end--;
}
}
// Function to reverse words
{ ca
static char[] reverseWords(char[] s)
int start = 0;
for (int end = 0; end < s.length; end++) {
tin
// If we see a space, we
// reverse the previous
// word (word between
es
// Driver Code
public static void main(String[] args)
{
String s = "i like this program very much ";
// Function call
char[] p = reverseWords(s.toCharArray());
System.out.print(p);
}}
y
m
🧵 Funtions in Java
de
a function is called a method(class). Methods in Java are blocks of code that perform a
specific task and can be reused throughout your program
ca
1. No Return Type
2. Return Type
gA
int add(int a, int b) {
return a + b;
}
tin
int result = add(5, 3); // Calling the 'add' method with arguments 5 and 3
Practice -
● Prime Number
● Swap Two Numbers
● String reverse
● Take User input as array
● Maximum in Array
y
● Print diagonal Elements 2D array
m
de
ca 📗 OOPs ( Java)
gA
2. Object vs Functional
es
eT
Th
PPL Details
Using the Global Struct to create a Complex Data Type and X global primitive
Struct Customer {
Int id,
String name
String age
Int x = 99;
● UpdateCustomer()
y
● FetchCustomer()
● Show() can also use the Customer and Primitive x (NO ENCAPSULATION)
m
● Data Security issues (global, local variables)
de
☯️ No Relation between the Struct(Global) and Functions.
ca
How to Use Oops to Build Any Modern-Day Software
a. Data - Student -> name, id, age, address, email, course taken
b. Operations -> addStudent, deleteStudent
c. Bind them with Encapsulation (Class)
es
Abstraction Example
y
m
de
ca
gA
tin
es
eT
Th
Abstract class
An abstract class, on the other hand, can contain both abstract methods (methods with no
implementation) and concrete methods (methods with an implementation).
// concrete method
public String getColor() {
return this.color;
}
// abstract method
public abstract double getArea();
}
y
class Rectangle extends Shape {
m
private double width;
private double height;
de
public Rectangle(double width, double height, String color) {
super(color);
this.width = width;
} ca
this.height = height;
gA
// implementation of the abstract method defined in the superclass
@Override
public double getArea() {
return this.width * this.height;
tin
}
}
es
In this example,
● the Shape class is an abstract class that defines an abstract method getArea() and a
concrete method getColor().
● The Rectangle and Circle classes are concrete subclasses of Shape that must
implement the getArea() method because it is abstract in the superclass.
● The Rectangle and Circle classes can also use the getColor() method inherited from
the Shape class.
[Assignment]
20+ Examples of Abstract Class and Interface (in Demo)
y
Interface
m
An interface is a collection of abstract methods that must be implemented by any class that
implements the interface
de
Inheritance
ca
1. Example with Student -> Manual , Automation
2. Extra Data members, Operations or Methods
gA
PolyMorphism
● + operator
tin
y
m
de
ca
the different types of inheritance include:
gA
1. Single Inheritance: A class inherits from a single base class.
tin
a hierarchy of inheritance.
eT
Question Answer
The purpose of a programming model is to provide a systematic approach to
Q1) What is the purpose develop computer programs. It defines the rules, principles, and guidelines to
of any programming be followed while designing and implementing software solutions. It also
model? helps programmers to organize their code and create efficient, reliable, and
maintainable applications.
Q2) What are the The programming models available to develop applications include
y
available to develop functional programming (FP), event-driven programming (EDP), and
m
applications? aspect-oriented programming (AOP).
de
The main components of the Procedure Oriented Programming model
ca
Q3) What are the main
components of the
Procedure Oriented
include procedures or functions, which are a set of instructions that perform
a specific task, and data structures, which are used to organize and store
data. POP follows a top-down approach, which means the program flow
gA
Programming model? starts from the main function and then calls other functions or procedures
as required.
tin
Q4) What are the The limitations of the Procedure Oriented Programming model include a lack
es
limitations of the of data security, difficulty in maintaining and modifying code, and low
Procedure Oriented reusability of code. POP is also not suitable for large-scale applications as
Programming model? the program logic becomes complex and difficult to manage.
eT
Q5) What is OOPs emphasizes the use of objects, which are instances of classes, to represent
Q6) What are the main used to define the attributes and behavior of objects, and objects are
Object-Oriented provides data security by hiding the implementation details of classes, while
Programming model? inheritance allows the creation of new classes by extending existing classes.
Polymorphism enables the use of the same code for different types of
objects.
y
m
Q7) Who is the father of Alan Kay is considered the father of OOPs, as he introduced the concept of
de
OOPs? object-oriented programming in the 1960s.
ca
Q8) What are the major
The major principles of Object-Oriented Programming include inheritance,
details, and polymorphism enables the use of the same code for different
types of objects.
es
Q9) What is abstraction? complex systems by breaking them down into smaller, manageable parts. In
interfaces.
Class Book{
y
Int id;
m
String name;
String author;
de
}
ca
1. JVM allocates 8 bytes for each reference variable.
2. All variables are assigned a memory.
gA
3. Referq
● Override the methods if the child extends the Parent or adds itself as Abstract.
● No object for Abstract, only reference.
es
Interfaces
eT
1. Variables
2. Blocks
3. Constructors
eT
4. Methods
5. Inner Class
Th
package atb.classdemo;
// Block
{
System.out.println("I am block");
}
// Default constructor
Book(){
System.out.println("Default Con");
}
// Parameters constructor
public Book(int id, String name, String author) {
this.id = id;
this.name = name;
y
this.author = author;
}
m
// Method
de
void show(){
System.out.println("Data");
}
ca
@Override
public String toString() {
return "Book{" +
gA
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
'}';
tin
}
es
// Inner Classe
class Publisher{
String name;
eT
void show(){
System.out.println(Book.this.name);
}
Th
Type of Variables
1. Instance Variable
a. Primitive variable
b. Reference variable
2. Local Variables
3. Static Variables
package atb.classdemo.staticdemo;
y
System.out.println(b);
}
m
}
de
Static members can be accessed with Class Name.
ca
Instance members can’t be accessed with class Name.
package atb.classdemo.staticdemo;
gA
public class Main {
public static void main(String[] args) {
StaticDemo.m2(); // How?
tin
}
}
es
Class Loaders
eT
Encapsulation
● Refers to the bundling of data and methods that operate on that data within a single
unit, or object.
● Encapsulation helps to promote the principle of "data hiding".
● This is achieved by declaring the object's data fields as private and providing
public getter and setter methods to access and modify the data.
y
}
m
public void setName(String name) {
this.name = name;
de
}
public int getAge() {
return this.age;
}
ca
public void setAge(int age) {
this.age = age;
gA
}
public String getAddress() {
return this.address;
}
tin
}
}
eT
Th
Access Modifier
Th
eT
es
tin
gA
ca
de
m
y
Access modifiers in Java:
y
m
de
ca
gA
tin
es
Polymorphism
eT
Th
Th
eT
es
tin
gA
ca
de
m
y
Th
eT
es
tin
gA
ca
de
m
y
y
m
de
Abstraction
ca
gA
Abstract classes and methods
tin
● Although it is not required, an abstract class may have the declaration of one or more
abstract methods.
● Since the body of an abstract method cannot be implemented in an abstract class.
Th
y
7. Variables declared in the interface are by default public final and static.
8. Methods declared in the interface are by default public and abstract.
m
de
Default Methods in interfaces
● Default methods are methods that can have a body.
●
●
ca
They provide additional functionality to a given type without breaking down the
implementing classes.
If a new method was introduced in an interface then all the implementing classes
gA
used to break.
static methods in interfaces are similar to default methods but the only difference is that you
can’t override them.
eT
interface I1{}
interface I2{}
class A{}
class B{}
class Test1 extends A{ } //0K
class Test2 extends A,B{ } //Not OK
class Test3 implements I1{ }//0K
class Test4 implements I1,I2{ }//0K
class Test5 extends A implements I1,I2{ }//OK
class Test6 implements I1 extends A{ } / /Not OK
interface I3 extends A{}
interface I4 implements A{}
interface I5 extends A,B{}
interface I6 extends I1,I2{ }
y
m
de
ca
✅ Problem Statement
gA
Book class which has an abstract method getDetails(),name, author, price.
PrintMyBook class that inherits from the Book class.
asbtract
tin
// Output
es
Nested Class
Class within Class is called Nested class
class OuterClass
{
...
class NestedClass
{
...
}
}
y
m
de
ca
gA
Static Nested Class
class OO{
static int o =100;
es
int a = 900;
static class SNCI{
void show(){
eT
System.out.println(o);
//Only a static member of outer class can be accessed directly.
// System.out.println(a);
}
Th
}
}
}
}
Inner Class
An inner class in Java is a class that is defined within another class. Inner classes are useful
for organizing code and for creating classes that are tightly coupled to their outer class.
y
4. Static declaration is not allowed in the inner class
m
5. Static Inner class, Instance Inner class, Local Inner class, Anonymous inner class
de
There are 4 ways you can create a Class
1. Inner Class
2. Method Level Inner Class
ca
3. Nested Class
4. Anonymous Class
gA
public class Car {
// outer class field
private String make;
private String model;
tin
// inner class
public class Engine {
es
this.horsepower = horsepower;
this.fuelType = fuelType;
}
//
Car myCar = new Car("Toyota", "Camry");
y
Car.Engine engine = myCar.new Engine(200, "Gasoline");
engine.start();
m
de
ca
Upcasting and Downcasting in Class
gA
You can assign a subclass object to the super type reference variable directly. This process
is called UPCASTING.
tin
class Parent{}
class Child extends Parent{}
es
class Hello{}
class Child extends Hello{}
An anonymous inner class can be useful when making an instance of an object with
certain “extras” such as overriding methods of a class or interface, without having to actually
subclass a class.
y
{
// data members and methods
m
public void test_method()
{
de
........
........
}
}
●
ca
An anonymous class has access to the members of its enclosing class.
gA
● An anonymous class cannot access local variables in its enclosing scope that are not
declared as final or effectively final.
● constructors can not be declared in an anonymous class.
tin
●
es
eT
Th
Anonymous inner classes are generic created via below listed two ways as follows:
package thetestingacademy.oops.anonymousclass;
y
Student student = new Student() {
m
@Override
public void setId() {
System.out.println(id);
de
}
};
student.setId();
}
}
ca
interface Student{
gA
int id = 11;
void setId();
}
@Override
public void setId() {
System.out.println(id);
es
}
}
eT
Th
Wrapper Classes
● A Wrapper class is a class whose object wraps or contains primitive data types.
● They convert primitive data types into objects.
● Data structures in the Collection framework, such as ArrayList and Vector, store
only objects (reference types) and not primitive types.
● An object is needed to support synchronization in multithreading.
y
m
Primitive -> Wrapper , Primitive -> String ,Wrapper -> Primitive
de
ca
1. Primitive to String
1. Using valueOf()
2. toString() of wrapper
2. String to Primitive
gA
a. A) using parseXO;
3. Primitive to Wrapper Object
a. A) Using Constructor of Wrapper class
tin
// JVM - values from -128 to 127 are cached, so the same objects are returned.
y
Integer X = new Integer(10);
Integer Y = 10;
m
// Due to auto-boxing, a new Wrapper object
de
// is created which is pointed by Y
System.out.println(X == Y);
ca 📕 Exceptions
gA
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions.
tin
P.S. - If no exceptions are handled, control is passed to the JVM, which terminates the
program.
es
Exception Hierarchy
eT
Th
package thetestingacademy.exceptions; // 0
y
int x = Integer.parseInt(sh);
int a = 10/x;
m
System.out.println(x);
System.out.println(a);
}
de
}
2.
ca
Solve the three problems in the above program.
1. Array.
Number format
gA
3. Arithmetic.
tin
Exception Handling in Java is a mechanism for handling runtime errors so that the
application's normal flow can be maintained.
es
⚠️Questions
1. Throwable in Catch Block
2. String in Catch ?
y
m
de
ca
gA
tin
es
Multiple Catch
You can catch multiple exceptions; their execution depends on the execution problem.
eT
package thetestingacademy.exceptions;
Th
⚠️
// Keep the Biggest at the last Exception E ( bigger basket)
y
P.S. - Please do not write anything between Try and Catch.
m
Please find the problem in this Code.
de
package thetestingacademy.exceptions;
ca
public static void main(String[] args) {
try {
int a = Integer.parseInt(args[0]);
gA
}
catch (NumberFormatException exception) {
exception.printStackTrace();
}
tin
try {
int b = 10 / a;
}
es
try {
String ip = args[0];
}
catch (ArrayIndexOutOfBoundsException exception) {
Th
exception.printStackTrace();
}
}
}
Or Catch Concept
After Java 7, We can write them in OR condition with pipe char |
try {
String ip = args[0];
int a = Integer.parseInt(args[0]);
int b = 10 / a;
} catch (NumberFormatException | ArithmeticException |
ArrayIndexOutOfBoundsException exception) {
exception.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
y
Finally Block
m
The finally block is a block of code that follows a try-catch block and is always executed,
de
regardless of whether an exception is thrown or caught. The finally block is typically used to
release resources or perform other cleanup tasks.
try {
ca
// code that might throw an exception
} catch (ExceptionType e) {
gA
// code to handle the exception
} finally {
// code to be executed after the try-catch block
}
tin
Yes
y
FileInputStream file = null;
m
try {
file = new FileInputStream("file.txt");
// read from the file
de
} catch (FileNotFoundException e) {
System.out.println("File not found!");
} finally {
ca
if (file != null) {
try {
file.close();
gA
} catch (IOException e) {
// handle the exception
}
}
tin
}
}
es
Problem 1
class ProblemF{
int a = 10;
int show(){
try{
System.out.println("In class -> "+ a);
return a;
}catch (Exception e){
System.out.println("Catch");
a = 20;
return a;
}finally {
System.out.println("I am Final");
}
}}
Problem #2
y
package thetestingacademy.exceptions;
m
public class Ex06 {
de
public static void main(String[] args) {
ProblemF problemF = new ProblemF();
int x = problemF.show();
System.out.println(x);
}
}
ca
gA
class ProblemF{
int a = 10;
int show(){
try{
tin
// a = 10/0;
System.out.println("In class -> "+ a);
return a;
es
return a;
}finally {
System.out.println("I am Final");
Th
y
package thetestingacademy.exceptions;
m
public class Ex08 {
public static void main(String[] args) {
de
try {
int a = 10 / 10;
} catch (Exception a) {
System.out.println("I am Catch 01");
}
ca
} finally {
System.out.println("Finally 01");
gA
try {
int a = 10 / 0;
} catch (Exception a) {
System.out.println("I am Catch 02");
tin
} finally {
System.out.println("Finally 02");
}
es
try {
int a = 10 / 0;
} catch (Exception a) {
eT
System.out.println("Finally 03");
}
try {
int a = 10 / 20;
} catch (Exception a) {
System.out.println("I am Catch 04");
} finally {
System.out.println("Finally 04");
}
}
}
Exception Passing Methods
y
m
package thetestingacademy.exceptions;
de
public class Exception02 {
public static void main(String[] args) {
extracted2();
System.out.println("MAIN Execute");
}
ca
private static void extracted2() {
gA
extracted1();
System.out.println("extracted2 Execute");
}
tin
try {
// String name = null;
// name.length();
Th
y
Throw exObject.
m
Throws Keyword at Method LEVEL
de
ca
gA
tin
es
eT
Custom Exception
allow you to create specific types of exceptions to represent error conditions that are specific
to your application.
For example, you might create a custom exception to represent an error condition such as
"insufficient funds" in a bank account application. This allows you to handle this error
condition in a specific way, rather than using a more general exception type such as
"Exception" or "RuntimeException".
y
m
de
ca
gA
tin
Important Points
es
catch(Exception){}
catch(Error){}
catch(Throwable){}
catch(Object){} //Not Ok
2) NoClassDefFoundError
y
3) StackOverflowError
m
In recursive method call, if memory is not available in stack.)
de
4) OutOfMemoryError
ca
int arr[]=new int[54453453];
5) UnsupportedClassVersionError
gA
(If JVM version is lower then compiler version.)
6) ExceptionInInitializerError
tin
(if exception occurs at static variable or static block while loading the class.)
static int p;
static {p=Integer.parseInt("SRI");}
}
es
eT
1) ClassCastException
Th
(If you try to convert superclass object into subclass object whitout having the ref. of
subclass.)
2) IllegalStateException
3) IllegalArgumentException
t.setPriority(30);
Thread priority must be b/w 1-10.
Try Out
package thetestingacademy.exceptions;
y
public class Ex11 {
m
public static void main(String[] args) {
de
Hello h = new Hello();
h.process();
System.out.println("Pramod");
}
} ca
gA
class Hello {
public int process() {
tin
}
eT
Th
Collection Framework
y
● Since we have to give size, memory is wasted.
● Insertion and deletion are heavy.
m
● No built-in support for sorting, searching.
de
We prefer below classes and Interfaces in place of Arrays.
● Vector
● Stack
ca
Legacy Classes
gA
● Properties
● Hash table
● Dictionary
tin
Legacy Interface
● Enumeration (cursor)
es
Enumeration
It is an interface used to get elements of legacy collections(Vector, Hashtable)
eT
What is a Framework?
A framework is a set of classes and interfaces which provide a ready-made architecture.
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html
y
m
de
ca
gA
● Ordered Collection
● Control over the insertion
● List allows Duplicate.
tin
Way to Initialize
● List<String> fruites = List.of("orange","apple");
● ArrayList - Underline Array - Get element is easy, inserting, Delete is Costly.
es
● LinkedList - LinkedList
● Vector
eT
Most of the time, programmers prefer ArrayList over Vector because ArrayList can be
synchronized explicitly using Collections.synchronizedList.
Th
List Functions
Use the javap java.util.List
y
21. public abstract void add(int, E);
22. public abstract E remove(int);
m
23. public abstract int indexOf(java.lang.Object);
24. public abstract int lastIndexOf(java.lang.Object);
de
25. public abstract java.util.ListIterator<E> listIterator();
26. public abstract java.util.ListIterator<E> listIterator(int);
27. public abstract java.util.List<E> subList(int, int);
28.
Arraylist
ca
public default java.util.Spliterator<E> spliterator();
gA
● ArrayList allows duplicates and it is implemented as a resizable array.
● ArrayList elements will be stored internally using indexing notation.
tin
Array vs Vector
eT
Vector
Th
ca
gA
tin
es
eT
Th
Array vs LinkedList
y
m
de
ca
gA
tin
es
eT
Th
●
LinkedList
● LinkedList allows duplicates and internally implements a doubly-linked list data
structure.
● LinkedList elements will be stored internally using node representation.
● It is fast to insert or delete the elements, but slow for accessing the elements.
Stack
● Stack is a legacy subclass of vector and its methods are synchronized, so stack
objects can’t be accessed by multiple threads at a time.
● Stack has important operations like peek(), pop(), push(), search() and other
operations are same as Vector. It is a and not in use.
y
Duplicate Vaue Yes Yes Yes
m
Null Value Yes Yes Yes
de
Sequential Access Yes Yes Yes
ca
List Iterator
Enumeration
Yes
No
Yes
No
Yes
Yes
gA
Index Representation Yes No Yes
https://stackoverflow.com/questions/2113216/which-is-more-efficient-a-for-each-loop-or-an-it
erator
Iterator
● used to iterate or traverse or retrieve a Collection or Stream object’s elements one by
one and called a Java Cursor is an Iterator.
Methods in Iterator
y
m
de
ca
gA
Problem with Iterator
● In CRUD Operations, it does NOT support CREATE and UPDATE operations.
● only Forward direction.
tin
ListIterator
es
Iterator that is used to traverse all types of lists including ArrayList, Vector, LinkedList, Stack,
etc. It is available since Java 1.2. It extends the iterator interface.
eT
● bi-directional traversal.
● four CRUD operations(Create, Read, Update, Delete)
● Cursor concept.
Th
Methods in ListIterator
y
m
de
Iterator vs ListIterator
ca
gA
tin
es
eT
Th
Spliterator
● Spliterator == Splittable Iterator
● it can split some source, and it can iterate it too. (2 balanced)
● trySplit is for. Splitting is needed for parallel processing.
y
m
de
ca
package thetestingacademy.collections.list;
gA
import java.util.ArrayList;
import java.util.Spliterator;
tin
import java.util.stream.Stream;
al.add(1);
al.add(2);
al.add(-3);
al.add(-4);
al.add(5);
// getting Spliterator object on al
Spliterator<Integer> splitr1 = al.spliterator();
// estimateSize method
System.out.println("estimate size : " +
splitr1.estimateSize());
// getExactSizeIfKnown method
System.out.println("exact size : " +
splitr1.getExactSizeIfKnown());
// Split
y
System.out.println(n));
m
}
de
System.out.println("\nOutput from splitr1: ");
splitr1.forEachRemaining((n) -> System.out.println(n));
ca
ArrayList<Integer> tempList = new ArrayList<>();
gA
while(splitr1.tryAdvance((n) -> tempList.add(Math.abs(n))));
Spliterator<Integer> splitr2 = tempList.spliterator();
while(splitr2.tryAdvance((n) -> System.out.println(n)));
tin
}
}
es
eT
ConcurrentModificationException
● Can’t add to the List while iterating.
Th
Set
y
● Interface, java.util.Set
● Unique Only
m
● If o1.equals(o2) Only one will be in the List
● Set interface has the following concrete subclasses:
de
○ o HashSet
○ o LinkedHashSet
○ o TreeSet .
ca
gA
tin
es
eT
HashSet
Th
de
● LinkedHashSet is a subclass of HashSet.
● It stores the data in the order as added by the user. A,B,C -> ABC
TreeSet
ca
● It stores the elements in a sorted order. - 23,45,1 -> A,Z,B -> ABz, s1, s2, s3 -> It
won’t able -> Collections.srot
● compareTo() method is used to identify the object uniquely and to manage the order
gA
of elements in TreeSet.
● The object you are adding in the TreeSet must be the subtype of Comparable
interface.
● If object is not the subtype of Comparable, then it will throw an exception at
tin
runtime
java.lang.ClassCastException
● TreeSet allows storing elements of similar type only.
es
NavigableSet
● NavigableSet is an interface added in Java 6.
● It is a subtype of SortedSet.
● Its functionality is almost similar to TreeSet except it provides some extra methods for
easy navigation.
● Elements from NavigableSet can be accessed in both forward and reverse order.
y
m
de
ca
gA
tin
es
eT
Th
Comparable vs Comparator
Comparable object is capable of comparing itself with another object. The class itself must
implements the java.lang.Comparable interface to compare its instances.
Comparator is external to the element type we are comparing. It’s a separate class
CompareTo(??)
Compare
y
m
de
ca
gA
tin
Queue
● Added interface in Java 5.
es
Null Value
ca
Duplicate Vaue No
Yes
No
Yes
No
No
gA
Synchronized No No No
tin
List Iterator No No No
es
Enumeration No No Yes
Index Representation No No No
eT
y
SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap
m
● Map hm = new HashMap();
● Map interface has following concrete sub classes:
○ o HashMap
de
○ o LinkedHashMap
○ o TreeMap
○ o Hashtable
ca
gA
tin
es
eT
Th
y
m
de
HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation
of the Map interface of Java. It stores the data in (Key, Value) pairs.
ca
No Duplicate Key on HashMap
gA
LinkedHashMap is just like HashMap with an additional feature of maintaining an order of
elements inserted into it.
tin
The TreeMap in Java is used to implement the Map interface and NavigableMap along with
the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a
Comparator provided at map creation time, depending on which constructor is used.
es
eT
Th
Th
eT
es
tin
gA
ca
de
m
y
y
m
de
ca
gA
HashTable
● By using TreeMap
● By using LinkedHashMap
● Sort HashMap by Values
● Sort HashMap by Values using Comparator Interface
y
m
de
ca
gA
tin
● Arrays are always of fixed size, Collection, size can be changed dynamically as per
need.
●
● Arrays can only store homogeneous or similar type objects, but in Collection,
heterogeneous objects can be stored.
●
● Arrays cannot provide the ?ready-made? methods for user requirements as sorting,
searching, etc. but Collection includes readymade methods to use
y
What is the difference between Set and Map?
m
● Set contains values only whereas Map contains key and values both.
● Set contains unique values whereas Map can contain unique Keys with duplicate
values.
de
● Set holds a single number of null value whereas Map can include a single null key
with n number of null values.
ca
What is the difference between HashMap and Hashtable?
gA
tin
es
eT
y
m
de
.
ca
gA
How to synchronize List, Set and Map elements?
The default size of load factor is 0.75. The default capacity is computed as initial capacity *
load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
Th
y
Generics
m
● Introduction to Generics, Generics Class
● Implementing Generics for the Custom List
● Examples
de
"Generics allow the reusability of code, where one single method can be used for different
data-types of variables or objects."
ca
idea is to allow different types like Integer, String, … etc and user-defined types to be a
parameter to methods, classes, and interfaces.
gA
tin
es
eT
Th
MaxtTheerGeneric Demo
Th
eT
es
tin
gA
ca
de
m
y
Th
eT
es
tin
gA
ca
de
m
y
Multithreading
1. Multi Tasking
a. Multi Thread
b. Multi Processing
y
Multitasking
m
● CPU executes multiple jobs by switching among them.
● typically using a small-time quantum, and these switches occur so frequently that the
users can interact with each program while it is running.
de
ca
gA
tin
es
Multi Processing:
● Process is a program.
eT
○ Running PPT
○ Running Zoom
○ Running WhatsApp
● System Level concept. CPU level, Raspberry Pi 1 Single CPU
● They will have different memories (written in different languages).
● They can share data, but it is a very complex process.
● Context switch or control is difficult. (P1 will ask P2, P3 for permission)
Multi Threading:
● Thread is part of Program
● Thread is a sub process.
● E.g. Zoom,
○ SP1, SP2, SP3 three sub processes each are Thread
○ SP1 - Audio transfer
○ SP2 - Video Recordings
○ SP3 - Chat
y
● Application level
m
● They can share the memories
● They can do it easily in threads.
● Switching to control in Threads is easy. ( T1 -> T2)
de
-
- ca
Bank Application allows multiple users to login, bank balance, withdraw amount.
gA
tin
es
eT
Th
Thread t = Thread.currentThread();
System.out.println(t);
for (int i = 0; i < 10; i++) {
System.out.println(i+" - "+t.getName());
System.out.println(i+" - "+t.getPriority());
Thread.sleep(5000);
}
y
}
}
m
de
ca
gA
tin
es
eT
Th
y
There are two ways you can create the Threads in Java.
m
1. Extend Thread
2. Runnable
de
package thetestingacademy.multithreading;
ca
public class Task03 {
public static void main(String[] args) {
gA
Worker worker = new Worker();
worker.start();
// Where is the Start ?
tin
}
}
eT
@Override
public void run() {
Th
Why don’t we call run() method directly, why call start() method?
● We can call run() method if we want but then it would behave just like a normal
Th
● public Thread():
Creates a new Thread object. When started, then run() will be invoked from the
current object.
● public Thread(String);
Creates a new Thread object by specifying the name.
● public Thread(Runnable);
Creates a new Thread object. When started then run() will be invoked from specified
Runnable object.
y
● public Thread (Runnable, String);
m
Creates a new Thread object by specifying the Runnable object and thread name.
de
● public Thread(ThreadGroup, Runnable);
Creates a new Thread object by specifying the threadgroup Runnable object.
●
●
ca
public Thread(ThreadGroup, Runnable, String);
gA
Creates a new Thread object by specifying the ThreadGroup, Runnable object and
thread name.
tin
es
eT
Th
y
m
de
ca
Constants from Thread Class
● static final int MIN_PRIORITY Constant represents minimum priority of a thread
● static final int NORM_PRIORITY Constant represents normal priority of a thread
gA
● static final int MAX_PRIORITY Constant represents maximum priority of a thread
Concurrency refers to the ability of a system to handle multiple tasks or threads at the same
ca
time, allowing them to be executed independently and asynchronously.
Concurrency enables a system to perform multiple tasks simultaneously, but it does not
gA
necessarily mean that the tasks are executed simultaneously.
For example, a web server can handle multiple client requests concurrently, but each
request is handled by a single thread and the server may not be able to process all the
tin
Parallelism enables a system to perform multiple tasks at the same time, rather than one at
eT
a time.
For example, a parallel program can use multiple cores or processors to perform a
large computation in less time.
Th
In summary, concurrency enables a program to handle multiple tasks at the same time,
but it does not necessarily mean that the tasks are executed simultaneously.
Parallelism enables a program to execute multiple tasks simultaneously, using multiple cores
or processors.
y
m
de
ca
gA
Synchronous vs Asynchronous
tin
Synchronous operations block the execution of the program or system until the operation
is completed.
es
This means that the program or system will not execute any other code or perform any other
tasks until the current task is completed.
eT
This can lead to a situation where the program or system is "stuck" waiting for an operation
to complete, and this can make the program or system unresponsive or slow.
Th
y
m
de
Asynchronous operations, on the other hand, do not block the execution of the program or
system.
ca
The program or system can continue to execute other code or perform other tasks while an
asynchronous operation is in progress.
gA
This can make the program or system more responsive and efficient, because it can perform
multiple tasks at the same time.
tin
In summary, synchronous operations block the execution of a program or system until the
operation is completed, while asynchronous operations do not block the execution and allow
the program or system to continue running while the operation is in progress.
es
eT
Th
Thread Priority
y
m
de
ca
gA
tin
es
eT
Th
1. Create a Thread.
2. Start the Thread ( th.start() ) , T1, T2.
3. Initial state will be ready TO Run (waiting for CPU).
y
4. Thread scheduler selects the t1
m
● New - Instance of thread created which is not yet started by invoking start() it will be.
de
● Runnable - After Invocation of start() and before it is selected to be run by the
scheduler.
● Running - After the thread scheduler has selected it.
●
● ca
Non-runnable - Thread alive, not eligible to run.
Terminated - run() method has exited.
gA
tin
es
eT
Th
y
m
de
● ca
Synchronization
Lock on an Object.
gA
tin
es
eT
class Pramod{
y
ArrayList al = new ArrayList();
m
void show(){ ...
synchronized(al){ ... } ...
}
de
}
ca
Important points for the Synchronization
gA
● Case 1
● Case 2
● Case 3
● Case 4
● Case 5
tin
● Case 6
es
eT
Deadlocks
Th
y
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
m
try {
de
Thread.sleep(100);
} catch (Exception e) {
}
2");
ca synchronized (resource2) {
System.out.println("Thread 1: locked resource
gA
}
}
}
};
tin
try {
Thread.sleep(100);
Th
} catch (Exception e) {
}
synchronized (resource1) {
System.out.println("Thread 2: locked resource
1");
}
}
}
};
t1.start();
t2.start();
}
}
Wait.
y
● immediately and the current thread will be moved to WAIT state.
m
● Following are the wait() methods defined in Object class:
○ o public final void wait()
○ o public final native void wait(long ms)
de
○ o public final void wait(long ms, int ns)
● If you call wait() method on unlocked object then
java.lang.IllegalMonitorStateException
●
ca
will be thrown at runtime
package thetestingacademy.multithreading.synchronization.WaitDemo;
gA
public class WaitDemo {
customThread.start();
customThread2.start();
}
Th
class WaitForMe {
y
// for (int i = 1; i <= 5; i++) {
// System.out.println(th.getName() + " - show -" + i);
m
// try {
////this.wait(1000);
de
// al.wait(1000);
// } catch (Exception ex) {
// System.out.println(ex);
// }
//
//
// }
ca
}
}
gA
}
tin
@Override
Th
● When you call notifyAll() method on any locked object then following task will
happen:
○ All or some required number of threads as per the requirement which are in
WAIT state will be picked.
○ Checks whether the resources released are available or not.
○ If resources are available then the threads acquire the resources and goes to
y
READY TO RUN state.
○ If resources are not available then the threads go to BLOCKED state.
m
de
Code sample at ATBNotes.zip
Join()
ca
gA
● This method will be used to join one thread at the end of another thread.
● In Main thread -> t1.join()
○ Main thread will be joined at the end of t1.
● In t1 thread -> t2.join()
tin
Thread Pool
eT
● A thread pool in Java is a collection of worker threads that are used to execute
multiple tasks concurrently.
● The main advantage of using a thread pool is that it allows the program to reuse
threads, which can improve performance and reduce the overhead of creating and
Th
destroying threads.
● In a thread pool, a fixed number of worker threads are created and are managed by a
thread pool executor. When a task is submitted to the thread pool, it is placed in a
task queue and is executed by an available worker thread. Once a task is completed,
the worker thread is returned to the thread pool and is available for executing another
task.
● Java provides the Executor framework, which simplifies the task of creating and
managing thread pools. The Executor interface has a single execute() method, which
is used to submit tasks to the thread pool
Thread Local
ThreadLocal is a class in the Java standard library that allows you to create variables that
are specific to a single thread. These variables are called "thread-local" variables, because
they are local to the thread that accesses them.
y
Instance variables are more prone to the Thread Safty, Local variables are always safe.
m
class MyThreadLocal {
private static ThreadLocal<Integer> myThreadLocal = new
de
ThreadLocal<>();
public static void set(Integer value) {
myThreadLocal.set(value);
}
ca
public static Integer get() {
return myThreadLocal.get();
gA
}
}
tin
MyThreadLocal.set(10);
System.out.println(MyThreadLocal.get()); // 10
es
It's important to note that each thread will have its own copy of the thread-local variable, so
the value of the thread-local variable set by one thread will not affect the value of the
eT
For example, ThreadLocal can be used to store a user's session information in a web
Th
application, where each user's session information is specific to the thread that is handling
the user's request.
y
m
de
ca
gA
tin
es
eT
Th
● A finalizer thread is a special type of thread in Java that is used to run the finalize()
method of an object before it is garbage collected.
● The finalize() method is a protected method that is defined in the Object class and
can be overridden by subclasses to perform cleanup tasks, such as releasing
resources or closing open file handles.
y
m
de
ca
In this example, the finalize() method is used to delete a file when the MyResource object is
eligible for garbage collection.
gA
However, it's important to note that the finalize() method is not guaranteed to be run before
an object is garbage collected, and it's not guaranteed to be run at all.
So, it's not recommended to rely on finalize() method to release resources, instead use
tin
it's not recommended to use finalize() method for critical tasks, because it's not
guaranteed to be run and it might cause performance issues.
eT
Yes, we can synchronize a run() method in Java, but it is not required because this method
has been executed by a single thread only.
If we don't override run() method, compiler will not flash any error and it will execute run()
method of Thread class that has empty implemented, So, there will be no output for this
thread.
sleep() method can be used to pause the execution of the current thread for a specified time
in milliseconds.
Wait() method releases lock during Synchronization. Sleep() method does not release the
lock on object during Synchronization.
y
m
What is daemon thread?
de
Daemon thread in Java is a low-priority thread that runs in the background to perform tasks
such as garbage collection.
public final void setDaemon(boolean on)
ca
What is race condition in Java?
A condition in which the critical section (a part of the program where shared memory is
accessed) is concurrently executed by two or more threads.
gA
tin
es
eT
Th