-Java Notes- - TheTestingAcademy (Pramod Sir)
-Java Notes- - TheTestingAcademy (Pramod Sir)
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)
Native code generated on one OS will not run on other OS directly. Window -> exe, Mac ->
dmg, Linux, deb, pkg
es
Java Compiler is a program developed in C or C++ programming language with the name
“javac”. It will check syntactic or grammatical errors of the programs. It converts source
code to byte code.
Th
y
How to Set JAVA_HOME path in MAC - Click here
m
1. Download the JDK latest -
de
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
newer), then it should instead be:
ca
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.zshrc
3. In either case, restart your shell.
gA
brew install openjdk
tin
https://www.oracle.com/java/technologies/javase/jdk21-archive-downloads.html
eT
C:\Program Files\Java\jdk21
You can also type where java at the command prompt.
y
m
de
ca
Note for Windows users on 64-bit systems
Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'
gA
7. Click OK and Apply Changes as prompted
It is a set of various utility programs which are required for developing and executing the java
es
programs.
It is Platform dependent. Various JDKs are provided for various Operating Systems.
Following are various utility programs provided under JDK:
eT
iii. javap
iv. Jar
etc
2) Source Files
3) JRE
etc
⚠️ What is JRE?
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
y
etc
m
de
ca
gA
tin
es
eT
JDK Vs JRE
Th
y
m
de
ca
Java Editions
gA
1. Enterprise Edition - Banking, Application,Servlets, JSP, JDBC etc.
2. Micro Edition - micro devices like Mobiles,Setup Box etc
3. Standard Edition - Used to develop standalone applications using applet and swing.
tin
es
Edition Description
eT
Java SE The main edition of Java that is used for desktop and server applications. It
Th
(Standard 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
(Enterprise web and mobile applications, distributed systems, and cloud computing. It
Edition) includes components like servlets, JSPs, EJBs, JMS, JPA, and more.
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
A platform for developing rich client applications and user interfaces, with features
y
Java FX like graphics and media support, animation, and web integration. It includes a set
m
of APIs and tools for developing desktop, mobile, and web applications.
de
ca
Note that Java EE has been rebranded as Jakarta EE, as Oracle transferred ownership of
the Java EE specification to the Eclipse Foundation.
gA
Java Versions
tin
es
Java 1.2 (Java 2) Collections framework, reflection, Swing GUI toolkit, JNDI
Java 1.3 (Java 2) HotSpot JVM, Java Sound API, Bluetooth support
Java 1.4 (Java 2) Assertions, regular expressions, Java Web Start, JNI
Java 5 (Java 1.5) Generics, annotations, enhanced for loop, concurrent API
y
Java 8 (1.8) Lambda expressions, Stream API, java.time package, CompletableFuture
m
Java 9 Module system, private interface methods, JShell
de
Java 10 Local variable type inference, garbage collector improvements
ca
gA
Java 11 HttpClient API, var keyword for lambda parameters, Unicode 10.0 support
Java 16 Pattern matching for instanceof, garbage collector and JFR improvements
y
A comment that extends from the // marker to the end of the line. It
m
Single-line
// comment is ignored by the compiler and used for adding notes and
comment
explanations to the code.
de
A comment that can span multiple lines, starting with the /* marker
Multi-line
comment ca /* comment
*/
and ending with the */ marker. It is also ignored by the compiler and
Documentation /** multi-line comment, but it is specifically used for generating API
comment comment */ documentation with tools like Javadoc. It can include tags like
Javadoc comment /** can be used to describe classes, interfaces, methods, fields, etc.
Th
y
m
de
ca
gA
Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.
es
Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly
to replace licensed proprietary parts / replace with more high-performance items that only
work on specific OS] components without breaking the TCK compatibility.
eT
https://stackoverflow.com/questions/22358071/differences-between-oracle-jdk-and-openjdk
Th
y
⚠️ Which JRE will be used while compiling the Java Source File?
m
The JRE is not used for compiling Java source files, but rather the Java Development Kit
(JDK) is used, specifically the Java compiler (javac) which is included in the JDK.
de
⚠️ What will happen when I am compiling Java program without PRIVATE JRE?
Compiling a Java program does not require a PRIVATE JRE. However, if the program
ca
requires a specific version of the JRE to execute, and that version is not installed on the
system, the program may not run properly.
⚠️ What will happen when I am executing Java program without PUBLIC JRE?
tin
If a PUBLIC JRE is not installed on the system, the Java application will not be able to run.
The user will need to install a JRE before the application can be executed.
es
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.
y
⚠️Can I install multiple JRE versions in my machine?
m
Yes, it is possible to install multiple JRE (Java Runtime Environment) versions on the same
machine. It is important to manage the PATH and other environment variables correctly to
de
ensure that the correct version is used
ca
Explain the main method in Java
gA
● The main method in Java is the entry point for any Java program.
● It is a predefined method that is executed when a Java program is run, and is
required in every Java program.
tin
● The main method has a specific signature, which includes the keyword "public", the
keyword "static", the return type "void", and a parameter of type "String" array named
"args". Here is an example of the main method signature:
es
● 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.
Steps that the JVM takes to call the main method:
Th
JDK 11
✅ Keywords & Identifiers
● Simple English words which are having predefined meaning in Java Programming
Language.
● Keywords are also called Reserved Words.
● All the keywords are defined in Lower Case.
● We can’t use keywords as names for variables, methods, classes, or as any other
identifiers.
y
m
de
ca
gA
tin
es
eT
Identifiers - names those will be used to identify the programming elements like classes,
methods, variables, etc uniquely
Th
y
m
Types of Variables
There are two types of variables based on data type used to declare the variable.
de
1) Primitive Variables
2) Reference Variables
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 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(Non Primitve) Variables - Variables declared with reference data types are
y
called as 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 a 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 + 0 + 32 + 0 + 8 + 4 + 0 + 0 = 44.
ca
(00101100)₂ = (0 × 2⁷) + (0 × 2⁶) + (1 × 2⁵) + (0 × 2⁴) + (1 × 2³) + (1 × 2²) + (0 × 2¹) + (0 × 2⁰)
= (44)₁₀
gA
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
Interview QnA
Question Answer
Bitwise operators are used to perform bitwise
What is the use of bitwise operators?
operations on binary representations of integers.
What is the result type of String concatenation The result type of String concatenation operation is
y
What will happen when I try to assign int type The code will not compile because you cannot assign
m
to String type variable? Ex: String str=99; an int value to a String variable directly.
de
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
es
(explicit).
eT
What is the difference between String The String concatenation operator (+) is used to
Concatenation and Arithmetic Addition concatenate two strings, while the arithmetic addition
What are the bitwise operators available? (bitwise AND), | (bitwise OR), ^ (bitwise XOR), << (left
y
Implicit casting is done automatically by the compiler,
m
What is the difference between Implicit
while explicit casting requires the programmer to
casting and Explicit Casting?
specify the conversion explicitly.
de
The assignment operator is used to assign a value to a
ca
What is the use of assignment operator?
variable or an array element.
gA
2's complement is a way of representing negative
What is 2's Complement? integers in binary. It involves flipping all the bits and
tin
What are types of operands allowed for Arithmetic operators can be used with numeric
arithmetic operators? operands (int, long, float, double) and char operands.
eT
What is the difference between unary Unary arithmetic operators act on a single operand,
Th
arithmetic and binary arithmetic operators? while binary arithmetic operators act on two operands.
What is the syntax of Explicit casting? The syntax of explicit casting is: (datatype) value.
What are types of operands allowed for Bitwise operators can be used with integer operands
y
The instanceof operator is used to check if an object is
m
What is the use of instanceof operator?
an instance of a particular class or interface.
de
What is result type when you add two byte
The result type when you add two byte variables is int.
variables?
ca
What is result type when you add long and The result type when you add long and float variables is
gA
float variables? float.
tin
es
Question Answer
eT
What are the valid conditions for Division by a positive number or multiplication by a positive
What is the difference between String String concatenation is used to join two or more strings
Concatenation and Arithmetic Addition together, while arithmetic addition is used to add numeric
operator? values.
y
The new operator is used to allocate memory for an object
m
What is the result of new operator?
and returns a reference to that object.
de
What is the result of instanceof The instanceof operator returns true if an object is an
What will happen when I try to assign int It will result in a compilation error because they are
What is the use of assignment The assignment operator is used to assign a value to a
operator? variable.
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.
y
operators available? bitwise operation with an assignment.
m
de
2's complement is a binary representation of a signed number
What is 2's Complement?
that uses the most significant bit as a sign bit.
ca
What are types of operands allowed for
bitwise operators?
Bitwise operators can be applied to integer types: byte, short,
What is the syntax of Explicit casting? The syntax of explicit casting is: (target_type) expression.
tin
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
y
What is the difference between
larger type, while narrowing casting occurs when you convert
m
Widening and Narrowing?
a larger type to a smaller type.
de
ca ✅ Conditions and Loop
gA
If
condition -> true or false
if(condition)
tin
if(a % 2==0)
System.out.println("Value is EVEN");
eT
else
System.out.println("Value is ODD");
}
Th
// switch statement
switch(expression)
eT
{
// case statements
// values must be of same type of expression
Th
case value2 :
// Statements
break; // break is optional
y
Much improved switch accepts multiple values per case.
m
switch (itemCode) {
de
case 001, 002, 003 :
System.out.println("It's an electronic gadget!");
break;
ca
case 004, 005:
System.out.println("It's a mechanical device!");
gA
}
tin
A new keyword yield has been introduced. It returns values from a switch branch only.
es
We don’t need a break after yield as it automatically terminates the switch expression.
yield 2;
}
switch (itemCode) {
case 001 -> System.out.println("It's a laptop!");
case 002 -> System.out.println("It's a desktop!");
case 003,004 -> System.out.println("It's a mobile phone!");
y
}
m
de
ca
gA
tin
es
eT
Th
For
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>;
✅ Functions
y
m
1. No Return Type - void
2. Return Type - data -> Primitive or Ref Type
de
3. Main method overloading - Interview.
toString() method
In Java, the toString() method is a method defined in the Object class that returns a string
representation of an object.
y
hashCode() method
m
In Java, the hashCode() method is a method defined in the Object class that returns an
de
integer hash code value for an object.
The hashCode() method is implemented by converting the internal address of the object into
an integer value. If two objects are equal according to the equals() method, then they should
ca
have the same hash code.
gA
public class Person {
private String name;
private int age;
tin
}
@Override
eT
return result;
}
}
Person p1 = new Person("John", 30);
Person p2 = new Person("John", 30);
System.out.println(p1.hashCode()); // prints a number
System.out.println(p2.hashCode()); // prints the same number as p1
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
m
public Person(String name, int age) {
this.name = name;
this.age = age;
de
}
@Override
ca
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Person)) return false;
gA
Person other = (Person) obj;
return name.equals(other.name) && age == other.age;
}
}
tin
Person p1 = new Person("John", 30);
Person p2 = new Person("John", 30);
es
getClass() method,
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
public static void main(String[] args)
m
{
Test t = new Test();
System.out.println(t.hashCode());
de
t = null;
ca// calling garbage collector
System.gc();
gA
System.out.println("end");
}
@Override protected void finalize()
tin
{
System.out.println("finalize method called");
}
es
clone()method
eT
It returns a new object that is exactly the same as this object. For clone() method refer
Clone().
Th
y
System.out.println(p1 == p2); // prints false
m
Note that the clone() method only creates a shallow copy of the object, which means that it
de
only copies the references to the object's fields, rather than creating new copies of the
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.
ca 📙 Arrays in Java
gA
tin
○ o Array Construction
○ o Array Initialization
● Arrays can be constructed with multiple dimensions i.e 1-D Array, 2-D Array etc.
Th
● length
● Use a loop to traverse.
● 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.
● When you are specifying -ve value as array size then
java.lang.NegativeArraySizeException will be thrown at runtime
Multidimensional Arrays
y
● The size of the array cannot be altered(once initialized).
● JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been
m
accessed with an illegal index
de
MyClass myClassArray[];
Object[] ao,
ca
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Array of Objects
gA
Student[] arr = new Student[5];
// set the values of the array elements
numbers[0] = 10;
es
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
eT
numbers[4] = 50;
// print the values of the array elements
for (int i = 0; i < numbers.length; i++) {
Th
System.out.println(numbers[i]);
}
// prints 10, 20, 30, 40, 50
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
Enter a number: 8
Enter a number: 2
Enter a number: -1
The highest number is 8
The lowest number is 2
import java.util.Scanner;
y
m
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
de
// create an array to store the numbers
int[] numbers = new int[100];
ca
int size = 0;
if (n >= 0) {
numbers[size] = n;
size++;
es
}
} while (n >= 0);
eT
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other arrays.
y
m
de
ca
gA
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
eT
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
Th
y
● String objects are immutable objects. It means once the object is created then the
content or data of the object can't be modified.
m
● When you try to modify the contents of object then new object will be created as a
result.
de
How can String be represented?
ca
1) String class
2) StringBuffer
3) StringBuilder
gA
4) Array of Characters
5) ArrayList of Characters
tin
The reason for making strings immutable in Java is to increase efficiency, security, and
thread-safety.
eT
In this example, we create a string str1 with the value "Hello". We then concatenate the
string " World" to str1 using the concat() method, and assign the result to str2. The concat()
method does not modify str1 but creates a new string with the value "Hello World".
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
Concept of String Pool and New Operator
y
m
de
ca
gA
String class provides a wide range of functions to manipulate strings.
tin
Here are some of the most commonly used functions of the String class:
charAt(int index): Returns the character at the specified index in the string.
es
concat(String str): Concatenates the specified string to the end of the original string.
eT
contains(CharSequence s): Returns true if the string contains the specified sequence of
characters, otherwise false.
Th
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.
replace(char oldChar, char newChar): Returns a new string resulting from replacing all
occurrences of the specified oldChar with the specified newChar.
Example: "hello".replace('l', 'w') returns "hewwo".
split(String regex): Splits the string into an array of substrings based on the specified
regular expression.
Example: "hello world".split(" ") returns ["hello", "world"].
y
substring(int beginIndex, int endIndex): Returns a new string that is a substring of the
m
original string, starting from the specified beginIndex and ending at the endIndex (exclusive).
Example: "hello".substring(1, 3) returns "el".
de
toLowerCase(): Returns a new string with all characters converted to lowercase.
Example: "HELLO".toLowerCase() returns "hello".
ca
toUpperCase(): Returns a new string with all characters converted to uppercase.
Example: "hello".toUpperCase() returns "HELLO".
gA
== operator checks if two string references point to the same memory location.
tin
equals method compares the actual content of the strings, checking if they contain the same
sequence of characters.
es
characters.
● They are designed for efficient string manipulation operations, such as appending,
inserting, or deleting characters from a string.
Th
Table summarizing the most commonly used functions of StringBuilder and StringBuffer
classes in Java:
y
Function Description
m
de
append() Appends the specified character(s) or object to the end of the string.
insert()
ca Inserts the specified character(s) or object at the specified index in the string.
gA
Deletes the characters from the string between the specified start and end
tin
delete()
indices.
es
Replaces the characters in the string between the specified start and end indices
replace()
with the specified string.
y
m
de
setCharAt() Sets the character at the specified index in the string to the specified character.
Ensures that the capacity of the string builder is at least the specified minimum
tin
ensureCapacity()
capacity.
es
trimToSize() Trims the capacity of the string builder to its current length.
eT
Th
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
O/P- s = cba
public static void main (String[] args) {
String str= "Pramod", nstr="";
char ch;
System.out.print("Original word: ");
System.out.println("Pramod"); //Example word
for (int i=0; i<str.length(); i++)
{
y
ch= str.charAt(i); //extracts each character
nstr= ch+nstr; //adds each character in front of the existing
m
string
}
de
System.out.println("Reversed word: "+ nstr);
}
Palindrome
ca
gA
Input : str = "abba"
Output: Yes
tin
Input : str = "pramod"
Output: No
es
// Initializing a new boolean variable for the
// answer
boolean ans = false;
for (int i = str.length() - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
// Checking if both the strings are equal
if (str.equals(rev)) {
ans = true;
}
return ans;
}
class ReverseString {
public static void main(String[] args)
{
String input = "Pramod Sir is Owner of TheTestingAcademy";
y
m
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
de
input1.append(input);
// reverse StringBuilder input1
ca
input1.reverse();
class TheTestingAcademy {
// Reverse the letters
Th
// of the word
static void reverse(char str[], int start, int end)
{
// Temporary variable
// to store character
char temp;
while (start <= end) {
// Swapping the first
// and last character
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
// Function to reverse words
static char[] reverseWords(char[] s)
{
// Reversing individual words as
// explained in the first step
y
int start = 0;
for (int end = 0; end < s.length; end++) {
m
// If we see a space, we
// reverse the previous
de
// word (word between
// the indexes start and end-1
// i.e., s[start..end-1]
if (s[end] == ' ') {
ca
}
reverse(s, start, end);
start = end + 1;
gA
}
// Reverse the last word
reverse(s, start, s.length - 1);
tin
// Reverse the entire String
reverse(s, 0, s.length - 1);
es
return s;
}
eT
// Driver Code
public static void main(String[] args)
{
Th
y
1. No Return Type
2. Return Type
m
int add(int a, int b) {
return a + b;
de
}
int result = add(5, 3); // Calling the 'add' method with arguments 5 and 3
ca
public class Calculator {
public int add(int a, int b) {
return a + b;
gA
}
Practice -
● Prime Number
● Swap Two Numbers
● String reverse
● Take User input as array
● Maximum in Array
● Print diagonal Elements 2D array
y
📗 OOPs ( Java)
m
de
1. OOPs vs POP or PPL (Procedural oriented programming)
2. Object vs Functional
ca
gA
tin
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()
● FetchCustomer()
● Show() can also use the Customer and Primitive x (NO ENCAPSULATION)
● Data Security issues (global, local variables)
y
How to Use Oops to Build Any Modern-Day Software
m
Consider this scenario: We are developing an Automation Tester Batch System.
de
1. Identify the objects
a. Like Student, Course, Payment.
2. Describe those with details
ca
a. Data - Student -> name, id, age, address, email, course taken
b. Operations -> addStudent, deleteStudent
c. Bind them with Encapsulation (Class)
3. Establish the relationship with each other
gA
a. Student -> payment, Student -> Course, Course -> Payment
4. Now implement it via Class and Objects
tin
Abstraction Example
es
y
m
de
ca
gA
tin
es
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).
eT
abstract class
protected String color;
public Shape(String color) {
this.color = color;
}
// concrete method
public String getColor() {
return this.color;
}
// abstract method
public abstract double getArea();
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height, String color) {
super(color);
this.width = width;
y
this.height = height;
}
m
// implementation of the abstract method defined in the superclass
de
@Override
public double getArea() {
return this.width * this.height;
}
}
ca
class Circle extends Shape {
gA
private double radius;
public Circle(double radius, String color) {
super(color);
tin
this.radius = radius;
}
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)
Interface
An interface is a collection of abstract methods that must be implemented by any class that
implements the interface
Inheritance
y
1. Example with Student -> Manual , Automation
2. Extra Data members, Operations or Methods
m
de
PolyMorphism
● + operator
● Remote or on/off button poly behavior
ca
gA
Class and Objects
tin
https://docs.google.com/presentation/d/1pilgqDxrvs7KsFEOHyLBzF75Da3ZXYPvnPCHfG1
Gk4s/edit?usp=sharing
es
eT
Th
Inheritance
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
// Interface
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 (OOP), 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
}
Book s1 = new Book();
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
y
m
de
ca
gA
Important Concepts
● super()
● //1. Use of super with Variables
tin
●
● // Encapsulation
● // Polymorphism
eT
● // Abstraction
● // Access Modifiers
● // Static Keyword
Th
● //Inner Class
1. Variables
2. Blocks
3. Constructors
4. Methods
5. Inner Class
package atb.classdemo;
public class Book {
// Instance Variables
int id; // -> Instance Primitive variable
String name; // -> Instance Reference variable
String author;
// Block
{
System.out.println("I am block");
y
}
m
// Default constructor
Book(){
de
System.out.println("Default Con");
}
// Parameters constructor
ca
public Book(int id, String name, String author) {
this.id = id;
this.name = name;
gA
this.author = author;
}
// Method
tin
void show(){
System.out.println("Data");
}
es
@Override
public String toString() {
eT
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
Th
// Inner Classe
class Publisher{
String name;
void show(){
System.out.println(Book.this.name);
}
}
}
Type of Variables
1. Instance Variable
a. Primitive variable
b. Reference variable
2. Local Variables
3. Static Variables
package atb.classdemo.staticdemo;
y
m
public class StaticDemo {
int a = 10;
static int b= 20;
de
void m1(){
System.out.println(a);
System.out.println(b);
}
ca
static void m2(){
//System.out.println(a);
gA
System.out.println(b);
}
}
tin
package atb.classdemo.staticdemo;
eT
public class Main {
public static void main(String[] args) {
Th
StaticDemo.m2(); // How?
}
}
Class Loaders
y
public getter and setter methods to access and modify the data.
m
public class Student {
de
// data fields are private
private String name;
private int age;
ca
private String address;
// public getter and setter methods for each field
public String getName() {
gA
return this.name;
}
public void setName(String name) {
this.name = name;
tin
}
public int getAge() {
return this.age;
es
}
public void setAge(int age) {
eT
this.age = age;
}
public String getAddress() {
Th
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
}
Th
eT
es
tin
gA
Access Modifier
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
ca Abstraction
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.
abstract
tin
// Output
es
Static Keyword
The static keyword in Java is mainly used for memory management. It used to share the
same variable or method of a given class.
The static keyword is a non-access modifier in Java that is applicable for the following:
● Blocks
● Variables
● Methods
● Classes
Static blocks, data members, methods, and classes in Java with an example.
1. Class:
A class is a blueprint for creating objects. It defines the properties (data members) and
behaviors (methods) that the objects created from the class will have.
2. Data Members:
Data members (also known as instance variables) are variables that hold the data/state of
an object. These can be instance variables or static variables.
3. Methods:
Methods define the behaviors or functions that an object can perform. These can be
y
instance methods or static methods.
m
4. Static Block:
A static block is a block of code that gets executed when the class is loaded into memory. It
de
is used to initialize static data members.
ca
Nested Class
Class within Class is called Nested class
gA
class OuterClass
{
...
class NestedClass
tin
{
...
}
es
}
eT
Th
y
m
de
class OO{
static int o =100;
int a = 900;
es
}
}
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.
1. Inner classes can use the outer data and members.
2. Inner class members can’t be used directly, use Inner class object.
3. Inner class use outside with
Outer.Inner io2 = new Outer().new Inner();
y
4. Static declaration is not allowed in the inner class
5. Static Inner class, Instance Inner class, Local Inner class, Anonymous inner class
m
There are 4 ways you can create a Class
de
1. Inner Class
2. Method Level Inner Class
3. Nested Class
ca
4. Anonymous Class
// inner class
public class Engine {
// inner class fields
es
this.fuelType = fuelType;
}
// inner class method
public void start() {
System.out.println("Engine starting...");
}
}
// outer class constructor
public Car(String make, String model) {
this.make = make;
this.model = model;
}
// outer class method
public void drive() {
System.out.println("Driving the car...");
}
}
//
Car myCar = new Car("Toyota", "Camry");
Car.Engine engine = myCar.new Engine(200, "Gasoline");
y
engine.start();
m
de
ca
Upcasting and Downcasting in Class
You can assign a subclass object to the super type reference variable directly. This process
gA
is called UPCASTING.
class Parent{}
tin
parent=child;
// Valid -> Upcasting
Th
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
public void test_method()
m
{
........
de
........
}
}
ca
● An anonymous class has access to the members of its enclosing class.
● An anonymous class cannot access local variables in its enclosing scope that are not
gA
declared as final or effectively final.
● constructors can not be declared in an anonymous class.
●
tin
es
eT
Th
package thetestingacademy.oops.anonymousclass;
y
Student student = new Student() {
@Override
m
public void setId() {
System.out.println(id);
}
};
de
student.setId();
}
}
ca
interface Student{
int id = 11;
void setId();
gA
}
@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
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
}
ca
Solve the three problems in the above program.
1. Array.
2. 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;
public class Ex04 {
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
Navigating the Exception Flows from One Method to OTHER
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
}
private static void extracted() {
eT
try {
// String name = null;
// name.length();
Th
Integer[] i = new Integer[2];
System.out.println(i[3]);
} catch (NullPointerException e) {
System.out.println("Null");
e.printStackTrace();
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out");
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
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
void m1() throws Exception
void m1() throws Error
void m1() throws Throwable
void m1() throws Object //Not Ok
Some Errors Asked in the Interview :
1) NoSuchMethodError:main
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.
m
● Insertion and deletion are heavy.
● No built-in support for sorting, searching.
de
We prefer below classes and Interfaces in place of Arrays.
ca
Legacy Classes
● Vector
gA
● Stack
● Properties
● Hash table
● Dictionary
tin
Legacy Interface
● Enumeration (cursor)
es
Enumeration
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
● Ordered Collection
● Control over the insertion
● List allows Duplicate.
y
Way to Initialize
m
● List<String> fruites = List.of("orange","apple");
● ArrayList - Underline Array - Get element is easy, inserting, Delete is Costly.
● LinkedList - LinkedList
de
● Vector - Array
ca
Most of the time, programmers prefer ArrayList over Vector because ArrayList can be
synchronized explicitly using Collections.synchronizedList.
gA
List Functions
Use the javap java.util.List
tin
Arraylist
y
● It is fast to access the elements, but slow to insert and delete the elements.
m
de
Array vs Vector
Vector
ca
● Vector allows duplicates, and it is implemented as a resizable array.
● Vector is a legacy class and elements will be stored internally using indexing
gA
notation.
● Vector methods are synchronized, so vector objects can’t be accessed by
multiple threads at a time.(Slow)
tin
es
eT
Th
y
m
de
ca
gA
tin
es
eT
Th
Array vs ArrayList
y
m
de
ca
gA
Array vs LinkedList
tin
es
eT
Th
y
m
de
●
LinkedList
ca
● LinkedList allows duplicates and internally implements a doubly-linked list data
structure.
● LinkedList elements will be stored internally using node representation.
gA
● It is fast to insert or delete the elements, but slow for accessing the elements.
tin
es
eT
Th
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
m
de
Task
ca ArrayList LinkedList Vector Stack
gA
Order User added User added User added
Enumeration No No Yes
Th
Iterator
● used to iterate or traverse or retrieve a Collection or Stream object’s elements one by
y
one and called a Java Cursor is an Iterator.
m
three cursors in Java.
de
1. Iterator - For all
2. Enumeration - V
3. ListIterator - List
ca
Methods in Iterator
gA
tin
es
eT
ListIterator
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.
● bi-directional traversal.
● four CRUD operations(Create, Read, Update, Delete)
● Cursor concept.
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;
public class SpliteratorDemo {
es
ArrayList<Integer> al = new ArrayList<>();
// Add values to the array list.
Th
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
Spliterator<Integer> splitr1_split = splitr1.trySplit();
// If splitr1 could be split, use splitr2 first.
if(splitr1_split != null) {
System.out.println("Output from splitr2: ");
splitr1_split.forEachRemaining((n) ->
y
System.out.println(n));
m
}
// Now, use the splitr
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
y
Set
m
● Interface, java.util.Set
● Unique Only
● If o1.equals(o2) Only one will be in the List
de
● Set interface has the following concrete subclasses:
○ o HashSet
○ o LinkedHashSet
ca○ o TreeSet .
gA
tin
es
eT
HashSet
● It is fast for searching and retrieving elements.
● It does not maintain any order for stored elements.> A, B, C -> B,C, A, ABC, BAC
y
m
LinkedHashSet
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.sort
● 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
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
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
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
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
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
es
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 {
public static void main(String[] args) {
tin
WaitForMe waitForMe = new WaitForMe();
es
customThread.start();
customThread2.start();
}
Th
}
class WaitForMe {
// synchronized void show(){
synchronized void show() {
Thread thread = Thread.currentThread();
for (int i = 0; i < 5; i++) {
System.out.println(" Name -> " + thread.getName() + " -> " +
i);
try {
this.wait(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Blocking a Block or Third Party Object
// void show() {
// Thread th = Thread.currentThread();
// ArrayList al = new ArrayList();
// synchronized (al) {
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