[Java Notes]-TheTestingAcademy by Pramod
[Java Notes]-TheTestingAcademy by Pramod
Ref - https://www.scaler.com/topics/why-java-is-not-100-object-oriented/
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
[Java Notes] - TheTestingAcademy (Pramod Sir)
● Simple.
● Object-Oriented.
● Platform Independent.
● Portable.
● Robust.
● Secure.
● Interpreted.
● Multi-Threaded
Native code generated on one OS will 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 “javac”. It will
check syntactic or grammatical errors of the programs. It converts source code to byte code.
6. In the Variable Value field, enter your JDK or JRE installation path .
If the path contains spaces, use the shortened path name. For example,
C:\Progra~1\Java\jdk1.8.0_65
It is a set of various utility programs which are required for developing and executing the java
programs.
[Java Notes] - TheTestingAcademy (Pramod Sir)
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
ii. java
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 etc
JDK Vs JRE
[Java Notes] - TheTestingAcademy (Pramod Sir)
Java Editions
Edition Description
The main edition of Java that is used for desktop and server applications. It includes
Java SE (Standard
the Java language, JVM, class libraries, and tools for developing, testing, and
Edition)
deploying Java applications.
A set of specifications and APIs for developing enterprise applications, including web
Java EE (Enterprise
and mobile applications, distributed systems, and cloud computing. It includes
Edition)
components like servlets, JSPs, EJBs, JMS, JPA, and more.
Java ME (Micro A platform for developing applications for mobile and embedded devices, like
Edition) phones, PDAs, and set-top boxes. It includes a subset of the Java SE APIs and tools,
as well as additional libraries for mobile-specific features like user interfaces and
[Java Notes] - TheTestingAcademy (Pramod Sir)
networking.
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
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
Java 11 HttpClient API, var keyword for lambda parameters, Unicode 10.0 support
Java 16 Pattern matching for instanceof, garbage collector and JFR improvements
Java Comments
A comment that extends from the // marker to the end of the line. It is
Single-line comment // comment ignored by the compiler and used for adding notes and explanations
to the code.
Multi-line comment /* comment */ A comment that can span multiple lines, starting with the /* marker
and ending with the */ marker. It is also ignored by the compiler and
used for adding longer explanations or temporarily disabling code.
[Java Notes] - TheTestingAcademy (Pramod Sir)
A comment that begins with /** and ends with */. It is similar to a
Documentation /** comment multi-line comment, but it is specifically used for generating API
comment */ documentation with tools like Javadoc. It can include tags like
Javadoc comment /** be used to describe classes, interfaces, methods, fields, etc. and their
Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.
Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to replace
[Java Notes] - TheTestingAcademy (Pramod Sir)
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
⚠️ 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 (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?
Compiling a Java program does not require a PRIVATE JRE. However, if the program 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?
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.
● 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.
● 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:
● public static void main(String[] args) {
● // code to be executed
●}
● 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:
JDK 11
● 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.
[Java Notes] - TheTestingAcademy (Pramod Sir)
Identifiers - names those will be used to identify the programming elements like classes, methods,
variables, etc uniquely
Variables
Types of Variables
There are two types of variables based on data type used to declare the variable.
1) Primitive Variables
2) Reference Variables
[Java Notes] - TheTestingAcademy (Pramod Sir)
Some Points
● 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.
● Variables in Java are strongly typed; thus they all must have a data type declared with their
identifier
Primitive Variables
● Variables declared with primitive data types are called primitive variables.
●[JavaintNotes] - TheTestingAcademy
a; int b = 99; double d1; double d2=9.9; (Pramod Sir)
Reference Variables - Variables declared with user defined data types are called as reference variables.
String str1;
String str2 = “TheTestingAcademy”;
● 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.
Data Types
There are eight primitive data types in Java, which are categorized into four groups: integer, floating-point,
character, and boolean.
When the statement byte b = 10 is executed in Java, the JVM creates a variable named b of type byte and
assigns it the value 10.
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:
Reference data types are used to store complex objects, such as arrays and classes. These data types are
created using predefined or custom classes.
[Java Notes] - TheTestingAcademy (Pramod Sir)
User Defined Data types
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 called as reference
variables
✅ Constants
● Special variable whose value can't be modified during the program execution.
● Constant is also called as final variable.
B) goto
Which of the following are valid Java keywords? E) struct
Q3 A) instanceof B) goto C) null D) assert E) struct F) true G) I) virtual
Long H) false I) virtual J) signed J) signed
What is an identifier? What are the rules to follow to define identifier are: i) It should start with a
Q5
an identifier? letter or underscore, ii) No
What is data type? How many types of data types variable can hold. There are two types
Q6
available? of data types: i) Primitive data types,
Q15 What are the possible values can be used for boolean type? true or false
Q20 What is the default value of local variable? variable. It must be initialized before
use.
How can I declare multiple variable of same type in one can be declared in one statement by
Q22
statement? separating each variable name with a
comma.
How can I declare and initialize multiple variables of same statement by separating each
Q24
type in one statement? variable name with a comma and
when it is declared.
Q26 When will the memory be allocated for the variables? Memory for variables is allocated at
UNICODE Characters
Practice QnA
Question 1
int enum=9;
System.out.println(enum);
Question 2
char char='A'; System.out.println(char);
✅ Literals
String literals A sequence of characters enclosed in double quotes, such as "hello world"
Null literals A special literal that represents a null reference or a null value
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
061 -> 49
061 = (0 × 8²) + (6 × 8¹) + (1 × 8⁰) = 49
https://www.rapidtables.com/convert/number/octal-to-decimal.html
[Java Notes] - TheTestingAcademy (Pramod Sir)
Question Answer
How many boolean literals are There are only two boolean literals available, which are true and
available? false.
Can we store empty character in char No, you cannot store an empty character in a char type variable
UNICODE value is found in String The string "UNICODE of A is A" will be displayed because \u0041
\u0041";
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" will
Sequence is found in String Literal? be displayed on the next line because \n represents the newline
Null literal
● 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
● 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()
Remember this
[Java Notes] - TheTestingAcademy (Pramod Sir)
Type Casting
Source type is not same as destination type then source type must be converted to
destination type.
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
Logical Operators
[Java Notes] - TheTestingAcademy (Pramod Sir)
Logical OR and Logical AND ( || , &&
new Operator
● new operator is used to create the new object for class.
● It returns of the address of newly created object.
● String s1 = new String(“Pramod”);
instanceof Operator
● It is used to check whether the given object belongs to specified class or not.
● Result of instanceof operator is boolean value.
● It returns true if given object belongs to specified class otherwise false.
● It is also called aCOMPARISONERATOR.
● System.out.println(s1 instanceof Object);
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
[Java Notes] - TheTestingAcademy (Pramod Sir)
https://bit-calculator.com/bit-shift-calculator
1. 7+ (6 + 5 *3) - 4/2
2. boolean b = (boolean)1; b)
3. String str=(String)99;
Interview QnA
Question Answer
What is the result type of String concatenation The result type of String concatenation operation is
String type variable? Ex: String str=99; int value to a String variable directly.
What are types of operands allowed for Comparison operators can be used with numeric and
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
What is 2's Complement? in binary. It involves flipping all the bits and adding 1 to
the result.
What are types of operands allowed for Arithmetic operators can be used with numeric operands
What is the difference between unary arithmetic Unary arithmetic operators act on a single operand, while
and binary arithmetic operators? 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 Bitwise operators can be used with integer operands (int,
What is result type when you add long and float The result type when you add long and float variables is
variables? float.
[Java Notes] - TheTestingAcademy (Pramod Sir)
Question Answer
What are the valid conditions for "Infinity" Division by a positive number or multiplication by a positive
output? infinity.
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.
What is the use of bitwise operators? Bitwise operators are used to perform operations at the bit level.
What is the use of assignment operator? The assignment operator is used to assign a value to a 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.
What are types of operands allowed for Bitwise operators can be applied to integer types: byte, short, int,
What is the syntax of Explicit casting? The syntax of explicit casting is: (target_type) expression.
The prefix form evaluates and returns the value after the
What is the difference between prefix and
operation, while the postfix form evaluates and returns the value
postfix forms of decrement operator?
before the operation.
If
condition -> true or false
if(condition)
{ // Statements (IF BLOCK) }
if(a % 2==0)
System.out.println("Value is EVEN");
else
System.out.println("Value is ODD");
}
● [ ] Java switch expressions must be of byte, short, int, long(with its Wrapper type), enums and
String. Beginning with JDK7, it also works with enumerated types (Enums in java), the String class,
and Wrapper classes.
● [ ] The value for a case must be constant or literal. Variables are not allowed.
// switch statement
switch(expression)
{
// case statements
// values must be of same type of expression
case value1 : expression = value 1 ->
// Statements
break; // break is optional
case value2 :
// Statements
break; // break is optional
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.
switch (itemCode) {
case 001 -> System.out.println("It's a laptop!");
case 002 -> System.out.println("It's a desktop!");
[Java
case Notes]
003,004 - TheTestingAcademya(Pramod
-> System.out.println("It's Sir)
mobile phone!");
}
[Java Notes] - TheTestingAcademy (Pramod Sir)
For
1.
While
● condition of while statement is mandatory and must be boolean type
[Java Notes] - TheTestingAcademy (Pramod Sir)
Do While
● 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
● then the block will not be executed.
● for and while statement are also called as Entry Controlled Loop.
● If you want to execute the block at least once then use do-while statement
In the case of do-while first block of statements will be executed and then condition will be verified.
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
1. No Return Type - void
2. Return Type - data -> Primitive or Ref Type
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.
public class Person {
[Java
private Notes]
String name;- TheTestingAcademy (Pramod Sir)
private int age;
@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}
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 an integer
value. If two objects are equal according to the equals() method, then they should have the same hash
code.
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + age;
return result;
}
}
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.
[Java Notes] - TheTestingAcademy (Pramod Sir)
The default implementation of the equals() method in the Object class compares the memory addresses of
the objects
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Person)) return false;
Person other = (Person) obj;
return name.equals(other.name) && age == other.age;
}
}
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.
t = null;
System.out.println("end");
}
clone()method
It returns a new object that is exactly the same as this object. For clone() method refer Clone().
@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 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.
📙 Arrays in Java
[Java Notes] - TheTestingAcademy (Pramod Sir)
● Array is a collection of data which is of similar type.
● Array is also called as Homogeneous data structure.
● Elements of an array will be stored in contiguous memory locations.
● Arrays are objects in Java.
● Three tasks to remember while you are working with arrays:
○ o Array Declaration
○ o Array Construction
○ o Array Initialization
● Arrays can be constructed with multiple dimensions i.e 1-D Array, 2-D Array etc.
● 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
MyClass myClassArray[];
Object[] ao,
// Array of Objects
Student[] arr = new Student[5];
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
import java.util.Scanner;
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other
arrays.
// 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.
● String is a built-in class in java.lang package.
● String is final class, so you can't define the subclass for String class.
● String class implements the following interfaces:
○ java.io.Serializable
○ java.lang.Comparable
○ java.lang.CharSequence
●[Java Notes]
String class - TheTestingAcademy
has following variable to hold data. (Pramod Sir)
○ private final char value[];
● String objects are immutable objects. It means once the object is created then the
content or data of the object can't be modified.
● When you try to modify the contents of object then new object will be created as a
result.
1) String class
2) StringBuffer
3) StringBuilder
4) Array of Characters
5) ArrayList of Characters
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
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.
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.
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"].
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".
toLowerCase(): Returns a new string with all characters converted to lowercase.
[Java Notes] - TheTestingAcademy (Pramod Sir)
Example: "HELLO".toLowerCase() returns "hello".
== operator checks if two string references point to the same memory location.
equals method compares the actual content of the strings, checking if they contain the same sequence of
characters.
● StringBuilder and StringBuffer are classes that provide mutable sequences of characters.
● They are designed for efficient string manipulation operations, such as appending, inserting, or
deleting characters from a string.
● The main difference between StringBuilder and StringBuffer is that StringBuilder is not thread-
safe, while StringBuffer is thread-safe.
● StringBuilder is faster and more efficient in single-threaded environments, while StringBuffer is
safer to use in multi-threaded environments.
Table summarizing the most commonly used functions of StringBuilder and StringBuffer classes in Java:
Function Description
append() Appends the specified character(s) or object to the end of the string.
insert() Inserts the specified character(s) or object at the specified index in the string.
delete() Deletes the characters from the string between the specified start and end indices.
[Java Notes] - TheTestingAcademy (Pramod Sir)
deleteCharAt() Deletes the character at the specified index in the string.
Replaces the characters in the string between the specified start and end indices
replace()
with the specified string.
substring() Returns a substring of the string between the specified start and end indices.
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
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.
[Java Notes] - TheTestingAcademy (Pramod Sir)
[Assignment] String Problems
Reverse a String
Input - s = abc
O/P- s = cba
Palindrome
class ReverseString {
public static void main(String[] args)
{
String input = "Pramod Sir is Owner of TheTestingAcademy";
// 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);
}}
🧵 Functions in Java
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
1. No Return Type
2. Return Type
int add(int a, int b) {
return a + b;
}
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
● Print diagonal Elements 2D array
📗 OOPs ( Java)
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)
Abstraction Example
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).
// abstract method
public abstract double getArea();
}
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)
[Java Notes] - TheTestingAcademy (Pramod Sir)
Interface
An interface is a collection of abstract methods that must be implemented by any class that implements
the interface
Inheritance
1. Example with Student -> Manual , Automation
2. Extra Data members, Operations or Methods
PolyMorphism
● + operator
● Remote or on/off button poly behavior
https://docs.google.com/presentation/d/1pilgqDxrvs7KsFEOHyLBzF75Da3ZXYPvnPCHfG1Gk4s/edit?
usp=sharing
Inheritance
// Interface
Question Answer
maintainable applications.
Q2) What are the The programming models available to develop applications include procedure-
Q5) What is OOPs concept? OOPs (Object-Oriented Programming) is a programming concept that
Q7) Who is the father of Alan Kay is considered the father of OOPs, as he introduced the concept of
enables the use of the same code for different types of objects.
program.
[Java Notes] - Inheritance
TheTestingAcademy (Pramod
is a programming concept Sir)
that allows the creation of new classes
Q11) What is inheritance? by extending existing classes. It enables code reuse and promotes the creation
Class Book{
Int id;
String name;
String author;
● Override the methods if the child extends the Parent or adds itself as Abstract.
● No object for Abstract, only reference.
Interfaces
Important Concepts
● super()
● //1. Use of super with Variables
● //2. Use of super with Methods
● //3. Use of super with constructors
●
● // Constructor Chaining
●
● // Encapsulation
● // Polymorphism
● // Abstraction
● // Access Modifiers
● // Static Keyword
● //Inner Class
1. Variables
2. Blocks
3. Constructors
4. Methods
5. Inner Class
package atb.classdemo;
// Block
{
[Java Notes] - TheTestingAcademy
System.out.println("I am block"); (Pramod Sir)
}
// Default constructor
Book(){
System.out.println("Default Con");
}
// Parameters constructor
public Book(int id, String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
// Method
void show(){
System.out.println("Data");
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
'}';
}
// 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;
package atb.classdemo.staticdemo;
Class Loaders
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.
Access Modifier
Access modifiers in Java:
[Java Notes] - TheTestingAcademy (Pramod Sir)
Polymorphism
[Java Notes] - TheTestingAcademy (Pramod Sir)
[Java Notes] - TheTestingAcademy (Pramod Sir)
Abstraction
Abstract classes and methods
Interface
1. Interface variables will be inherited to subclasses.
2. interface is a keyword which is used to define User Defined Datatypes.
3. Interfaces can be used to achieve multiple inheritance in Java.
4. One interface can extend one or more interfaces.
5. One class can implement one or more interfaces.
[Java Notes] - TheTestingAcademy (Pramod Sir)
6. Interface can contain the following members:
a. public final static variables
b. public abstract methods
c. public static inner classes
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.
static methods in interfaces are similar to default methods but the only difference is that you can’t override
them.
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
abstract
// Output
"Harry Potter, J.k. Rowling, 100"
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 instance methods or
static methods.
4. Static Block:
A static block is a block of code that gets executed when the class is loaded into memory. It is used to
initialize static data members.
Nested Class
Class within Class is called Nested class
class OuterClass
{
...
class NestedClass
{
...
}
}
[Java Notes] - TheTestingAcademy (Pramod Sir)
class OO{
static int o =100;
int a = 900;
static class SNCI{
void show(){
System.out.println(o);
//Only a static member of outer class can be accessed directly.
// System.out.println(a);
}
}
}
}
}
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.
// inner class
public class Engine {
// inner class fields
private int horsepower;
private String fuelType;
//
Car myCar = new Car("Toyota", "Camry");
Car.Engine engine = myCar.new Engine(200, "Gasoline");
engine.start();
class Parent{}
class Child extends Parent{}
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.
Anonymous inner classes are generic created via below listed two ways as follows:
package thetestingacademy.oops.anonymousclass;
interface Student{
int id = 11;
void setId();
}
@Override
public void setId() {
System.out.println(id);
}
}
[Java Notes] - TheTestingAcademy (Pramod Sir)
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.
1. Primitive to String
1. Using valueOf()
2. toString() of wrapper
2. String to Primitive
a. A) using parseXO;
3. Primitive to Wrapper Object
a. A) Using Constructor of Wrapper class
b. B) Using valueOf method of Wrapper class
4. Wrapper Object to Primitive
a. A) Using xxValue0 method of Wrapper classes
5. String to Wrapper Object
a. A) Using constructor of Wrapper classes
b. B) Using valueOf method of Wrapper classes
6. Wrapper Object to String
a. A) Using toString( method
// JVM - values from -128 to 127 are cached, so the same objects are returned.
📕 Exceptions
An exception is an event that occurs during the execution of a program that disrupts the normal flow of
instructions.
P.S. - If no exceptions are handled, control is passed to the JVM, which terminates the program.
Exception Hierarchy
package thetestingacademy.exceptions; // 0
public class Ex01 {
// 3 PROBLEMs in this problem
public static void main(String[] args) {
String sh = args[0];
int x = Integer.parseInt(sh);
int a = 10/x;
[Java Notes]
System. - TheTestingAcademy (Pramod Sir)
out.println(x);
System.out.println(a);
}
}
Exception Handling in Java is a mechanism for handling runtime errors so that the application's
normal flow can be maintained.
⚠️ Questions
1. Throwable in Catch Block
2. String in Catch ?
[Java Notes] - TheTestingAcademy (Pramod Sir)
Multiple Catch
You can catch multiple exceptions; their execution depends on the execution problem.
package thetestingacademy.exceptions;
⚠️
// Keep the Biggest at the last Exception E ( bigger basket)
P.S. - Please do not write anything between Try and Catch.
package thetestingacademy.exceptions;
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();
}
Finally Block
The finally block is a block of code that follows a try-catch block and is always executed, regardless of
whether an exception is thrown or caught. The finally block is typically used to release resources or
perform other cleanup tasks.
try {
// code that might throw an exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// code to be executed after the try-catch block
}
If the file cannot be found, a FileNotFoundException is thrown, which is caught by the catch block.
Regardless of whether the exception is thrown or not, the finally block is always executed, and it closes the
file.
Yes
Problem 1
class ProblemF{
int a = 10;
int show(){
try{
[JavaSystem.out.println("In
Notes] - TheTestingAcademy
class -> "+(Pramod
a); Sir)
return a;
}catch (Exception e){
System.out.println("Catch");
a = 20;
return a;
}finally {
System.out.println("I am Final");
}
}}
Problem #2
package thetestingacademy.exceptions;
class ProblemF{
int a = 10;
int show(){
try{
// a = 10/0;
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");
//int[] a1 = new int[-1]; fix it
}
}
}
Problem #03
[Java
package Notes] - TheTestingAcademy (Pramod Sir)
thetestingacademy.exceptions;
package thetestingacademy.exceptions;
Throw exObject.
Throws Keyword at Method LEVEL
[Java Notes] - TheTestingAcademy (Pramod Sir)
Custom Exception
"Exception" class or any of its subclasses, such as "RuntimeException". Custom exceptions 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".
Important Points
throw new Exception();
throw [Java Notes] - TheTestingAcademy (Pramod Sir)
new Error();
throw new Throwable();
catch(Exception){}
catch(Error){}
catch(Throwable){}
catch(Object){} //Not Ok
2) NoClassDefFoundError
3) StackOverflowError
4) OutOfMemoryError
5) UnsupportedClassVersionError
6) ExceptionInInitializerError
(if exception occurs at static variable or static block while loading the class.)
static int p;
static {p=Integer.parseInt("SRI");}
}
1) ClassCastException
(If you try to convert superclass object into subclass object whitout having the ref. of
subclass.)
2) IllegalStateException
Thread t= new Thread();
t.start();[Java Notes] - TheTestingAcademy (Pramod Sir)
t.start();//Here this err will occur
3) IllegalArgumentException
t.setPriority(30);
Thread priority must be b/w 1-10.
Try Out
package thetestingacademy.exceptions;
public class Ex11 {
public static void main(String[] args) {
Hello h = new Hello();
h.process();
System.out.println("Pramod");
}
}
class Hello {
public int process() {
throw new NullPointerException();
}
}
Collection Framework
Legacy Interface
● Enumeration (cursor)
Enumeration
It is an interface used to get elements of legacy collections(Vector, Hashtable)
Vector access with Enumeration
Vector v - new Vector();
Enumeration e = v.elements(); and hasNext functions
Collection vs Collections
● Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and
interfaces in it.
● Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root”
interfaces of Java collection classes.
What is a Framework?
[Java Notes] - TheTestingAcademy (Pramod Sir)
A framework is a set of classes and interfaces which provide a ready-made architecture.
List
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.
Way to Initialize
● List<String> fruites = List.of("orange","apple");
● ArrayList - Underline Array - Get element is easy, inserting, Delete is Costly.
● LinkedList - LinkedList
● Vector - Array
Most of the time, programmers prefer ArrayList over Vector because ArrayList can be synchronized
explicitly using Collections.synchronizedList.
List Functions
Use the javap java.util.List
Array vs Vector
Vector
Array vs ArrayList
Array vs LinkedList
[Java Notes] - TheTestingAcademy (Pramod Sir)
●
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.
[Java Notes] - TheTestingAcademy (Pramod Sir)
Enumeration No No Yes
Methods in Iterator
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
[Java Notes] - TheTestingAcademy (Pramod Sir)
Iterator vs ListIterator
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.
package thetestingacademy.collections.list;
import java.util.ArrayList;
import java.util.Spliterator;
import[Java Notes] - TheTestingAcademy (Pramod Sir)
java.util.stream.Stream;
// estimateSize method
System.out.println("estimate size : " + splitr1.estimateSize());
// getExactSizeIfKnown method
System.out.println("exact size : " +
splitr1.getExactSizeIfKnown());
// Split
}
}
ConcurrentModificationException
● Can’t add to the List while iterating.
[Java Notes] - TheTestingAcademy (Pramod Sir)
Set
● Interface, java.util.Set
● Unique Only
● If o1.equals(o2) Only one will be in the List
● Set interface has the following concrete subclasses:
○ o HashSet
○ o LinkedHashSet
○ o TreeSet .
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
LinkedHashSet
● LinkedHashSet is a subclass of HashSet.
● It stores the data in the order as added by the user. A,B,C -> ABC
TreeSet
● 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 of elements
[Java Notes] - TheTestingAcademy (Pramod Sir)
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 runtime
java.lang.ClassCastException
● TreeSet allows storing elements of similar type only.
● Null value cannot be stored in TreeSet.
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.
[Java Notes] - TheTestingAcademy (Pramod Sir)
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
Queue
● Added interface in Java 5.
● PriorityQueue is one of the commonly used subclasses of Queue interface.
● PriorityQueue doesn’t allow null values.
● You can add only comparable objects to PriorityQueue
[Java Notes] - TheTestingAcademy (Pramod Sir)
Duplicate Vaue No No No
Synchronized No No No
List Iterator No No No
Enumeration No No Yes
Index Representation No No No
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.
LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements
inserted into it.
[Java Notes] - TheTestingAcademy (Pramod Sir)
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.
[Java Notes] - TheTestingAcademy (Pramod Sir)
HashTable
● By using TreeMap
● By using LinkedHashMap
● Sort HashMap by Values
● Sort HashMap by Values using Comparator Interface
[Java Notes] - TheTestingAcademy (Pramod Sir)
● 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
.
How to synchronize List, Set and Map elements?
Using the subList() method: You can use the subList() method to create a new ArrayList that contains a
subset of elements from the original ArrayList. Example: ArrayList<Integer> copiedList = new ArrayList<>
(originalList.subList(fromIndex, toIndex));
Generics
● Introduction to Generics, Generics Class
● Implementing Generics for the Custom List
● Examples
"Generics allow the reusability of code, where one single method can be used for different data-types of
variables or objects."
idea is to allow different types like Integer, String, … etc and user-defined types to be a parameter to
methods, classes, and interfaces.
MaxtTheerGeneric Demo
[Java Notes] - TheTestingAcademy (Pramod Sir)
Multithreading
1. Multi Tasking
[Java Notes] - TheTestingAcademy (Pramod Sir)
a. Multi Thread
b. Multi Processing
Multitasking
● 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.
Multi Processing:
● Process is a program.
● Each process is treated as a separate execution unit and is assigned to a different CPU.
○ Running MS Word C#
○ 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
● Application level
● They can share the memories
● They can do it easily in threads.
● Switching to control in Threads is easy. ( T1 -> T2)
- Bank Application allows multiple users to login, bank balance, withdraw amount.
-
[Java Notes] - TheTestingAcademy (Pramod Sir)
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);
}
}
}
[Java Notes] - TheTestingAcademy (Pramod Sir)
There are two ways you can create the Threads in Java.
1. Extend Thread
2. Runnable
package thetestingacademy.multithreading;
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
System.out.println(i + " --> ");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
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 method and we
would not be able to take the advantage of multithreading.
● When the run method gets called though start() method then a new separate thread is being
[Java Notes] - TheTestingAcademy (Pramod Sir)
allocated to the execution of run method, so if more than one thread calls start() method that
means their run method is being executed by separate threads (these threads run simultaneously).
● 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.
Concurrency vs Parallelism
Concurrency refers to the ability of a system to handle multiple tasks or threads at the same time, allowing
them to be executed independently and asynchronously.
Concurrency enables a system to perform multiple tasks simultaneously, but it does not 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 requests at the same time.
Parallelism refers to the ability of a system to execute multiple tasks or threads simultaneously, using
multiple cores or processors.
Parallelism enables a system to perform multiple tasks at the same time, rather than one at a time.
For example, a parallel program can use multiple cores or processors to perform a large computation in
less time.
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.
[Java Notes] - TheTestingAcademy (Pramod Sir)
Synchronous vs Asynchronous
Synchronous operations block the execution of the program or system until the operation is completed.
This means that the program or system will not execute any other code or perform any other tasks until the
current task is completed.
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.
Asynchronous operations, on the other hand, do not block the execution of the program or system.
The program or system can continue to execute other code or perform other tasks while an asynchronous
operation is in progress.
This can make the program or system more responsive and efficient, because it can perform multiple tasks
[Java Notes] - TheTestingAcademy (Pramod Sir)
at the same time.
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.
Thread Priority
[Java Notes] - TheTestingAcademy (Pramod Sir)
1. Create a Thread.
2. Start the Thread ( th.start() ) , T1, T2.
3. Initial state will be ready TO Run (waiting for CPU).
4. Thread scheduler selects the t1
● New - Instance of thread created which is not yet started by invoking start() it will be.
● Runnable - After Invocation of start() and before it is selected to be run by the scheduler.
● Running - After the thread scheduler has selected it.
● Non-runnable - Thread alive, not eligible to run.
● Terminated - run() method has exited.
[Java Notes] - TheTestingAcademy (Pramod Sir)
Synchronization
● Lock on an Object.
● Applying synchronized keywords for local blocks is called as Block Level Synchronization.
● You must specify some object as a parameter to synchronized block.
● When a local block is synchronized, then the object which you are passing as a parameter to the
synchronized block will be locked by the current thread.
class Pramod{
● Case 1
● Case 2
● Case 3
● Case 4
● Case 5
● Case 6
Deadlocks
package thetestingacademy.multithreading.deadlock;
try {
Thread.sleep(100);
} catch (Exception e) {
}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
try {
Thread.sleep(100);
} catch (Exception e) {
}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
Wait.
customThread.start();
customThread2.start();
}
}
class WaitForMe {
@Override
public void run() {
wait.show();
}
}
● 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 READY TO
RUN state.
○ If resources are not available then the threads go to BLOCKED state.
Join()
● 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()
○ t1 thread will be joined at the end of t2.
Thread Pool
● 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 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
[Java Notes] - TheTestingAcademy (Pramod Sir)
Executor executor = Executors.newFixedThreadPool(5);
executor.execute(new RunnableTask());
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.
Instance variables are more prone to the Thread Safty, Local variables are always safe.
class MyThreadLocal {
private static ThreadLocal<Integer> myThreadLocal = new ThreadLocal<>
();
public static void set(Integer value) {
myThreadLocal.set(value);
}
public static Integer get() {
return myThreadLocal.get();
}
}
MyThreadLocal.set(10);
System.out.println(MyThreadLocal.get()); // 10
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 thread-local variable in another
thread.
For example, ThreadLocal can be used to store a user's session information in a web application, where
each user's session information is specific to the thread that is handling the user's request.
[Java Notes] - TheTestingAcademy (Pramod Sir)
● 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.
[Java Notes] - TheTestingAcademy (Pramod Sir)
In this example, the finalize() method is used to delete a file when the MyResource object is eligible for
garbage collection.
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 try-catch-finally or
try-with-resources statements to release resources and also use explicit methods like close() to release
resources.
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.
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.
What is daemon thread?
[Java Notes] - TheTestingAcademy (Pramod Sir)
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)