0% found this document useful (0 votes)
22 views

[Java Notes]-TheTestingAcademy by Pramod

Uploaded by

Dharani nadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

[Java Notes]-TheTestingAcademy by Pramod

Uploaded by

Dharani nadh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 131

[Java Notes] - TheTestingAcademy (Pramod Sir)

Java Notes - TheTestingAcademy (Pramod Sir)

✅ Why Learn Java?

● Java is a general-purpose, object-oriented programming language that was designed by James


Gosling at Sun Microsystems in 1995.
● Compilation of the Java applications results in the bytecode that can be run on any platform using
the Java Virtual Machine. Because of this, Java is also known as a WORA (Write Once, Run
Anywhere)
● Java Version - https://en.wikipedia.org/wiki/Java_version_history
● High Level, Platform independent & Architecture Neutral
● Secure, Robus, Multi Thread, Distributed and OOPs language.

⚠️ Why Java is not 100% Object-Oriented?

● Primitive data types.


● Use of Static.
● Wrapper class

⚠️ How is Java ​Secure?

● JVM which protects from unauthorized or illegal access to system resources.


● Oops and inner classes

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)

Check the Languages, with the Level of Abstraction

Major Features of Java Programming Language

● Simple.
● Object-Oriented.
● Platform Independent.
● Portable.
● Robust.
● Secure.
● Interpreted.
● Multi-Threaded

⚠️ What is Source Code?


[Java Notes] - TheTestingAcademy (Pramod Sir)
Human understandable code written using High Level Programming language is called as Source Code.
(NameOfFile.java)

⚠️What is Byte Code?


JVM understandable code generated by Java Compiler is called as Byte Code. Byte code is also called as
Magic Value.

⚠️Why C and C++ are Platform Dependent?


When you compile a C or C++ program on one Operating System then the compiler generates that
Operating System understandable native code.

Native code generated on one OS will not run on other OS directly. Window -> exe, Mac -> dmg, Linux, deb,
pkg

⚠️ What is Java Compiler?

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.

⚠️ What is Java Interpreter?


Java Interpreter is a program developed in C or C++ programming language with the name
“Java”. It will convert byte code to native code line by line. It will execute that native code.

⚠️ What is JIT Compiler?


JIT (Just-In-Time) compiler is a component of the Java Runtime Environment. JIT Compiler compiles or
translates or converts the necessary part of the bytecode into machine code instead of converting line by
line. Because of this, performance of Java program has improved.

Run your First Java Program


1. Install Java and Set path to the Home in Windows / Mac
2. Install IDE (IntelliJ) and you can avoid the first step.
3. Create new command line project and Add the code and run the program.

How to Set JAVA_HOME path in MAC - Click here


1. Download the JDK latest -
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:
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.zshrc
3. In either case, restart your shell.

brew install openjdk

How to Set JAVA_HOME path in Windows

Set the JAVA_HOME Variable


https://www.oracle.com/java/technologies/javase/jdk21-archive-downloads.html
[Java Notes] - TheTestingAcademy (Pramod Sir)
https://www.openlogic.com/openjdk-downloads

To set the JRE_HOME or JAVA_HOME variable:

1. Locate your Java installation directory


If you didn't change the path during installation, it'll be something like
C:\Program Files\Java\jdk21

You can also type where java at the command prompt.

2. Do one of the following:


Windows 7 – Right click My Computer and select Properties > Advanced
Windows 8 – Go to Control Panel > System > Advanced System Settings
Windows 10/11 – Search for Environment Variables then select Edit the system environment variables

3. Click the Environment Variables button.

4. Under System Variables, click New.

5. In the Variable Name field, enter either:

● JAVA_HOME if you installed the JDK (Java Development Kit)


or

● JRE_HOME if you installed the JRE (Java Runtime Environment)

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

Note for Windows users on 64-bit systems


Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'

7. Click OK and Apply Changes as prompted

⚠️ What is JDK (Java Development Kit) / SDK (Software Development Kit)?

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

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.

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 Version Key Features

Java 1.0 Garbage collection, multi-threading, network programming

Java 1.1 Inner classes, JavaBeans, JDBC

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 6 (Java 1.6) JAXB API, Java Compiler API

Java 7 (Java 1.7) Try-with-resources, multi-catch exceptions, Fork/Join Framework, NIO.2

Java 8 (1.8) Lambda expressions, Stream API, java.time package, CompletableFuture


[Java Notes] - TheTestingAcademy (Pramod Sir)
Java 9 Module system, private interface methods, JShell

Java 10 Local variable type inference, garbage collector improvements

Java 11 HttpClient API, var keyword for lambda parameters, Unicode 10.0 support

Java 12 Switch expressions, garbage collector improvements

Java 13 Text blocks, Z Garbage Collector improvements

Java 14 Record classes

Java 15 Sealed classes and interfaces, garbage collector improvements

Java 16 Pattern matching for instanceof, garbage collector and JFR improvements

Java 17 Sealed Types Preview, garbage collector improvements

Java Comments

Comment Type Syntax Description

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

@param, @return, @throws, etc.

A special type of documentation comment that starts with /** and

includes additional Javadoc tags for generating documentation. It can

Javadoc comment /** be used to describe classes, interfaces, methods, fields, etc. and their

functionality. It is a best practice to include Javadoc comments in your

code for documentation purposes.

⚠️ Why this Kolavari DI? (Reason for this error)


Install JDK properly

⚠️ Difference between Java and C++

⚠️ Differences between Oracle JDK and OpenJDK

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

⚠️ What is the use of setting the PATH?


Setting the PATH is important for the operating system to know where to look for executable files when a
command is executed. In the case of Java, setting the PATH is essential for the system to locate the Java
compiler and runtime environment (JRE) executable files.

⚠️ What is the reason for the following error?


● Javac : file not found Hello.java
● Error Could not find or load main class Hello
● java.lang.NoClassDefFoundError : hello(Wrong name Hello)
● java.lang.ClassFormatERROR : Incompatible magic value ( change in .class)
● java.lang.UnSupporttedClassVersion : Hello (Compiled with Old )

⚠️ What are the ways available to set the PATH?


There are several ways to set the PATH, including using the command line, editing system environment
variables, and using third-party tools or scripts. The specific method used may vary depending on the
operating system being used.

⚠️ What is the difference between PRIVATE JRE and PUBLIC JRE?


A PRIVATE JRE is a Java runtime environment that is installed and used by a specific application or user,
and is not shared with other applications or users on the same system. A PUBLIC JRE is a Java runtime
environment that is installed and made available to all applications and users on the system.

⚠️ 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.

⚠️ Which JRE will be used while executing Java application?


The JRE that is used to execute a Java application depends on several factors, including the system's PATH
settings, the application's CLASSPATH settings, and any environment variables that may be set.

⚠️ 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.

⚠️ Can we execute java program without setting PATH?


It is possible to execute a Java program without setting the PATH, but it requires specifying the full path to
the Java executable file every time the command is executed.

⚠️ What is the difference between JVM and JRE?


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.

⚠️ What is the difference between JIT Compiler and Java Interpreter?


A JIT (Just-In-Time) compiler is a component of the JVM that dynamically compiles bytecode into machine
code at runtime, while a Java Interpreter executes bytecode directly without compiling it.

⚠️ What is the difference between Byte code and Native code?


Bytecode is a machine-independent code that is generated by the Java compiler and is designed to be
[Java Notes] - TheTestingAcademy (Pramod Sir)
executed by the JVM. Native code, on the other hand, is machine-specific code that is directly executable
by the CPU.

⚠️ Is it possible to execute Java program without having JDK in machine?


It is possible to execute a Java program without having the JDK (Java Development Kit) installed on the
machine, but a JRE (Java Runtime Environment) must be installed.

⚠️ Can I install multiple JDK versions in my machine?


Yes, it is possible to install multiple JDK (Java Development Kit) versions on the same machine. It is
important to manage the PATH and other environment variables correctly to ensure that the correct version
is used when compiling or executing Java programs.

⚠️ Can I install multiple JRE versions in my machine?


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 ensure that the correct version
is used

​Explain the main method in Java

● 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:

● Loads the necessary classes for the program.


● Locates the entry point class specified on the command line.
● Locates the main method in the entry point class.
● Sets up the environment and executes the code inside the main method.
● When the main method completes, the JVM terminates the program.

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.
[Java Notes] - TheTestingAcademy (Pramod Sir)

Identifiers - names those will be used to identify the programming elements like classes, methods,
variables, etc uniquely

Rules to follow when you define an Identifier:


1. Identifier can contain Alphabets, Digits, and two special symbol i.e. Dollar ($),
2. Underscore (_).
3. First character of an identifier must be an Alphabet or Dollar ($) or Underscore (_).
4. Keywords or Reserved words can't be used as Identifiers.

✅ Variables and Data Types in Java

Variables

● A variable is a container (storage area) used to hold data.


● Each variable should be given a unique name (identifier).
● Memory will be allocated for the variable while executing the program
● Value of the variable can be changed any number of times during the program execution.

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

● There are three rules to create an identifier:


○ Characters from A to Z, as well as their lowercase counterparts, can be used.
○ Numbers from 0-9 can be used.
○ Special characters that can be used are $ (the dollar sign) and _ (underscore).

int $ = 34; // 44 - Yes


// int _pramod = 34; // Yes
// int 123 = 34; // NO
// int 123_name = 34; // NO
// int 1name = 34; // no
//int #1 = 34; // No
// System.out.println($);

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”;

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.

● Declare variables with default values


● Multiple variable declare.

Data Types

● Type of data you want to use


● Amount of memory allocation required for your data.
○ Size, Range

There are two types of data types


1) Primitive Data Types
2) User Defined Data Types
[Java Notes] - TheTestingAcademy (Pramod Sir)
Primitive data types
They are the basic data types in Java and are used to store simple values.

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

byte 8 0 byte b = 10;

short 16 0 short s = 100;


[Java Notes] - TheTestingAcademy (Pramod Sir)
int 32 0 int i = 1000;

long 64 0L long l = 100000L;

float 32 0.0f float f = 1.23f;

double 64 0.0d double d = 1.23;

char 16 '\u0000' char c = 'A';

boolean 1 false boolean b = true;

How byte b = 10 is stored in JVM?

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

Four types of User Defined Data types:


● Class type - String
● Interface type
● Enum type (From JAVA 5)
● Annotation type (From JAVA 5)

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.

byte b; int a; double d; char ch;

2) Reference(Non Primitve) Variables - Variables declared with reference data types are called as reference
variables

String str; Hello h;

✅ Constants
● Special variable whose value can't be modified during the program execution.
● Constant is also called as final variable.

final int A=99;


final String STR="TTA";
final double D1=999.99;

Variables & Constants


1) Default value of char is either ASCII - 0 or UNICODE \u0000.
2) Default value of char is not space.
3) JVM will not provide default value for Local Variable.
4) Local variable must be initialized before using .
5) JVM will provide default value for static Variable.
6) Static variable can be accessed from Static method (main method).
7) JVM will provide default value for instance Variable.
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.
[Java Notes] - TheTestingAcademy (Pramod Sir)
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

Q2 What is the keyword added newly in Java 5? enum

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 are the keywords available which can’t be used in


Q4 goto, const
Java Program?

An identifier is a name assigned to a

variable, method, class, or package.

The rules to follow while defining an

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

whitespace or special characters

allowed except underscore, iii) It

should not be a reserved keyword.

Data type defines the type of value a

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,

ii) Reference data types.

Q7 How many primitive data types available? 8


[Java Notes] - TheTestingAcademy (Pramod Sir)
What is the Integral data type that will not allow negative
Q8 char
value?

Q9 What is the default value of char data type? '\u0000'

The range of short and char are


Why the range of short and char are different even both
Q10 different because short is signed and
required 2 bytes of memory?
char is unsigned.

How many types of User defined data types available up to


Q11 2
JDK1.4?

How many types of User defined data types available from


Q12 1
Java 5?

Q13 Is String a data type? No, it is a class.

Q14 What is the default value of reference data type? null

Q15 What are the possible values can be used for boolean type? true or false

A variable is a container that stores


Q16 What is a variable?
values.

How many types of variables are available as per the data


Q17 2
type?
[Java Notes] - TheTestingAcademy (Pramod Sir)
How many types of variables are available as per the
Q18 3
scope?

Primitive variables hold the actual


What are the differences between Primitive variables and
Q19 values, while reference variables hold
Reference variables?
the memory location of the object.

There is no default value for a local

Q20 What is the default value of local variable? variable. It must be initialized before

use.

Not possible. Variables must be


How can I declare multiple types of variables in one
Q21 declared separately for each data
statement?
type.

Multiple variables of the same type

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.

Declare and initialize a variable in one


How can I declare and initialize a variable in one
Q23 statement by assigning a value to it
statement?
when it is declared.

Declare and initialize multiple

variables of the same type in one

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

assigning a value to each variable

when it is declared.

Can I change the value of variable during program


Q25 Yes
execution?

Q26 When will the memory be allocated for the variables? Memory for variables is allocated at

runtime, while the program is


executing.
[Java Notes] - TheTestingAcademy (Pramod Sir)

UNICODE Characters

● UNICODE stands for UNIversal CODE.


● Every character will have UNICODE value.
● UNICODE Notation
● Syntax:
○ \uXXXX - X will be hexadecimal digit
● Starts with \u followed by four hexadecimal digits.
● UNICODE Range
● \u0000 (0) to \uFFFF (65535)
[Java Notes] - TheTestingAcademy (Pramod Sir)
[Java Notes] - TheTestingAcademy (Pramod Sir)

Practice QnA

Give the output of the following in the following

1. It will not compile.


2. At runtime error
3. Condition 1
4. Condition 2

Question 1
int enum=9;
System.out.println(enum);

Question 2
char char='A'; System.out.println(char);

✅ Literals

● Literals are the actual values assigned


● Literals can be Numeric and Non Numeric.

Literal Type Description


[Java Notes] - TheTestingAcademy (Pramod Sir)
Integer literals Whole numbers without decimal points, such as 42 or -123

Floating-point literals Numbers with decimal points, such as 3.14 or -0.0025

Character literals A single character enclosed in single quotes, such as 'a'

Boolean literals A value of either true or false

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

Diff between /n and /r


https://stackoverflow.com/questions/1761051/difference-between-n-and-r
[Java Notes] - TheTestingAcademy (Pramod Sir)
Escape Sequence - Task_12.java

ASCII stands for American Standard Code for Information Interchange.


● Every character enclosed in single quotation marks will have an integer equivalent value called as
ASCII value.
● ASCII Value Range is 0 – 255.
● ASCII Value can be assigned to a char type variable

Octal Value as char type ( 0)

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)

Syntax: \DDD - D will be octal digit


OCTAL Range Range in Decimal 0 - 255 Range in Octal \0 - \377

Question Answer

A literal is a fixed value that is directly used in a program without


What is a literal?
needing to be computed or evaluated.
[Java Notes] - TheTestingAcademy (Pramod
There are six types of literals availableSir)
in programming languages:
How many types of literals are
numeric literals, character literals, boolean literals, string literals,
available?
array literals, and null literals.

How many boolean literals are There are only two boolean literals available, which are true and

available? false.

When you assign the value 1 to a boolean type variable, it will be


What will happen when I assign 1 to
interpreted as true because any non-zero value is considered as
boolean type variable?
true in boolean expressions.

Can we store empty character in char No, you cannot store an empty character in a char type variable

type variable? because it requires at least one character.

To store a single quote in a char variable, you need to use the


How to store single quote in char
escape sequence ' because the single quote is a reserved character
variable?
in programming languages.

An escape sequence is a combination of characters used to

What is Escape Sequence? represent special characters or non-printable characters in a string

literal. It usually starts with a backslash () character.

What will be displayed when

UNICODE value is found in String The string "UNICODE of A is A" will be displayed because \u0041

Literal? String str="UNICODE of A is represents the Unicode value of the letter A.

\u0041";

What will be displayed when Octal

representation is found in String The string "Octal of A is A" will be displayed because \101

Literal? String str="Octal of A is represents the octal value of the letter A.

\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

String str="Hello\nGuys"; character.


[Java Notes] - TheTestingAcademy (Pramod Sir)
Integer Literals

● Decimal Literals- // Base of 10


● Octal Literals - int b=0101; // Base of 8
● Hexadecimal Literals - int c=0Xface; // base 16 rather than base 10
● Binary Literals (From Java 7) - int b2 = 0b101;

Scientific / Exponent N Literals


float f = 129.8763e2F;
double d1 = 129.8763e+2;
double d2 = 12987.63e-2;
System.out.println(f);
System.out.println(d1);
System.out.println(d2);

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

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
○ Two operands are required.
● 3) Ternary Operator
○ Three Operands are required.
Types of operator depending on the operation:
● Arithmetic Operators
○ i. Unary Arithmetic Operators
○ ii. Binary Arithmetic Operators
● String Concatenation Operator
● Assignment Operator
○ i. Simple Assignment Operator
○ ii. Compound Assignment Operators
● Increment & Decrement Operators
● Relational Operators
● Logical Operators
● new Operator
● instanceof Operator
● Conditional or Ternary Operator
● Bitwise Operators.
[Java Notes] - TheTestingAcademy (Pramod Sir)
Unary Arithmetic 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()

Binary Arithmetic Operators

Remember this
[Java Notes] - TheTestingAcademy (Pramod Sir)

String Concatenation Operator (+)


+ operator can be used for two purposes:
1) Arithmetic Addition
2) String Concatenation

Simple Assignment Operator (=)


It is a binary operator.
It is used to assign the value to a variable. =
o Operand1 must be a variable.
o Operand2 can be a variable, value or expression.

Type Casting
Source type is not same as destination type then source type must be converted to
destination type.

Type casting can be done in two ways:


o Implicit casting
o Explicit Casting

Type casting can be done in two ways:


o Implicit casting
o Explicit Casting
[Java Notes] - TheTestingAcademy (Pramod Sir)
Implicit casting:
When type casting is happening automatically by the compiler then it is called as Implicit 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

Narrowing is the process of converting higher type to lower type.


Ex:
int a=300;
byte b=a; // INVALID – Implicit Casting
byte b = (byte)a; // VALID – Explicit Casting

int a=300; -> int means 32 bits memory required


00000000000000000000000100101100
byte b1=(byte)a; -> byte means 8 bits memory required
00101100
Value is
0 + 0 + 32 + 0 + 8 + 4 + 0 + 0 = 44.
(00101100)₂ = (0 × 2⁷) + (0 × 2⁶) + (1 × 2⁵) + (0 × 2⁴) + (1 × 2³) + (1 × 2²) + (0 × 2¹) + (0 × 2⁰) = (44)₁₀

Compound Assignment Operators

int a=90; a+=9; => a = a+9;

Increment (++) / Decrement (--) Operators

● Increment operator will be used to increase the value of the variable by 1.


● Decrement operator will be used to decrease the value of the variable by 1.
● Increment / Decrement operator can't be applied for value/constant.
[Java Notes] - TheTestingAcademy (Pramod Sir)
Relational Operators

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)

Bitwise AND o Bitwise OR o Exclusive OR (XOR)

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

Bitwise operators are used to perform bitwise operations


What is the use of bitwise operators?
on binary representations of integers.

What is the result type of String concatenation The result type of String concatenation operation is

operation? always a String.


[Java Notes] - TheTestingAcademy (Pramod Sir)
What will happen when I try to assign int type to The code will not compile because you cannot assign an

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

comparison operators? boolean operands.

The prefix form increments the value before it is used,


What is the difference between prefix and postfix
while the postfix form uses the value and then increments
forms of increment operator?
it.

Type casting is a way to convert a value from one data


What is type casting and what are the types
type to another. The types available are widening
available?
conversion (implicit) and narrowing conversion (explicit).

The new operator is used to create an instance of a class


What is the use of new operator?
or an array.

What is the difference between String The String concatenation operator (+) is used to

Concatenation and Arithmetic Addition concatenate two strings, while the arithmetic addition

operator? operator (+) is used to add two numeric values.

The bitwise operators available are: ~ (bitwise NOT), &

What are the bitwise operators available? (bitwise AND), | (bitwise OR), ^ (bitwise XOR), << (left

shift), >> (right shift), and >>> (unsigned right shift).

The equality operators available are: == (equal to) and !=


What are equality operators available?
(not equal to).

Implicit casting is done automatically by the compiler,


What is the difference between Implicit casting
while explicit casting requires the programmer to specify
and Explicit Casting?
the conversion explicitly.
[Java Notes] - TheTestingAcademy (Pramod Sir)
The assignment operator is used to assign a value to a
What is the use of assignment operator?
variable or an array element.

2's complement is a way of representing negative integers

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

arithmetic operators? (int, long, float, double) and char 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,

operators? long, short, char, byte).

The logical NOT operator (!) is used to negate a boolean


What is the use of Logical NOT operator?
value.

The prefix form decrements the value before it is used,


What is the difference between prefix and postfix
while the postfix form uses the value and then
forms of decrement operator?
decrements it.

The instanceof operator is used to check if an object is an


What is the use of instanceof operator?
instance of a particular class or interface.

What is result type when you add two byte


The result type when you add two byte variables is int.
variables?

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

An operator is a symbol that represents a specific operation to


What is an operator?
be performed between operands.

What are the valid conditions for "Infinity" Division by a positive number or multiplication by a positive

output? infinity.

Arithmetic operators are used to perform mathematical


What is the use of arithmetic operators?
calculations between operands.

What is the result type when you add long


The result type is a float.
and float variables?

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.

The new operator is used to allocate memory for an object and


What is the result of new operator?
returns a reference to that object.

The instanceof operator returns true if an object is an instance


What is the result of instanceof operator?
of a particular class, or a subclass of that class.

What is the use of bitwise operators? Bitwise operators are used to perform operations at the bit level.

Type casting is the process of converting one data type to


What is type casting and what are the
another. The two types of type casting are implicit casting and
types available?
explicit casting.
[Java Notes] - TheTestingAcademy (Pramod Sir)
What will happen when I try to assign int It will result in a compilation error because they are incompatible

type to String type variable? types.

What is the use of assignment operator? The assignment operator is used to assign a value to a variable.

What is the difference between unary


Unary operators work on a single operand, while binary
arithmetic and binary arithmetic
operators work on two operands.
operators?

The logical NOT operator is used to reverse the truth value of a


What is the use of Logical NOT operator?
boolean expression.

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 compound assignment Compound assignment operators combine an arithmetic or

operators available? bitwise operation with an assignment.

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.

What are types of operands allowed for Bitwise operators can be applied to integer types: byte, short, int,

bitwise operators? and long.

What is the syntax of Explicit casting? The syntax of explicit casting is: (target_type) expression.

The relational operators compare two values and return a


What are the relational operators?
boolean result: <, >, <=, >=.

What is result type when you add byte and


The result type is an int.
int variables?
[Java Notes] - TheTestingAcademy (Pramod Sir)
What are the bitwise operators available? The bitwise operators are: &,

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.

What is the result type of String


The result type is a String.
concatenation operation?

The instanceof operator is used to test whether an object is an


What is the use of instanceof operator?
instance of a particular class or not.

Widening casting occurs when you convert a smaller type to a


What is the difference between Widening
larger type, while narrowing casting occurs when you convert a
and Narrowing?
larger type to a smaller type.

✅ Conditions and Loop

If
condition -> true or false
if(condition)
{ // Statements (IF BLOCK) }

Problem to find the Even and Odd with % Mod

if(a % 2==0)
System.out.println("Value is EVEN");
else
System.out.println("Value is ODD");
}

Problem to find the MAX three

if(a>b && a> c)


max=a;
else if(b> a && b>c)
max = b;
else
max=c;
System.out.println("Max value is "+max);
[Java Notes] - TheTestingAcademy (Pramod Sir)

Switch : Multi-way branch statement

● [ ] Java switch statement executes one statement from multiple conditions.

● [ ] 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.

● [ ] case/s values are not allowed.

● [ ] The value for a case must be constant or literal. Variables are not allowed.

● [ ] break can’t be used with elseif condition

// 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

// We can have any number of case statements


// below is default statement, used when none of the cases is true.
// No break is needed in the default case.
default :
// Statements
}
[Java Notes] - TheTestingAcademy (Pramod Sir)
String browser = "chrome"
switch(browser){
case "chrome" :
sop("chrome started!!");
break;

● Default fall through due to missing break - JDK 13

Much improved switch accepts multiple values per case.

switch (itemCode) {
case 001, 002, 003 :
System.out.println("It's an electronic gadget!");
break;

case 004, 005:


System.out.println("It's a mechanical device!");

● yield is used to return a value

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.

int val = switch (code) {


case "x", "y" :
yield 1;
case "z", "w" :
yield 2;
}

Switch can be used as an expression

String text = switch (itemCode) {


case 001 :
yield "It's a laptop!";
case 002 :
yield "It's a desktop!";
case 003 :
yield "It's a mobile phone!";
default :
throw new IllegalArgumentException(itemCode + "is an unknown device!");
}

Switch with arrows

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.

// While -> Condition -> Body -> Increment

// Do While -> Body -> Condition -> Increment


[Java Notes] - TheTestingAcademy (Pramod Sir)
break Statement and continue
● 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:
● 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
1. No Return Type - void
2. Return Type - data -> Primitive or Ref Type
3. Main method overloading - Interview.

✅ Object Class in Java

● Object class is present in java.lang package.


● Every class in Java is directly or indirectly derived from the Object class.
● Object class methods are available to all Java classes.

Ref image - geeksforgeeks

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;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}

Person p = new Person("John", 30);


System.out.println(p); // prints "Person[name=John, age=30]"

hashCode() method

In Java, the hashCode() method is a method defined in the Object class that returns an integer hash code
value for an object.

The hashCode() method is implemented by converting the internal address of the object into an integer
value. If two objects are equal according to the equals() method, then they should have the same hash
code.

public class Person {


private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + age;
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

equals(Object obj) method

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

public class Person {


private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

@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;
}
}

Person p1 = new Person("John", 30);


Person p2 = new Person("John", 30);
Person p3 = new Person("Jane", 30);

System.out.println(p1.equals(p2)); // prints true


System.out.println(p1.equals(p3)); // prints false

getClass() method,

public class Test {


public static void main(String[] args)
{
Object obj = new String("GeeksForGeeks");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "
+ c.getName());
}
}

Output - Class of Object obj is : java.lang.String

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.

// Java program to demonstrate working of finalize()

public class Test {


public static void main(String[] args)
{
Test t = new Test();
[Java Notes] - TheTestingAcademy (Pramod Sir)
System.out.println(t.hashCode());

t = null;

// calling garbage collector


System.gc();

System.out.println("end");
}

@Override protected void finalize()


{
System.out.println("finalize method called");
}
}

clone()method

It returns a new object that is exactly the same as this object. For clone() method refer Clone().

public class Person implements Cloneable {


private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public Person clone() {
try {
return (Person) super.clone();
} catch (CloneNotSupportedException e) {
// This should never happen, since we are Cloneable
throw new InternalError(e);
}
}
}

Person p1 = new Person("John", 30);


Person p2 = p1.clone();

System.out.println(p1 == p2); // prints false

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

int arr[5]; String names[3];

int arr[]={10,20,30}; String names[]={"Sri","Manish","DK"};

What happens if we try to access elements outside the array size?


ArrayIndexOutOfBoundsException

Multidimensional Arrays

int [][] arr= new int[3][3];


// 3 row and 3 column

● A group of like-typed variables referred to by a common name.


● Arrays are stored in contiguous memory.
● The variables in the array are ordered, and each has an index beginning from 0.
● The size of an array must be specified by int or short value and not long.
● The size of the array cannot be altered(once initialized).
● JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with
an illegal index

MyClass myClassArray[];
Object[] ao,

int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };

// Array of Objects
Student[] arr = new Student[5];

int[] numbers = new int[5];

// set the values of the array elements


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// print the values of the array elements


for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
} [Java Notes] - TheTestingAcademy (Pramod Sir)
// prints 10, 20, 30, 40, 50

[Assignment] - highest and lowest

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;

public class Main {


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

// create an array to store the numbers


int[] numbers = new int[100];
int size = 0;

// read the numbers from the user


int n;
do {
System.out.print("Enter a number: " , -1 to stop entering”);
n = scanner.nextInt();
if (n >= 0) {
numbers[size] = n;
size++;
}
} while (n >= 0);

// find the highest and lowest numbers


int highest = numbers[0];
int lowest = numbers[0];
for (int i = 1; i < size; i++) {
if (numbers[i] > highest) {
highest = numbers[i];
}
if (numbers[i] < lowest) {
lowest = numbers[i];
}
}

// print the highest and lowest numbers


System.out.println("The highest number is " + highest);
System.out.println("The lowest number is " + lowest);
} [Java Notes] - TheTestingAcademy (Pramod Sir)
}

For Each - For collections and arrays only

Multidimensional Arrays:
Multidimensional arrays are arrays of arrays with each element of the array holding the reference of other
arrays.

int [][] arr= new int[3][3];

public class multiDimensional {


public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// 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.

How can String be represented?

1) String class
2) StringBuffer
3) StringBuilder
4) Array of Characters
5) ArrayList of Characters

Why is String Immutable in Java?


The reason for making strings immutable in Java is to increase efficiency, security, and thread-safety.

Here is an example that demonstrates the immutability of strings in Java:

String str1 = "Hello";


String str2 = str1.concat(" World");
System.out.println(str1); // Output: Hello
System.out.println(str2); // Output: Hello World

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


[Java Notes] - TheTestingAcademy (Pramod Sir)

String class provides a wide range of functions to manipulate strings.

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.

length(): Returns the length of the string.


Example: "hello".length() returns 5.

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".

toUpperCase(): Returns a new string with all characters converted to uppercase.


Example: "hello".toUpperCase() 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 in Java

● 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.

StringBuilder sb = new StringBuilder("Hello");


sb.append(" World");
System.out.println(sb.toString()); // Output: Hello World

StringBuffer sb = new StringBuffer("Hello");


sb.append(" World");
System.out.println(sb.toString()); // Output: Hello World

StringBuffer and StringBuilder


● equals() is not overriden in StringBuilder and StringBuffer class.
● hashCode() is not overriden in the StringBuilder and StringBuffer class.

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.

reverse() Reverses the order of the characters in the string.

substring() Returns a substring of the string between the specified start and end indices.

charAt() Returns the character at the specified index in the string.

length() Returns the length of the string.

setCharAt() Sets the character at the specified index in the string to the specified character.

capacity() Returns the current capacity of the string builder.

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

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++)


{
ch= str.charAt(i); //extracts each character
nstr= ch+nstr; //adds each character in front of the existing
string
}
System.out.println("Reversed word: "+ nstr);
}

Palindrome

Input : str = "abba"


Output: Yes

Input : str = "pramod"


Output: No

public static boolean isPalindrome(String str)


{
// Initializing an empty string to store the reverse
// of the original str
String rev = "";

// 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;
} [Java Notes] - TheTestingAcademy (Pramod Sir)

Using the String Builder

class ReverseString {
public static void main(String[] args)
{
String input = "Pramod Sir is Owner of TheTestingAcademy";

StringBuilder input1 = new StringBuilder();

// append a string into StringBuilder input1


input1.append(input);

// reverse StringBuilder input1


input1.reverse();

// print reversed String


System.out.println(input1);
}

Reverse Words in String

Input: s = “i love programming very much”


Output: s = “much very programming love i”
// Java program to reverse a String
import java.util.*;
class TheTestingAcademy {

// Reverse the letters


// 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
int start = 0;
[Java Notes] - TheTestingAcademy
for (int (Pramod
end = 0; end < s.length; end++)Sir)
{
// If we see a space, we
// reverse the previous
// word (word between
// the indexes start and end-1
// i.e., s[start..end-1]
if (s[end] == ' ') {
reverse(s, start, end);
start = end + 1;
}
}

// Reverse the last word


reverse(s, start, s.length - 1);

// Reverse the entire String


reverse(s, 0, s.length - 1);
return s;
}

// 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

public class Calculator {


public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
[Java Notes] - TheTestingAcademy (Pramod Sir)
Calculator calculator = new Calculator();
int result = calculator.add(5, 3); // Calling the 'add' method
System.out.println("Result: " + result);
}
}

static String appDutta(String s){


System.out.println("Return with Param");
return s+"Dutta";
}

static String appDutta2(){


System.out.println("Return and Non Param");
return "Dutta";
}

static void print(String s){


System.out.println("Non Return with Param");
System.out.println("Print some"+ s);
}
static void print(){
System.out.println("Non Return and Non Param");
}

Practice -
● Prime Number
● Swap Two Numbers
● String reverse
● Take User input as array
● Maximum in Array
● Print diagonal Elements 2D array

📗 OOPs ( Java)

1. OOPs vs POP or PPL (Procedural oriented programming)


2. Object vs Functional
[Java Notes] - TheTestingAcademy (Pramod Sir)

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)

☯️ No Relation between the Struct(Global) and Functions.

How to Use Oops to Build Any Modern-Day Software

Consider this scenario: We are developing an Automation Tester Batch System.

1. Identify the objects


a. Like Student, Course, Payment.
2. Describe those with details
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
a. Student -> payment, Student -> Course, Course -> Payment
4. Now implement it via Class and Objects

Abstraction Example

● It is a design level concept.


● Example - PC Computer
[Javaa.Notes]
User - TheTestingAcademy (Pramod Sir)
b. Service Engineer (Hide price)

Object Oriented Programming


● Objects are the main building blocks of OOPS i.e your applications will be divided into multiple
objects.
● A class with
○ Data members
○ Methods -
● OOPs concepts apply now.
○ o Abstraction
○ o Encapsulation
○ o Inheritance
○ o Polymorphism
● Everything in the world is an object.

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 class Shape {


// fields (variables) and concrete methods can be defined in an abstract
class
protected String color;

public Shape(String color) {


this.color = color;
}
[Java Notes] - TheTestingAcademy (Pramod Sir)
// 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;
this.height = height;
}

// implementation of the abstract method defined in the superclass


@Override
public double getArea() {
return this.width * this.height;
}
}

class Circle extends Shape {


private double radius;

public Circle(double radius, String color) {


super(color);
this.radius = radius;
}

// implementation of the abstract method defined in the superclass


@Override
public double getArea() {
return Math.PI * this.radius * this.radius;
}
}

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

Class and Objects

https://docs.google.com/presentation/d/1pilgqDxrvs7KsFEOHyLBzF75Da3ZXYPvnPCHfG1Gk4s/edit?
usp=sharing

Inheritance

the different types of inheritance include:

1. Single Inheritance: A class inherits from a single base class.

2. Multiple Inheritance: A class inherits from multiple base classes.

3. Multilevel Inheritance: A class inherits from a derived class, forming a hierarchy


of inheritance.
[Java Notes]
4. Hierarchical - TheTestingAcademy
Inheritance: (Pramod
Multiple derived classes Sir) from a single base
inherit
class.

5. Hybrid Inheritance: A combination of multiple inheritance and multilevel


inheritance.

// Interface

Some Questions for Revision :

Question Answer

The purpose of a programming model is to provide a systematic approach to

develop computer programs. It defines the rules, principles, and guidelines to


Q1) What is the purpose of
be followed while designing and implementing software solutions. It also helps
any programming model?
programmers to organize their code and create efficient, reliable, and

maintainable applications.

Q2) What are the The programming models available to develop applications include procedure-

programming models oriented programming (POP), object-oriented programming (OOP), functional

available to develop programming (FP), event-driven programming (EDP), and aspect-oriented

applications? programming (AOP).

The main components of the Procedure Oriented Programming model include


Q3) What are the main
procedures or functions, which are a set of instructions that perform a specific
components of the
task, and data structures, which are used to organize and store data. POP
Procedure Oriented
follows a top-down approach, which means the program flow starts from the
Programming model?
main function and then calls other functions or procedures as required.

The limitations of the Procedure Oriented Programming model include a lack of


Q4) What are the limitations
data security, difficulty in maintaining and modifying code, and low reusability
of the Procedure Oriented
of code. POP is also not suitable for large-scale applications as the program
Programming model?
logic becomes complex and difficult to manage.

Q5) What is OOPs concept? OOPs (Object-Oriented Programming) is a programming concept that

emphasizes the use of objects, which are instances of classes, to represent


real-world entities and their behavior. OOPs focuses on encapsulation,
[Java Notes] - inheritance,
TheTestingAcademy (Pramod Sir)
and polymorphism to create reusable and modular code.

The main components of Object-Oriented Programming model include classes,

objects, encapsulation, inheritance, and polymorphism. Classes are used to


Q6) What are the main
define the attributes and behavior of objects, and objects are instances of
components of Object-
classes that represent real-world entities. Encapsulation provides data security
Oriented Programming
by hiding the implementation details of classes, while inheritance allows the
model?
creation of new classes by extending existing classes. Polymorphism enables

the use of the same code for different types of objects.

Q7) Who is the father of Alan Kay is considered the father of OOPs, as he introduced the concept of

OOPs? object-oriented programming in the 1960s.

The major principles of Object-Oriented Programming include inheritance,

encapsulation, abstraction, and polymorphism. Inheritance allows the creation


Q8) What are the major
of new classes by extending existing classes, encapsulation provides data
principles of Object-
security by hiding the implementation details of classes, abstraction allows the
Oriented Programming?
creation of complex systems by hiding unnecessary details, and polymorphism

enables the use of the same code for different types of objects.

Abstraction is a programming concept that involves hiding unnecessary details

and exposing only essential information. It allows the creation of complex


Q9) What is abstraction?
systems by breaking them down into smaller, manageable parts. In OOPs,

abstraction is achieved through the use of abstract classes and interfaces.

Encapsulation is a programming concept that involves hiding the

implementation details of classes and exposing only their interfaces or public


Q10) What is
methods. It provides data security by preventing unauthorized access to data
encapsulation?
and allows for easy modification of code without affecting other parts of the

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

of modular and scalable applications

Assignment - What happens if we do it

Class Book{
Int id;
String name;
String author;

Book s1 = new Book();

1. JVM allocates 8 bytes for each reference variable.


2. All variables are assigned a memory.
3. Referq

Abstract classes and methods

● Override the methods if the child extends the Parent or adds itself as Abstract.
● No object for Abstract, only reference.

Interfaces

1. Full Abstract - no implantation of any method apart from default.


2. Public static final variables
3. Public abstract methods.
[Java Notes] - TheTestingAcademy (Pramod Sir)

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

Important Class Members

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
{
[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;

public class StaticDemo {


int a = 10;
static int b= 20;
void m1(){
System.out.println(a);
System.out.println(b);
} [Java Notes] - TheTestingAcademy (Pramod Sir)
static void m2(){
//System.out.println(a);
System.out.println(b);
}
}

Static members can be accessed with Class Name.


Instance members can’t be accessed with class Name.

package atb.classdemo.staticdemo;

public class Main {


public static void main(String[] args) {
StaticDemo.m2(); // How?
}
}

Class Loaders

Moving the file from src file to memory


Class loaders are responsible for loading Java classes dynamically to the JVM (Java Virtual Machine)
during runtime.

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.

public class Student {


// data fields are private
private String name;
private int age;
private String address;
// public getter and setter methods for each field
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
} [Java Notes] - TheTestingAcademy (Pramod Sir)
public String getAddress() {
return this.address;
}

public void setAddress(String address) {


this.address = address;
}
}

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

● In Java Abstract is the keyword.


● Remember, abstract can be a class or method both.
● If the class doesn’t have any abstract method, then it is a concrete class.
● Abstract class cannot be final.
● An abstract class cannot be instantiated i.e. one cannot create an object of an abstract class.
● 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.
● Non-abstract/normal methods can be implemented in an abstract class.
● To use an abstract class it needs to be inherited from.
● The class which inherits from the abstract class must implement all the abstract methods
declared in the parent abstract class.
● An abstract class can have everything else as same as a normal Java class has i.e. constructor,
static variables and methods.
● You cannot use the following modifier with abstract methods:
Private, static, final, strictfp, synchronized, native.

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.

Default Methods in interfaces


● Default methods are methods that can have a body.
● 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 used to break.

default return type name () {}

- Solve the Diamond problem by Interface.super.methodName

Static methods in interfaces

static methods in interfaces are similar to default methods but the only difference is that you can’t override
them.

Problem to discuss to check Interface

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{ }
✅ Problem Statement
[Java Notes] - TheTestingAcademy (Pramod Sir)
Book class which has an abstract method getDetails(),name, author, price.
PrintMyBook class that inherits from the Book class.

abstract

Book myBook = new PrintMyBook("Harry Potter", "J.k. Rowling", "120");

// 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)

Static Nested Class

● Only a static member of the outer class can be accessed directly.


● Inside static nested class, static members can be declared.

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);
}
}
}

public class SNC {

public static void main(String[] args) {

OO.SNCI oo = new OO.SNCI();


oo.show();

}
}

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();
4. Static declaration is not allowed in the inner class
5. Static Inner class, Instance Inner class, Local Inner class, Anonymous inner class
[Java Notes] - TheTestingAcademy (Pramod Sir)
There are 4 ways you can create a Class
1. Inner Class
2. Method Level Inner Class
3. Nested Class
4. Anonymous Class

public class Car {


// outer class field
private String make;
private String model;

// inner class
public class Engine {
// inner class fields
private int horsepower;
private String fuelType;

// inner class constructor


public Engine(int horsepower, String fuelType) {
this.horsepower = horsepower;
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");
engine.start();

Upcasting and Downcasting in Class


You can assign a subclass object to the super type reference variable directly. This process is called
[Java Notes] - TheTestingAcademy (Pramod Sir)
UPCASTING.

class Parent{}
class Child extends Parent{}

Parent parent = new Parent(); // p1

Child child = new Child();


parent=child;
// Valid -> Upcasting

class Hello{}
class Child extends Hello{}

Hello hello = new Child();


Child hai=hello; // Invalid
Child hai= (Child)hello; // Valid ->Downcasting

Anonymous Inner class


It is an inner class without a name and for which only a single object is created.

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.

Test t = new Test()


{
// data members and methods
public void test_method()
{
........
........
}
}

● 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 declared as
final or effectively final.
● constructors can not be declared in an anonymous class.

[Java Notes] - TheTestingAcademy (Pramod Sir)

Types of Anonymous Inner Class


1. Anonymous Inner class that extends a class
2. Anonymous Inner class that implements an interface
3. Anonymous Inner class that defines inside method/constructor argument

Anonymous inner classes are generic created via below listed two ways as follows:

1. Class (may be abstract or concrete)


2. Interface

package thetestingacademy.oops.anonymousclass;

public class Anony02 {


public static void main(String[] args) {
// MyStudent myStudent = new MyStudent();
// myStudent.setId();

Student student = new Student() {


@Override
public void setId() {
System.out.println(id);
}
};
student.setId();
}
}

interface Student{
int id = 11;
void setId();
}

class MyStudent implements Student{

@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.

Primitive -> Wrapper , Primitive -> String ,Wrapper -> Primitive

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

Comparison of Autoboxed Integer

Integer x = 400, y = 400;


if (x == y)
System.out.println("Same");
else
System.out.println("Not Same");

// Les than 127


Integer x = 40, y = 40;
[Java Notes] - TheTestingAcademy (Pramod Sir)
if (x == y)
System.out.println("Same");
else
System.out.println("Not Same");

// JVM - values from -128 to 127 are cached, so the same objects are returned.

Integer x = new Integer(40), y = new Integer(40);


if (x == y)
System.out.println("Same");
else
System.out.println("Not Same");

Integer X = new Integer(10);


Integer Y = 10;

// Due to auto-boxing, a new Wrapper object


// is created which is pointed by Y
System.out.println(X == Y);

📕 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);
}
}

Solve the three problems in the above program.


1. Array.
2. Number format
3. Arithmetic.

Exception Handling in Java is a mechanism for handling runtime errors so that the application's
normal flow can be maintained.

Try and Catch


Attempt to catch the block.
[Java Notes] - TheTestingAcademy (Pramod Sir)

When Catch will be executed


Only when an exception in public class Ex02 is raised

public static void main(String[] args) {


try {
String name = null;
name.trim();
}catch (Exception e){
e.printStackTrace();
}
System.out.println("I am done");
}
}
Flow of the Exception Program
1. JVM calls Main Method.
2. If No Exception Execute and Skips Catch
3. If Exception, It created an Object of Exceptions.
4. Continue

⚠️ 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;

public class Ex03 {

public static void main(String[] args) {


try {
String ip = args[0];
int a = Integer.parseInt(args[0]);
int b = 10 / a;
} catch (NumberFormatException exception) {
exception.printStackTrace();
} catch (ArithmeticException exception) {
exception.printStackTrace();
} catch (ArrayIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}

Matching Catch it executes


If NumberFormat -> Number Ex
If Arth - Arth
If Array -> Array

⚠️
// Keep the Biggest at the last Exception E ( bigger basket)
P.S. - Please do not write anything between Try and Catch.

Please find the problem in this Code.

package thetestingacademy.exceptions;

public class Ex04 {


public static void main(String[] args) {
try {
int a = Integer.parseInt(args[0]);
[Java Notes] - TheTestingAcademy (Pramod Sir)
}
catch (NumberFormatException exception) {
exception.printStackTrace();
}
try {
int b = 10 / a;
}
catch (ArithmeticException exception) {
exception.printStackTrace();
}
try {
String ip = args[0];
}
catch (ArrayIndexOutOfBoundsException exception) {
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();
}

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
}

public class Main {


public static void main(String[] args) {
FileInputStream file = null;
try {
[Java
file Notes] - TheTestingAcademy (Pramod Sir)
= new FileInputStream("file.txt");
// read from the file
} catch (FileNotFoundException e) {
System.out.println("File not found!");
} finally {
file.close();
}
}
}

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.

Attempting to catch in the final is also permitted.

Yes

public static void main(String[] args) {


FileInputStream file = null;
try {
file = new FileInputStream("file.txt");
// read from the file
} catch (FileNotFoundException e) {
System.out.println("File not found!");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// handle the exception
}
}
}
}
Only in one case, If exit(0) is found, finally will not execute.

Problem 1

public class Ex06 {


public static void main(String[] args) {
ProblemF problemF = new ProblemF();
int x = problemF.show();
System.out.println(x);
}
}

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;

public class Ex06 {


public static void main(String[] args) {
ProblemF problemF = new ProblemF();
int x = problemF.show();
System.out.println(x);
}
}

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;

public class Ex08 {


public static void main(String[] args) {
try {
int a = 10 / 10;
} catch (Exception a) {
System.out.println("I am Catch 01");
} finally {
System.out.println("Finally 01");
}
try {
int a = 10 / 0;
} catch (Exception a) {
System.out.println("I am Catch 02");
} finally {
System.out.println("Finally 02");
}
try {
int a = 10 / 0;
} catch (Exception a) {
System.out.println("I am Catch 03");
System.exit(-1);
} finally {
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

package thetestingacademy.exceptions;

public class Exception02 {


public static void main(String[] args) {
extracted2();
System.out.println("MAIN Execute");
}
[Javastatic
private Notes] - TheTestingAcademy
void extracted2() { (Pramod Sir)
extracted1();
System.out.println("extracted2 Execute");
}

private static void extracted1() {


extracted();
System.out.println("extracted1 Execute");
}

private static void extracted() {


try {
// String name = null;
// name.length();

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();
}
}
}

Throw and Throws

● Till Now JVM created an Exception for us.


● Now We will do it

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();

throw new Object(); //Not Ok

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

(if main() method is not found upto jdk1.6.)

2) NoClassDefFoundError

(if class name is wrong while executing.)

3) StackOverflowError

In recursive method call, if memory is not available in stack.)

4) OutOfMemoryError

(While creating the object, if there is no memory in heap.)


int arr[]=new int[54453453];

5) UnsupportedClassVersionError

(If JVM version is lower then compiler version.)

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.)

Object ob1 = new Object();


String st1=(String)ob1;

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

Focus on Main Business Logic rather than Low Level Logics

Problem with Arrays


● Since we have to give size, memory is wasted.
● Insertion and deletion are heavy.
● No built-in support for sorting, searching.

We prefer below classes and Interfaces in place of Arrays.


Legacy APIs are provided
[Java Notes] - TheTestingAcademy (Pramod Sir)
Legacy Classes
● Vector
● Stack
● Properties
● Hash table
● Dictionary

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.

Advantages of the Collection Framework

● Reduces programming effort


● Increases program speed and quality
● Consistent API - add(), remove(), contains()

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

1. public abstract int size();


2. public abstract boolean isEmpty();
3. public abstract boolean contains(java.lang.Object);
4. public abstract java.util.Iterator<E> iterator();
5. public abstract java.lang.Object[] toArray();
6. public abstract <T> T[] toArray(T[]);
7. public abstract boolean add(E);
8. public abstract boolean remove(java.lang.Object);
9. public abstract boolean containsAll(java.util.Collection<?>);
10. public abstract boolean addAll(java.util.Collection<? extends E>);
11. public abstract boolean addAll(int, java.util.Collection<? extends E>);
12. public abstract boolean removeAll(java.util.Collection<?>);
13. public abstract boolean retainAll(java.util.Collection<?>);
14. public default void replaceAll(java.util.function.UnaryOperator<E>);
15. public default void sort(java.util.Comparator<? super E>);
16. public abstract void clear();
17. public abstract boolean equals(java.lang.Object);
18. public abstract int hashCode();
19. public abstract E get(int);
20. public abstract E set(int, E);
21. public abstract void add(int, E);
22. public abstract E remove(int);
23. public abstract int indexOf(java.lang.Object);
24. public abstract int lastIndexOf(java.lang.Object);
25. public abstract java.util.ListIterator<E> listIterator();
26. public abstract java.util.ListIterator<E> listIterator(int);
27. public abstract java.util.List<E> subList(int, int);
28. public default java.util.Spliterator<E> spliterator();
Arraylist
[Java Notes] - TheTestingAcademy (Pramod Sir)
● ArrayList allows duplicates and it is implemented as a resizable array.
● ArrayList elements will be stored internally using indexing notation.
● This is one of the most widely used concrete class.
● It is fast to access the elements, but slow to insert and delete the elements.

Array vs Vector

Vector

● Vector allows duplicates, and it is implemented as a resizable array.


● Vector is a legacy class and elements will be stored internally using indexing notation.
● Vector methods are synchronized, so vector objects can’t be accessed by multiple threads at a
time.(Slow)
[Java Notes] - TheTestingAcademy (Pramod Sir)

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)

Task ArrayList LinkedList Vector Stack

Order User added User added User added

Duplicate Vaue Yes Yes Yes

Null Value Yes Yes Yes

Random Access Yes No Yes

Sequential Access Yes Yes Yes

Iterator (used?) Yes Yes Yes

List Iterator Yes Yes Yes

Enumeration No No Yes

Index Representation Yes No Yes

Node Representation No Yes No

DeQue API can be used No Yes No

Serializable Yes Yes Yes

Cloneable Yes Yes Yes

For Each vs Iterator


In for-each loop, we can’t modify collection, it will throw a ConcurrentModificationException on the other
hand with iterator we can modify collection.

If we have to modify the collection, we can use Iterator.


Which is more efficient, a for-each loop, or an iterator? - Stack Overflow
Iterator [Java Notes] - TheTestingAcademy (Pramod Sir)
● used to iterate or traverse or retrieve a Collection or Stream object’s elements one by one and
called a Java Cursor is an Iterator.

three cursors in Java.

1. Iterator - For all


2. Enumeration - V
3. ListIterator - List

Methods in Iterator

Problem with Iterator


● In CRUD Operations, it does NOT support CREATE and UPDATE operations.
● only Forward direction.
● only Sequential iteration.

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;

public class SpliteratorDemo {

public static void main(String[] args) {

ArrayList<Integer> al = new ArrayList<>();


// Add values to the array list.
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) ->
System.out.println(n));
}

// Now, use the splitr


System.out.println("\nOutput from splitr1: ");
splitr1.forEachRemaining((n) -> System.out.println(n));

ArrayList<Integer> tempList = new ArrayList<>();


while(splitr1.tryAdvance((n) -> tempList.add(Math.abs(n))));
Spliterator<Integer> splitr2 = tempList.spliterator();
while(splitr2.tryAdvance((n) -> System.out.println(n)));

}
}

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 .

Check Implementation of Hash Set in Java doc

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)

Task Hashset LinkedHashSet TreeSet

Order No Order User added Default sort

Duplicate Vaue No No No

Null Value Yes Yes No

Synchronized No No No

Iterator (used?) Yes Yes Yes

List Iterator No No No

Enumeration No No Yes

Index Representation No No No

Node Representation No Yes No

NavigateableSet API used No No No

Serializable Yes Yes Yes

Cloneable Yes Yes Yes


Map [Java Notes] - TheTestingAcademy (Pramod Sir)
● Map is an interface available in java.util package and introduced in the Collection Framework API.
● a key and a value.
● The key is always unique in the Map.
● A Map cannot contain duplicate keys and each key can map to at most one value. Some
implementations allow null key and null values like the HashMap and LinkedHashMap, but some do
not like the TreeMap.
● The order of a map depends on the specific implementations. For example, TreeMap and
LinkedHashMap have predictable orders, while HashMap does not.
● There are two interfaces for implementing Map in java. They are Map and SortedMap, and three
classes: HashMap, TreeMap, and LinkedHashMap
● Map hm = new HashMap();
● Map interface has following concrete sub classes:
○ o HashMap
○ o LinkedHashMap
○ o TreeMap
○ o Hashtable

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.

No Duplicate Key on HashMap

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

● It is similar to HashMap, but is synchronized.


● Hashtable stores key/value pairs in hash table.
● In Hashtable we specify an object that is used as a key, and the value we want to associate to that
key. The key is then hashed, and the resulting hash code is used as the index at which the value is
stored within the table.
● The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
● HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast Enumeration

Sort HashMap by Keys

● By using TreeMap
● By using LinkedHashMap
● Sort HashMap by Values
● Sort HashMap by Values using Comparator Interface
[Java Notes] - TheTestingAcademy (Pramod Sir)

● Count Occurance of Character in the given String


● Count Occurance of Word in the given String

What are the main differences between array and collection?

● 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

What is the difference between Set and Map?


● Set contains values only whereas Map contains key and values both.
● Set contains unique values whereas Map can contain unique Keys with duplicate values.
● Set holds a single number of null value whereas Map can include a single null key with n number
of null values.

What is the difference between HashMap and Hashtable?


[Java Notes] - TheTestingAcademy (Pramod Sir)

What is the difference between Collection and Collections?

● The Collection is an interface whereas Collections is a class.


● The Collection interface provides the standard functionality of data structure to List, Set, and
Queue. However, Collections class is to sort and synchronize the collection elements.
● The Collection interface provides the methods that can be used for data structure whereas
Collections class provides the static methods which can be used for various operation on a
collection.
● new Student(); ox2323232, Student0x23323

What does the hashCode() method?


● The hashCode() method returns a hash code value (an integer number).
● The hashCode() method returns the same integer number if two keys (by calling equals() method)
are identical.
● However, it is possible that two hash code numbers can have different or the same keys.
● If two objects do not produce an equal result by using the equals() method, then the hashcode()
method will provide the different integer result for both the objects.

.
How to synchronize List, Set and Map elements?

1. public static List synchronizedList(List l){}


2. public static Set synchronizedSet(Set s){}
3. public static SortedSet synchronizedSortedSet(SortedSet s){}
4. public static Map synchronizedMap(Map m){}
5. public static SortedMap synchronizedSortedMap(SortedMap m){}

What is the default size of load factor in hashing based collection?


The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For
[Java Notes] - TheTestingAcademy (Pramod Sir)
example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.

Collection Framework QnA

How do you copy one ArrayList to another?


Using the addAll() method: You can use the addAll() method to add all elements of the original ArrayList to
the new ArrayList. Example: ArrayList<Integer> copiedList = new ArrayList<>();
copiedList.addAll(originalList);

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));

How do you check if an element exists in an ArrayList?

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)

Multitasking vs Multithreading vs Multiprocessing

public class Task02 {


public static void main(String[] args) throws InterruptedException
{

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)

Flow of Java program


1. Java Task02 123
2. The JVM asks the OS for the memory.
3. If the OS allocates the memory -> JVM adds Stack, Heaps.
4. JVM creates 2 thread groups, Main and System (2-3 threads). (GC, finalizer)
5. JVM adds the main thread to the main group.
6. JVM started the main thread. The main thread will do the program task.
7. Check whether Task02 .class is available or not.
8. ByteCode verification will be done.
9. Collect parameters ( 123 ).
10. Verify that the main method is present.
11. Create a String array and store command-line args.
12. Invokes ClassName.main() ( Task02.main()) by JVM
13. The main thread will execute your program.
14.
15. JVM will sJVM will clear garbagehut down.

Main Thread - Main Method

There are two ways you can create the Threads in Java.

1. Extend Thread
2. Runnable

package thetestingacademy.multithreading;

public class Task03 {


public static void main(String[] args) {

Worker worker = new Worker();


worker.start();
// Where is the Start ?
Worker worker2 = new Worker();
worker2.start();
} [Java Notes] - TheTestingAcademy (Pramod Sir)
}

class Worker extends Thread{

@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(ThreadGroup, String);


Creates a new Thread object by specifying the ThreadGroup name.

● public Thread(Runnable);
Creates a new Thread object. When started then run() will be invoked from specified Runnable
object.

● public Thread (Runnable, String);


Creates a new Thread object by specifying the Runnable object and thread name.

● public Thread(ThreadGroup, Runnable);


Creates a new Thread object by specifying the threadgroup Runnable object.

● public Thread(ThreadGroup, Runnable, String);


Creates a new Thread object by specifying the ThreadGroup, Runnable object and thread name.

Methods from ThreadGroup Class


● public final String getName() Returns the name of this thread group.
● public final ThreadGroup getParent() Returns the parent of this thread group
● public final boolean parentOf(ThreadGroup)
Tests if this thread group is either the thread group argument or parent of that thread group
● public final int getMaxPriority() Returns the maximum priority of this thread group.
● public final void setMaxPriority(int) Sets the maximum priority of the group.
● public final boolean isDaemon() Tests if this thread group is a daemon thread group.
● public final void setDaemon(boolean) Changes the daemon status of this thread group.
● public synchronized boolean isDestroyed()
Tests if this thread group has been destroyed.
● public int activeCount() Returns an estimate of the number of active threads in
this thread group and its subgroups.
● public final void stop() Stops this thread group.
[Java Notes] - TheTestingAcademy (Pramod Sir)

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
● static final int MAX_PRIORITY Constant represents maximum priority of a thread

Methods from Thread Class


[Java Notes] - TheTestingAcademy (Pramod Sir)

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)

You can create your own Thread Group also

Constants from Thread.


State enum
NEW RUNNABLE BLOCKED
WAITING TIMED_WAITING TERMINATED

Thread Life CYCLE

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.

- Withdraw example for the Synchronization

Method Level Synchronization


● Applying synchronized keyword to the method is called Method Level Synchronization.
● You can apply synchronized keyword for both instance methods and static methods.
● When instance method is synchronized then the object which is used to invoke the synchronized
method will be locked by the current thread.
● When static method is synchronized then the default object of the invoking class will be locked by
the current thread.
public synchronized void show(){ ... }
[Java Notes] - TheTestingAcademy (Pramod Sir)
Block Level Synchronization

● 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{

ArrayList al = new ArrayList();


void show(){ ...
synchronized(al){ ... } ...
}
}

Important points for the Synchronization

● Case 1
● Case 2
● Case 3
● Case 4
● Case 5
● Case 6

Deadlocks

Solution in ATBNotes.zip (or Github URL)

package thetestingacademy.multithreading.deadlock;

public class ThreadDeadLock {

public static void main(String[] args) {


final String resource1 = "ATB";
final String resource2 = "MTB";
// t1 tries to lock resource1 then resource2
[Java Notes]
Thread - TheTestingAcademy
t1 = new Thread() { (Pramod Sir)
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");

try {
Thread.sleep(100);
} catch (Exception e) {
}

synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: 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.

● wait() method is an instance method available in java.lang.Object class.


● When you call wait() method on any locked object then lock of that object will be released
● immediately and the current thread will be moved to WAIT state.
● Following are the wait() methods defined in Object class:
○ o public final void wait()
○ o public final native void wait(long ms)
○ o public final void wait(long ms, int ns)
● If you call wait() method on unlocked object then java.lang.IllegalMonitorStateException
● will be thrown at runtime
package thetestingacademy.multithreading.synchronization.WaitDemo;
[Java Notes] - TheTestingAcademy (Pramod Sir)
public class WaitDemo {

public static void main(String[] args) {

WaitForMe waitForMe = new WaitForMe();

CustomThread customThread = new CustomThread(waitForMe, "A");


CustomThread customThread2 = new CustomThread(waitForMe, "B");

customThread.start();
customThread2.start();
}
}

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) {
// for (int i = 1; i <= 5; i++) {
// System.out.println(th.getName() + " - show -" + i);
// try {
////this.wait(1000);
// al.wait(1000);
// } catch (Exception ex) {
// System.out.println(ex);
// }
// }
// }
// }
}

class CustomThread extends Thread {


WaitForMe wait;
[Java
public Notes] - TheTestingAcademy
CustomThread(WaitForMe wait, String(Pramod
name) { Sir)
super(name);
this.wait = wait;
}

@Override
public void run() {
wait.show();
}
}

Notify & NotifyAll()

● These methods are instance methods available in java.lang.Object class.


● When you call notify() method on any locked object then following task will happen:
○ Only one thread which has been waiting for long time will be picked.
○ Checks whether the resources released by the thread are available or not.
○ If resources are available, then the thread acquires the resources and goes to READY TO
RUN state.
○ If resources are not available then the thread goes to BLOCKED state.

● 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.

Code sample at ATBNotes.zip

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)

What is the finalizer Thread?

● 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.

Can I overload the run() method in thread class?

Overloading of run() method is possible

Can I define the run() method as synchronized?

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.

Can I define a thread class without overriding the run () method?

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.

How do I pause thread execution for specified amount of time?

sleep() method can be used to pause the execution of the current thread for a specified time in
milliseconds.

What is the difference between sleep() and wait() method?

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)

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.

You might also like