0% found this document useful (0 votes)
66 views158 pages

-Java Notes- - TheTestingAcademy (Pramod Sir)

The document provides an overview of Java, highlighting its features, security, and the differences between Java and other programming languages. It explains key concepts such as source code, bytecode, and the roles of JDK, JRE, and JVM in Java development. Additionally, it covers installation instructions, Java editions, and the evolution of Java versions with their key features.

Uploaded by

biplab.09052005
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)
66 views158 pages

-Java Notes- - TheTestingAcademy (Pramod Sir)

The document provides an overview of Java, highlighting its features, security, and the differences between Java and other programming languages. It explains key concepts such as source code, bytecode, and the roles of JDK, JRE, and JVM in Java development. Additionally, it covers installation instructions, Java editions, and the evolution of Java versions with their key features.

Uploaded by

biplab.09052005
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/ 158

​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

y
platform using the Java Virtual Machine. Because of this, Java is also known as a
WORA (Write Once, Run Anywhere)

m
●​ Java Version - https://en.wikipedia.org/wiki/Java_version_history
●​ High Level, Platform independent & Architecture Neutral

de
●​ Secure, Robus, Multi Thread, Distributed and OOPs language.

ca
⚠️ Why Java is not 100% Object-Oriented?
gA
●​ Primitive data types.
●​ Use of Static.
●​ Wrapper class
tin

⚠️ How is Java ​Secure?


es

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


●​ Oops and inner classes
eT

Ref - https://www.scaler.com/topics/why-java-is-not-100-object-oriented/
Th

Important Points

●​ Since Java applications can run on any kind of CPU so it is architecture – neutral.
●​ Java program can be executed on any kind of machine containing any CPU or any
●​ operating system.
●​ Java is robust because of following: Strong memory management(Garbage
Collector) No Pointers Exception handling Type checking mechanism Platform
Independent.
●​ Using RMI and EJB we can create distributed applications in java

y
m
de
ca
gA
Check the Languages, with the Level of Abstraction
tin
es
eT
Th
Major Features of Java Programming Language

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

y
m
⚠️ What is Source Code?

de
Human understandable code written using High Level Programming language is called as
Source Code. (NameOfFile.java)

⚠️ What is Byte Code?


ca
JVM understandable code generated by Java Compiler is called as Byte Code. Byte code is
also called as Magic Value.
gA
⚠️ 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.
tin

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

⚠️ What is Java Compiler?


eT

Java Compiler is a program developed in C or C++ programming language with the name
“javac”. It will check syntactic or grammatical errors of the programs. It converts source
code to byte code.
Th

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

y
How to Set JAVA_HOME path in MAC - Click here

m
1.​ Download the JDK latest - ​

de
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile
2.​ If you're using zsh (which probably means you're running macOS Catalina or
newer), then it should instead be:

ca
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.zshrc
3.​ In either case, restart your shell.
gA
brew install openjdk
tin

How to Set JAVA_HOME path in Windows


es

Set the JAVA_HOME Variable

https://www.oracle.com/java/technologies/javase/jdk21-archive-downloads.html
eT

To set the JRE_HOME or JAVA_HOME variable:


Th

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​

y
m
de

ca
Note for Windows users on 64-bit systems​
Progra~1 = 'Program Files'​
Progra~2 = 'Program Files(x86)'
gA
7.​ Click OK and Apply Changes as prompted

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


tin

It is a set of various utility programs which are required for developing and executing the java
es

programs.
It is Platform dependent. Various JDKs are provided for various Operating Systems.
Following are various utility programs provided under JDK:
eT

1) Java Development Tools


i. javac
ii. java
Th

iii. javap
iv. Jar
etc
2) Source Files
3) JRE
etc

⚠️ What is JRE?
Ans: JRE stands for Java Runtime Environment. It is an implementation of JVM. It contains
class
libraries, Interpreter, JIT Compiler etc. Only JRE is enough to run the Java program
⚠️ What is JVM?
Ans: JVM stands for Java Virtual Machine. It is a specification provided by SUN Microsystem
whose
implementation provides an environment to run our Java applications. JVM becomes an
instance of
JRE at run time.
Sun’s implementations of the Java Virtual Machine (JVM) is itself called as JRE. Sun’s JRE
is availabe
as a part of JDK and also as a separate application.
Many vendors has implemented JVM. Some of them are SUN JRE, IBM JRE, Oracle JRE

y
etc

m
de
ca
gA
tin
es
eT

JDK Vs JRE
Th
y
m
de
ca
Java Editions
gA
1.​ Enterprise Edition - Banking, Application,Servlets, JSP, JDBC etc.
2.​ Micro Edition - micro devices like Mobiles,Setup Box etc
3.​ Standard Edition - Used to develop standalone applications using applet and swing.
tin
es

Edition Description
eT

Java SE The main edition of Java that is used for desktop and server applications. It
Th

(Standard includes the Java language, JVM, class libraries, and tools for developing, testing,

Edition) and deploying Java applications.

Java EE A set of specifications and APIs for developing enterprise applications, including

(Enterprise web and mobile applications, distributed systems, and cloud computing. It

Edition) includes components like servlets, JSPs, EJBs, JMS, JPA, and more.
A platform for developing applications for mobile and embedded devices, like

Java ME (Micro phones, PDAs, and set-top boxes. It includes a subset of the Java SE APIs and

Edition) tools, as well as additional libraries for mobile-specific features like user

interfaces and networking.

A platform for developing rich client applications and user interfaces, with features

y
Java FX like graphics and media support, animation, and web integration. It includes a set

m
of APIs and tools for developing desktop, mobile, and web applications.

de
ca
Note that Java EE has been rebranded as Jakarta EE, as Oracle transferred ownership of
the Java EE specification to the Eclipse Foundation.
gA

Java Versions
tin
es

Java Version Key Features


eT

Java 1.0 Garbage collection, multi-threading, network programming


Th

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

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

m
Java 9 Module system, private interface methods, JShell

de
Java 10 Local variable type inference, garbage collector improvements

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

Java 12 Switch expressions, garbage collector improvements


tin

Java 13 Text blocks, Z Garbage Collector improvements


es
eT

Java 14 Record classes


Th

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

y
A comment that extends from the // marker to the end of the line. It

m
Single-line
// comment is ignored by the compiler and used for adding notes and
comment
explanations to the code.

de
A comment that can span multiple lines, starting with the /* marker
Multi-line

comment ca /* comment

*/
and ending with the */ marker. It is also ignored by the compiler and

used for adding longer explanations or temporarily disabling code.


gA
A comment that begins with /** and ends with */. It is similar to a
tin

Documentation /** multi-line comment, but it is specifically used for generating API

comment comment */ documentation with tools like Javadoc. It can include tags like

@param, @return, @throws, etc.


es

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


eT

includes additional Javadoc tags for generating documentation. It

Javadoc comment /** can be used to describe classes, interfaces, methods, fields, etc.
Th

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

y
m
de
ca
gA

⚠️ Differences between Oracle JDK and OpenJDK


tin

Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.
es

Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly
to replace licensed proprietary parts / replace with more high-performance items that only
work on specific OS] components without breaking the TCK compatibility.
eT

https://stackoverflow.com/questions/22358071/differences-between-oracle-jdk-and-openjdk
Th

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

y
⚠️ Which JRE will be used while compiling the Java Source File?

m
The JRE is not used for compiling Java source files, but rather the Java Development Kit
(JDK) is used, specifically the Java compiler (javac) which is included in the JDK.

de
⚠️ What will happen when I am compiling Java program without PRIVATE JRE?
Compiling a Java program does not require a PRIVATE JRE. However, if the program

ca
requires a specific version of the JRE to execute, and that version is not installed on the
system, the program may not run properly.

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


gA
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?
tin

If a PUBLIC JRE is not installed on the system, the Java application will not be able to run.
The user will need to install a JRE before the application can be executed.
es

⚠️ Can we execute java program without setting PATH?


It is possible to execute a Java program without setting the PATH, but it requires specifying
eT

the full path to the Java executable file every time the command is executed.

⚠️What is the difference between JVM and JRE?


Th

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

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

m
Yes, it is possible to install multiple JRE (Java Runtime Environment) versions on the same
machine. It is important to manage the PATH and other environment variables correctly to

de
ensure that the correct version is used

ca
​Explain the main method in Java
gA
●​ The main method in Java is the entry point for any Java program.
●​ It is a predefined method that is executed when a Java program is run, and is
required in every Java program.
tin

●​ The main method has a specific signature, which includes the keyword "public", the
keyword "static", the return type "void", and a parameter of type "String" array named
"args". Here is an example of the main method signature:
es

●​ public static void main(String[] args) {


●​ // code to be executed
●​ }
eT

●​ The main method takes an optional argument, "args", which is an array of strings that
ca
●​ n be used to pass command-line arguments to the program.
Steps that the JVM takes to call the main method:
Th

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

y
m
de
ca
gA
tin
es
eT

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

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.

y
m
Types of Variables
There are two types of variables based on data type used to declare the variable.

de
1) Primitive Variables
2) Reference Variables

ca
gA
tin
es
eT
Th
y
m
de
Some Points

ca
●​ A variable is a storage location paired with an associated symbolic name (an
identifier), which contains some known or unknown quantity of information referred to
as a value.
gA
●​ Variables in Java are strongly typed; thus they all must have a data type declared
with their identifier

●​ There are three rules to create an identifier:


tin

○​ 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 _
es

(underscore).

int $ = 34; // 44 - Yes


eT

// int _pramod = 34; // Yes


// int 123 = 34; // NO
// int 123_name = 34; // NO
Th

// int 1name = 34; // no


//int #1 = 34; // No
// System.out.println($);

Primitive Variables
●​ Variables declared with primitive data types are called primitive variables.
●​ ​ int a; int b = 99; double d1; double d2=9.9;
Reference Variables - Variables declared with user defined data types are called as
reference variables.
String str1;
String str2 = “TheTestingAcademy”;
Based On SCOPE variables are 3 types

●​ Instance Variables : Variables declared in the class without using static keyword are
called as Instance Variables.
●​ Static Variables : Variables declared in the class using static keyword are called as
Static variables.
●​ Local Variables - Variables declared in the member of the class like method etc are
called as Local variables.

y
m
de
ca
gA
tin
es
eT
Th

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

Primitive data types


They are the basic data types in Java and are used to store simple values.

y
m
de
ca
gA
tin
es
eT
Th

There are eight primitive data types in Java, which are categorized into four groups: integer,
floating-point, character, and boolean.
Data Type Size (bits) Default Value Example

byte 8 0 byte b = 10;

short 16 0 short s = 100;

y
m
de
int 32 0 int i = 1000;

long ca 64 0L long l = 100000L;


gA

float 32 0.0f float f = 1.23f;


tin
es

double 64 0.0d double d = 1.23;


eT

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


Th

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:

y
m
de
ca
gA
Reference data types are used to store complex objects, such as arrays and classes. These
data types are created using predefined or custom classes.
tin

User Defined Data types

Four types of User Defined Data types:


●​ Class type - String
es

●​ Interface type
●​ Enum type (From JAVA 5)
●​ Annotation type (From JAVA 5)
eT
Th
Types of Variables There are two types of variables based on data type used to declare the
variable.

1) Primitive Variables - Variables declared with primitive data types are called as primitive
variables.

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

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

y
called as reference variables

m
String str; Hello h;

de
✅ Constants
ca
●​ Special variable whose value can't be modified during the program execution.
●​ Constant is also called as final variable.
gA
final int A=99;
final String STR="TTA";
final double D1=999.99;
tin

Variables & Constants


1) Default value of char is either ASCII - 0 or UNICODE \u0000.
es

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

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

8) Instance variable cannot be accessed directly from Static method (main method).
9) You can't declare multiple variables of different data types in single variable declaration
statement.
10) You can declare multiple variables of same data types in a single statement.
11) You can assign same value to multiple variables in a single statement.
12) You can declare and initialize multiple variables of same data type in a single statement.
13) We can't declare two variables with same name in same scope.
14) Value of the variable can be changed any number of times during program execution.
15) Value of the final variable can not be changed.
16) We can't use const keyword to declare constant.
Q1 How many keywords are available prior to Java 5? 48

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

y
B) goto

m
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

de
Long H) false I) virtual J) signed J) signed

Q4
ca
What are the keywords available which can’t be used in
goto, const
gA
Java Program?

An identifier is a name assigned to


tin

a variable, method, class, or

package. The rules to follow while


es

defining an identifier are: i) It


What is an identifier? What are the rules to follow to
Q5 should start with a letter or
define an identifier?
underscore, ii) No whitespace or
eT

special characters allowed except

underscore, iii) It should not be a


Th

reserved keyword.

Data type defines the type of value

a variable can hold. There are two


What is data type? How many types of data types
Q6 types of data types: i) Primitive
available?
data types, ii) Reference data

types.
Q7 How many primitive data types available? 8

What is the Integral data type that will not allow negative
Q8 char
value?

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

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

ca and char is unsigned.


gA
How many types of User defined data types available up
Q11 2
to JDK1.4?
tin
es

How many types of User defined data types available


Q12 1
from Java 5?
eT

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


Th

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

What are the possible values can be used for boolean


Q15 true or false
type?
A variable is a container that stores
Q16 What is a variable?
values.

How many types of variables are available as per the


Q17 2
data type?

How many types of variables are available as per the

y
Q18 3
scope?

m
de
Primitive variables hold the actual

What are the differences between Primitive variables and values, while reference variables
Q19

ca
Reference variables? hold the memory location of the

object.
gA
There is no default value for a local

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

before use.
tin

Not possible. Variables must be


How can I declare multiple types of variables in one
es

Q21 declared separately for each data


statement?
type.
eT

Multiple variables of the same type

How can I declare multiple variable of same type in one can be declared in one statement
Th

Q22
statement? by separating each variable name

with a comma.

Declare and initialize a variable in


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

variables of the same type in one

How can I declare and initialize multiple variables of statement by separating each
Q24
same type in one statement? variable name with a comma and

assigning a value to each variable

when it is declared.

Can I change the value of variable during program


Q25 Yes

y
execution?

m
de
Memory for variables is allocated

Q26 When will the memory be allocated for the variables? at runtime, while the program is

executing.

ca
gA
UNICODE Characters
tin

●​ UNICODE stands for UNIversal CODE.


●​ Every character will have UNICODE value.
●​ UNICODE Notation
es

●​ Syntax:
○​ \uXXXX - X will be hexadecimal digit
●​ Starts with \u followed by four hexadecimal digits.
eT

●​ ​ UNICODE Range
●​ ​ \u0000 (0) to \uFFFF (65535)
Th
Th
eT
es
tin
gA
ca
de
m
y
Practice QnA

Give the output of the following in the following

1.​ It will not compile.


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

y
Question 1
int enum=9;

m
System.out.println(enum);

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

ca
gA
tin
es
eT
Th

✅ Literals
●​ Literals are the actual values assigned
●​ Literals can be Numeric and Non Numeric.
Literal Type Description

Integer literals Whole numbers without decimal points, such as 42 or -123

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

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

ca
gA
Boolean literals A value of either true or false
tin

String literals A sequence of characters enclosed in double quotes, such as "hello world"
es

Null literals A special literal that represents a null reference or a null value
eT
Th

Types of Literals
1) Boolean Literals - true, false
2) Character Literals -
3) String Literals
4) Integral Literals
5) Floating Literals
6) null Literal

1. Boolean Literals
There are two boolean literals 1) true 2) false
2. Character Literals
A char type variable can hold following:
●​ Single character enclosed in single quotation marks
●​ Escape Sequence
●​ ASCII Value
●​ UNICODE Character
●​ Octal Character

Diff between /n and /r

y
https://stackoverflow.com/questions/1761051/difference-between-n-and-r

m
de
Escape Sequence - Task_12.java

ca
gA
tin

ASCII stands for American Standard Code for Information Interchange.


es

●​ Every character enclosed in single quotation marks will have an integer equivalent
value
●​ called as ASCII value.
eT

●​ ASCII Value Range is 0 – 255.


●​ ASCII Value can be assigned to a char type variable
Th

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
y
m
de
ca
gA
tin
es
eT
Th

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.

There are six types of literals available in programming


How many types of literals are
languages: numeric literals, character literals, boolean literals,
available?
string literals, array literals, and null literals.

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

available? false.

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

ca
What will happen when I assign 1

to boolean type variable?


interpreted as true because any non-zero value is considered as

true in boolean expressions.


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

char type variable? because it requires at least one character.


tin

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


es

How to store single quote in char


escape sequence ' because the single quote is a reserved
variable?
character in programming languages.
eT

An escape sequence is a combination of characters used to


Th

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 represents the Unicode value of the letter A.

is \u0041";
What will be displayed when Octal

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

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"

Sequence is found in String will be displayed on the next line because \n represents the

Literal? String str="Hello\nGuys"; newline character.

y
m
Integer Literals

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


Scientific / Exponent N Literals
float f = 129.8763e2F;
tin

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

System.out.println(d1);
System.out.println(d2);
eT

Null literal
Th

●​ null is a value.
●​ It is default value for any reference variable.
●​ If the value of reference variable is null then it indicates that address/reference is not
●​ available in the variable.

String str2=null;
System.out.println(str1);
✅ Operators
Operators are used to perform operations by using operands.
There are three types of operator depending on the number of operands required.
●​ 1) Unary Operator
○​ Only one operand is required.
●​ 2) Binary Operator

y
○​ Two operands are required.
●​ 3) Ternary Operator

m
○​ Three Operands are required. ​

de
Types of operator depending on the operation:
●​ Arithmetic Operators
○​ i. Unary Arithmetic Operators
○​ ii. Binary Arithmetic Operators

ca
●​ String Concatenation Operator
●​ Assignment Operator
○​ i. Simple Assignment Operator
gA
○​ ii. Compound Assignment Operators
●​ Increment & Decrement Operators
●​ Relational Operators
●​ Logical Operators
tin

●​ new Operator
●​ instanceof Operator
●​ Conditional or Ternary Operator
es

●​ Bitwise Operators.
eT

Unary Arithmetic Operators


Th

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

y
m
de
ca
Remember this

gA
tin
es
eT
Th
String Concatenation Operator (+)
+ operator can be used for two purposes:
1) Arithmetic Addition
2) String Concatenation

Simple Assignment Operator (=)


It is a binary operator.
It is used to assign the value to a variable. =

y
o Operand1 must be a variable.
o Operand2 can be a variable, value or expression.

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

Type casting can be done in two ways:


tin

o Implicit casting
o Explicit Casting
es

Type casting can be done in two ways:


o Implicit casting
eT

o Explicit Casting

Implicit casting:
When type casting is happening automatically by the compiler then it is called as Implicit
Th

Casting.

Explicit Casting:
When type casting is happening explicitly by the programmer then it is called as Explicit
Casting.
There are two types of conversions:
o Widening
o Narrowing

Widening
Widening is the process of converting lower type to higher type. This is a safe conversion.
Ex:
byte b=10;
int a=b; // VALID – Implicit Casting
int a= (int)b; // VALID – Explicit Casting

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

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

m
00000000000000000000000100101100
byte b1=(byte)a; -> byte means 8 bits memory required

de
00101100
Value is
0 + 0 + 32 + 0 + 8 + 4 + 0 + 0 = 44.​

ca
(00101100)₂ = (0 × 2⁷) + (0 × 2⁶) + (1 × 2⁵) + (0 × 2⁴) + (1 × 2³) + (1 × 2²) + (0 × 2¹) + (0 × 2⁰)
= (44)₁₀
gA

Compound Assignment Operators


tin

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


es
eT
Th

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.
Relational Operators

y
m
Logical Operators

de
ca
gA
tin
es
eT
Th
Logical OR and Logical AND ( || , &&

y
m
de
ca
gA
new Operator
●​ new operator is used to create the new object for class.
tin

●​ It returns of the address of newly created object.


●​ String s1 = new String(“Pramod”);
es

instanceof Operator
●​ It is used to check whether the given object belongs to specified class or not.
●​ Result of instanceof operator is boolean value.
eT

●​ It returns true if given object belongs to specified class otherwise false.


●​ It is also called aCOMPARISONERATOR.
●​ System.out.println(s1 instanceof Object);
Th

Conditional Operator
●​ It is ternary operator. ? : Operand1 must be of boolean type.
●​ If Operand1 is true then Operand2 will be returned otherwise Operand3 will be
returned.

Bitwise Operators
y
m
de
ca
Bitwise AND o Bitwise OR o Exclusive OR (XOR)
gA
https://bit-calculator.com/bit-shift-calculator
tin

1.​ 7+ (6 + 5 *3) - 4/2


2.​ boolean b = (boolean)1; b)
3.​ String str=(String)99;
es
eT
Th

Interview QnA

Question Answer
Bitwise operators are used to perform bitwise
What is the use of bitwise operators?
operations on binary representations of integers.

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

operation? always a String.

y
What will happen when I try to assign int type The code will not compile because you cannot assign

m
to String type variable? Ex: String str=99; an int value to a String variable directly.

de
What are types of operands allowed for Comparison operators can be used with numeric and

comparison operators? boolean operands.

ca The prefix form increments the value before it is used,


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

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
es

available? conversion (implicit) and narrowing conversion

(explicit).
eT

The new operator is used to create an instance of a


Th

What is the use of new operator?


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

y
Implicit casting is done automatically by the compiler,

m
What is the difference between Implicit
while explicit casting requires the programmer to
casting and Explicit Casting?
specify the conversion explicitly.

de
The assignment operator is used to assign a value to a

ca
What is the use of assignment operator?
variable or an array element.
gA
2's complement is a way of representing negative

What is 2's Complement? integers in binary. It involves flipping all the bits and
tin

adding 1 to the result.


es

What are types of operands allowed for Arithmetic operators can be used with numeric

arithmetic operators? operands (int, long, float, double) and char operands.
eT

What is the difference between unary Unary arithmetic operators act on a single operand,
Th

arithmetic and binary arithmetic operators? while binary arithmetic operators act on two operands.

What is the syntax of Explicit casting? The syntax of explicit casting is: (datatype) value.

What are types of operands allowed for Bitwise operators can be used with integer operands

bitwise operators? (int, long, short, char, byte).


The logical NOT operator (!) is used to negate a
What is the use of Logical NOT operator?
boolean value.

The prefix form decrements the value before it is used,


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

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

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

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

ca
What is result type when you add long and The result type when you add long and float variables is
gA
float variables? float.
tin
es

Question Answer
eT

An operator is a symbol that represents a specific operation


What is an operator?
to be performed between operands.
Th

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

"Infinity" 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
The result type is a float.
long 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.

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

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

de
What is the result of instanceof The instanceof operator returns true if an object is an

operator? instance of a particular class, or a subclass of that class.

ca Bitwise operators are used to perform operations at the bit


gA
What is the use of bitwise operators?
level.
tin

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
types available?
es

and explicit casting.


eT

What will happen when I try to assign int It will result in a compilation error because they are

type to String type variable? incompatible types.


Th

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

operator? 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?
What is the use of Logical NOT The logical NOT operator is used to reverse the truth value of

operator? a 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

y
operators available? bitwise operation with an assignment.

m
de
2's complement is a binary representation of a signed number
What is 2's Complement?
that uses the most significant bit as a sign bit.

ca
What are types of operands allowed for

bitwise operators?
Bitwise operators can be applied to integer types: byte, short,

int, and long.


gA

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

The relational operators compare two values and return a


es

What are the relational operators?


boolean result: <, >, <=, >=.
eT

What is result type when you add byte


The result type is an int.
and int variables?
Th

What are the bitwise operators


The bitwise operators are: &,
available?

What is the difference between prefix The prefix form evaluates and returns the value after the

and postfix forms of decrement operation, while the postfix form evaluates and returns the

operator? value 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


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

Widening casting occurs when you convert a smaller type to a

y
What is the difference between
larger type, while narrowing casting occurs when you convert

m
Widening and Narrowing?
a larger type to a smaller type.

de
ca ✅ Conditions and Loop
gA
If​
condition -> true or false
if(condition)
tin

{ // Statements (IF BLOCK) }

Problem to find the Even and Odd with % Mod


es

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

else
System.out.println("Value is ODD");
}
Th

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);
y
m
de
ca Switch : Multi-way branch statement
gA
●​ [ ] 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.
tin

●​ [ ] 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
es

// switch statement
switch(expression)
eT

{
// case statements
// values must be of same type of expression
Th

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
}

String browser = "chrome"


switch(browser){
case "chrome" :
​ ​ ​ sop("chrome started!!");
break;

●​ Default fall through due to missing break - JDK 13

y
Much improved switch accepts multiple values per case.

m
switch (itemCode) {

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

ca
case 004, 005:
System.out.println("It's a mechanical device!");
gA
}
tin

●​ yield is used to return a value

A new keyword yield has been introduced. It returns values from a switch branch only.
es

We don’t need a break after yield as it automatically terminates the switch expression.

int val = switch (code) {


eT

case "x", "y" :


yield 1;
case "z", "w" :
Th

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!");​
case 003,004 -> System.out.println("It's a mobile phone!");​

y
}

m
de
ca
gA
tin
es
eT
Th
For

1.​
Th
eT
es
tin
gA
ca
de
m
y
While
●​ condition of while statement is mandatory and must be boolean type

y
m
de
Do While ca
gA
●​ When you are using for statement or while statement then it verifies the condition
before executing the block.
●​ So in the case of for statement and while statement, when first time condition is false
tin

●​ 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
es

In the case of do-while first block of statements will be executed and then condition
will be verified.
eT
Th
y
m
de
ca
gA

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


tin

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


es

break Statement and continue


eT

●​ break is a keyword.
●​ It can be used within switch or any looping statement.
●​ It is used to terminate the execution of the current looping/switch statement.
●​ break can be used in two ways:
Th

●​ break;
●​ break <label>;

Continue

●​ continue is a keyword.
●​ It can be used within any looping statements.
●​ It is used to continue the execution of the current looping statement with next
iteration.
●​ continue can be used in two ways:
○​ continue;
○​ continue <label>;
✅ Functions

y
m
1.​ No Return Type - void
2.​ Return Type - data -> Primitive or Ref Type

de
3.​ Main method overloading - Interview.

✅ Object Class in Java


ca
●​ Object class is present in java.lang package.
●​ Every class in Java is directly or indirectly derived from the Object class.
gA
●​ Object class methods are available to all Java classes.
Ref image - geeksforgeeks
tin
es
eT
Th

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


private String name;​
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]"

y
hashCode() method

m
In Java, the hashCode() method is a method defined in the Object class that returns an

de
integer hash code value for an object.

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

ca
have the same hash code.
gA
public class Person {​
private String name;​
private int age;​

tin

public Person(String name, int age) {​


this.name = name;​
this.age = age;​
es

}​

@Override​
eT

public int hashCode() {​


int result = 17;​
result = 31 * result + name.hashCode();​
result = 31 * result + age;​
Th

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.

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

y

m
public Person(String name, int age) {​
this.name = name;​
this.age = age;​

de
}​

@Override​

ca
public boolean equals(Object obj) {​
if (obj == this) return true;​
if (!(obj instanceof Person)) return false;​
gA
Person other = (Person) obj;​
return name.equals(other.name) && age == other.age;​
}​
}​
tin


Person p1 = new Person("John", 30);​
Person p2 = new Person("John", 30);​
es

Person p3 = new Person("Jane", 30);​



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

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


Th

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

y
​ public static void main(String[] args)​

m
​ {​
​ ​ Test t = new Test();​
​ ​ System.out.println(t.hashCode());​

de

​ ​ t = null;​





​ ca// calling garbage collector​
System.gc();​
gA
​ ​ System.out.println("end");​
​ }​

​ @Override protected void finalize()​
tin

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

clone()method
eT

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

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

y

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

m
Note that the clone() method only creates a shallow copy of the object, which means that it

de
only copies the references to the object's fields, rather than creating new copies of the
objects themselves. If you want to create a deep copy of an object, you need to create a new
copy of each object contained within the original object.

ca 📙 Arrays in Java
gA
tin

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

●​ Arrays are objects in Java.


●​ Three tasks to remember while you are working with arrays:
○​ o Array Declaration
eT

○​ o Array Construction
○​ o Array Initialization
●​ Arrays can be constructed with multiple dimensions i.e 1-D Array, 2-D Array etc.
Th

●​ length
●​ Use a loop to traverse.
●​ Array size is mandatory while constructing an array object. a. int a[] =new int[3];
//VALID b. int a[] =new int[]; //INVALID
●​ You can't specify the size of an array at the time of declaration. a. int a[] //VALID b. int
a[1] //INVALID.
●​ When you are specifying -ve value as array size then
java.lang.NegativeArraySizeException will be thrown at runtime

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.

y
●​ The size of the array cannot be altered(once initialized).
●​ JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been

m
accessed with an illegal index

de
MyClass myClassArray[]; ​
Object[] ao,

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

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

int[] numbers = new int[5];​


tin


// set the values of the array elements​
numbers[0] = 10;​
es

numbers[1] = 20;​
numbers[2] = 30;​
numbers[3] = 40;​
eT

numbers[4] = 50;​

// print the values of the array elements​
for (int i = 0; i < numbers.length; i++) {​
Th

System.out.println(numbers[i]);​
}​

// prints 10, 20, 30, 40, 50

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

y
m
public class Main {​
public static void main(String[] args) {​
Scanner scanner = new Scanner(System.in);​

de

// create an array to store the numbers​
int[] numbers = new int[100];​

​ ca
int size = 0;​

// read the numbers from the user​


gA
int n;​
do {​
System.out.print("Enter a number: " , -1 to stop entering”);​
n = scanner.nextInt();​
tin

if (n >= 0) {​
numbers[size] = n;​
size++;​
es

}​
} while (n >= 0);​

eT

// find the highest and lowest numbers​


int highest = numbers[0];​
int lowest = numbers[0];​
for (int i = 1; i < size; i++) {​
Th

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

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

y
m
de
ca
gA

public class multiDimensional {​


tin

​ public static void main(String args[])​


​ {​
​ ​ // declaring and initializing 2D array​
es

​ ​ int arr[][]​
​ ​ ​ = { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };​

eT

​ ​ // printing 2D array​
​ ​ for (int i = 0; i < 3; i++) {​
​ ​ ​ for (int j = 0; j < 3; j++)​
​ ​ ​ ​
Th

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
●​ String class has following variable to hold data.
○​ private final char value[];

y
●​ String objects are immutable objects. It means once the object is created then the
content or data of the object can't be modified.

m
●​ When you try to modify the contents of object then new object will be created as a
result.

de
How can String be represented?

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

Why is String Immutable in Java?


es

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

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

String str1 = "Hello";


String str2 = str1.concat(" World");
Th

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

y
m
de
ca
gA
String class provides a wide range of functions to manipulate strings.
tin

Here are some of the most commonly used functions of the String class:

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

Example: "hello".charAt(0) returns 'h'.

concat(String str): Concatenates the specified string to the end of the original string.
eT

Example: "hello".concat(" world") returns "hello world".

contains(CharSequence s): Returns true if the string contains the specified sequence of
characters, otherwise false.
Th

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

y
substring(int beginIndex, int endIndex): Returns a new string that is a substring of the

m
original string, starting from the specified beginIndex and ending at the endIndex (exclusive).
Example: "hello".substring(1, 3) returns "el".

de
toLowerCase(): Returns a new string with all characters converted to lowercase.
Example: "HELLO".toLowerCase() returns "hello".

ca
toUpperCase(): Returns a new string with all characters converted to uppercase.
Example: "hello".toUpperCase() returns "HELLO".
gA
== operator checks if two string references point to the same memory location.
tin

equals method compares the actual content of the strings, checking if they contain the same
sequence of characters.
es

StringBuilder and StringBuffer in Java

●​ StringBuilder and StringBuffer are classes that provide mutable sequences of


eT

characters.
●​ They are designed for efficient string manipulation operations, such as appending,
inserting, or deleting characters from a string.
Th

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

y
Function Description

m
de
append() Appends the specified character(s) or object to the end of the string.

insert()
ca Inserts the specified character(s) or object at the specified index in the string.
gA

Deletes the characters from the string between the specified start and end
tin

delete()
indices.
es

deleteCharAt() Deletes the character at the specified index in the string.


eT
Th

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.

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

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


gA

Ensures that the capacity of the string builder is at least the specified minimum
tin

ensureCapacity()
capacity.
es

trimToSize() Trims the capacity of the string builder to its current length.
eT
Th

Note that StringBuilder and StringBuffer share most of their functions and have very similar
syntax. The main difference between them is that StringBuilder is not thread-safe, while
StringBuffer is thread-safe.

[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++)​
{​

y
ch= str.charAt(i); //extracts each character​
nstr= ch+nstr; //adds each character in front of the existing

m
string​
}​

de
System.out.println("Reversed word: "+ nstr);​
}

Palindrome
ca
gA
Input : str = "abba" ​
Output: Yes​
tin


Input : str = "pramod"​
Output: No
es

public static boolean isPalindrome(String str)​


{​
eT

// Initializing an empty string to store the reverse​


// of the original str​
String rev = "";​
Th


// 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;​
}

Using the String Builder

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

y

m
StringBuilder input1 = new StringBuilder();​

// append a string into StringBuilder input1​

de
input1.append(input);​

// reverse StringBuilder input1​

​ ca
input1.reverse();​

// print reversed String​


gA
System.out.println(input1);​
}
tin

Reverse Words in String

Input: s = “i love programming very much”


es

Output: s = “much very programming love i”


// Java program to reverse a String
import java.util.*;​
eT

class TheTestingAcademy {​

​ // Reverse the letters​
Th

​ // of the word​
​ static void reverse(char str[], int start, int end)​
​ {​
​ ​ // Temporary variable​
​ ​ // to store character​
​ ​ char temp;​

​ ​ while (start <= end) {​
​ ​ ​ // Swapping the first​
​ ​ ​ // and last character​
​ ​ ​ temp = str[start];​
​ ​ ​ str[start] = str[end];​
​ ​ ​ str[end] = temp;​
​ ​ ​ start++;​
​ ​ ​ end--;​
​ ​ }​
​ }​
​ // Function to reverse words​
​ static char[] reverseWords(char[] s)​
​ {​
​ ​ // Reversing individual words as​
​ ​ // explained in the first step​

y
​ ​ int start = 0;​
​ ​ for (int end = 0; end < s.length; end++) {​

m
​ ​ ​ // If we see a space, we​
​ ​ ​ // reverse the previous​
​ ​ ​

de
// word (word between​
​ ​ ​ // the indexes start and end-1​
​ ​ ​ // i.e., s[start..end-1]​
​ ​ ​ if (s[end] == ' ') {​









ca ​

}​
reverse(s, start, end);​
start = end + 1;​
gA
​ ​ }​

​ ​ // Reverse the last word​
​ ​ reverse(s, start, s.length - 1);​
tin


​ ​ // Reverse the entire String​
​ ​ reverse(s, 0, s.length - 1);​
es

​ ​ return s;​
​ }​

eT

​ // Driver Code​
​ public static void main(String[] args)​
​ {​
Th

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

y
1.​ No Return Type
2.​ Return Type

m
int add(int a, int b) {
return a + b;

de
}

int result = add(5, 3); // Calling the 'add' method with arguments 5 and 3

ca
public class Calculator {
public int add(int a, int b) {
return a + b;
gA
}

public static void main(String[] args) {


Calculator calculator = new Calculator();
tin

int result = calculator.add(5, 3); // Calling the 'add' method


System.out.println("Result: " + result);
}
es

static String appDutta(String s){


eT

System.out.println("Return with Param");


return s+"Dutta";
}

static String appDutta2(){


Th

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

y
📗 OOPs ( Java)

m
de
1.​ OOPs vs POP or PPL (Procedural oriented programming)
2.​ Object vs Functional

ca
gA
tin
es
eT
Th

PPL Details
Using the Global Struct to create a Complex Data Type and X global primitive

Struct Customer {​

Int id,​
String name​
String age​

}
Int x = 99;

●​ UpdateCustomer()
●​ FetchCustomer()
●​ Show() can also use the Customer and Primitive x (NO ENCAPSULATION)
●​ Data Security issues (global, local variables)

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

y
How to Use Oops to Build Any Modern-Day Software

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

de
1.​ Identify the objects
a.​ Like Student, Course, Payment.
2.​ Describe those with details

ca
a.​ Data - Student -> name, id, age, address, email, course taken
b.​ Operations -> addStudent, deleteStudent
c.​ Bind them with Encapsulation (Class)
3.​ Establish the relationship with each other
gA
a.​ Student -> payment, Student -> Course, Course -> Payment
4.​ Now implement it via Class and Objects
tin

Abstraction Example
es

●​ It is a design level concept.


●​ Example - PC Computer
a.​ User
eT

b.​ Service Engineer (Hide price)


Th

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.

y
m
de
ca
gA
tin
es

Abstract class
An abstract class, on the other hand, can contain both abstract methods (methods with no
implementation) and concrete methods (methods with an implementation).
eT

abstract class Shape {​


// fields (variables) and concrete methods can be defined in an
Th

abstract class​
protected String color;​

public Shape(String color) {​
this.color = color;​
}​

// concrete method​
public String getColor() {​
return this.color;​
}​

// abstract method​
public abstract double getArea();​
}​

class Rectangle extends Shape {​
private double width;​
private double height;​

public Rectangle(double width, double height, String color) {​
super(color);​
this.width = width;​

y
this.height = height;​
}​

m

// implementation of the abstract method defined in the superclass​

de
@Override​
public double getArea() {​
return this.width * this.height;​
}​
}​
​ ca
class Circle extends Shape {​
gA
private double radius;​

public Circle(double radius, String color) {​
super(color);​
tin

this.radius = radius;​
}​

es

// implementation of the abstract method defined in the superclass​


@Override​
public double getArea() {​
eT

return Math.PI * this.radius * this.radius;​


}​
}
Th

In this example,
●​ the Shape class is an abstract class that defines an abstract method getArea() and a
concrete method getColor().
●​ The Rectangle and Circle classes are concrete subclasses of Shape that must
implement the getArea() method because it is abstract in the superclass.
●​ The Rectangle and Circle classes can also use the getColor() method inherited from
the Shape class.
[Assignment] ​
20+ Examples of Abstract Class and Interface (in Demo)

Interface
An interface is a collection of abstract methods that must be implemented by any class that
implements the interface

Inheritance

y
1.​ Example with Student -> Manual , Automation
2.​ Extra Data members, Operations or Methods

m
de
PolyMorphism
●​ + operator
●​ Remote or on/off button poly behavior

ca
gA
Class and Objects
tin

https://docs.google.com/presentation/d/1pilgqDxrvs7KsFEOHyLBzF75Da3ZXYPvnPCHfG1
Gk4s/edit?usp=sharing
es
eT
Th
Inheritance

y
m
de
ca
the different types of inheritance include:
gA
1. Single Inheritance: A class inherits from a single base class.
tin

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

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


es

a hierarchy of inheritance.
eT

4. Hierarchical Inheritance: Multiple derived classes inherit from a


single base class.
Th

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

Q1) What is the purpose develop computer programs. It defines the rules, principles, and guidelines to

of any programming be followed while designing and implementing software solutions. It also

model? helps programmers to organize their code and create efficient, reliable, and

maintainable applications.

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

programming models procedure-oriented programming (POP), object-oriented programming

y
available to develop (OOP), functional programming (FP), event-driven programming (EDP), and

m
applications? aspect-oriented programming (AOP).

de
The main components of the Procedure Oriented Programming model

ca
Q3) What are the main

components of the

Procedure Oriented
include procedures or functions, which are a set of instructions that perform

a specific task, and data structures, which are used to organize and store

data. POP follows a top-down approach, which means the program flow
gA
Programming model? starts from the main function and then calls other functions or procedures

as required.
tin

Q4) What are the The limitations of the Procedure Oriented Programming model include a lack
es

limitations of the of data security, difficulty in maintaining and modifying code, and low

Procedure Oriented reusability of code. POP is also not suitable for large-scale applications as

Programming model? the program logic becomes complex and difficult to manage.
eT

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


Th

Q5) What is OOPs emphasizes the use of objects, which are instances of classes, to represent

concept? real-world entities and their behavior. OOPs focuses on encapsulation,

inheritance, 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

Q6) What are the main used to define the attributes and behavior of objects, and objects are

components of instances of classes that represent real-world entities. Encapsulation

Object-Oriented provides data security by hiding the implementation details of classes, while

Programming model? inheritance allows the creation of new classes by extending existing classes.

Polymorphism enables the use of the same code for different types of

objects.

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

de
OOPs? object-oriented programming in the 1960s.

ca
Q8) What are the major
The major principles of Object-Oriented Programming include inheritance,

encapsulation, abstraction, and polymorphism. Inheritance allows the

creation of new classes by extending existing classes, encapsulation


gA
principles of
provides data security by hiding the implementation details of classes,
Object-Oriented
abstraction allows the creation of complex systems by hiding unnecessary
Programming?
tin

details, and polymorphism enables the use of the same code for different

types of objects.
es

Abstraction is a programming concept that involves hiding unnecessary


eT

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

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

OOPs, abstraction is achieved through the use of abstract classes and


Th

interfaces.

Encapsulation is a programming concept that involves hiding the

implementation details of classes and exposing only their interfaces or


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

parts of the program.


Inheritance is a programming concept that allows the creation of new
Q11) What is
classes by extending existing classes. It enables code reuse and promotes
inheritance?
the creation of modular and scalable applications

Assignment - What happens if we do it

Class Book{​

y
Int id; ​

m
String name;​
String author;​

de
}​

Book s1 = new Book();

ca
1.​ JVM allocates 8 bytes for each reference variable.
2.​ All variables are assigned a memory.
gA
3.​ Referq

Abstract classes and methods


tin

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

Interfaces
eT

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


2.​ Public static final variables
Th

3.​ Public abstract methods.


y
m
de
ca ​
gA
Important Concepts
●​ super()
●​ //1. Use of super with Variables
tin

●​ //2. Use of super with Methods


●​ //3. Use of super with constructors
●​
●​ // Constructor Chaining
es

●​
●​ // Encapsulation
●​ // Polymorphism
eT

●​ // Abstraction
●​ // Access Modifiers
●​ // Static Keyword
Th

●​ //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​
{​
System.out.println("I am block");​

y
}​

m
// Default constructor​
Book(){​

de
System.out.println("Default Con");​
}​

// Parameters constructor​

ca
public Book(int id, String name, String author) {​
this.id = id;​
this.name = name;​
gA
this.author = author;​
}​

// Method​
tin

void show(){​
System.out.println("Data");​
}​
es


@Override​
public String toString() {​
eT

return "Book{" +​
"id=" + id +​
", name='" + name + '\'' +​
Th

", 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;​

y

m
public class StaticDemo {​
int a = 10;​
static int b= 20;​

de
void m1(){​
System.out.println(a);​
System.out.println(b);​
}​
ca
static void m2(){​
//System.out.println(a);​
gA
System.out.println(b);​
}​
}​

tin

Static members can be accessed with Class Name.


es

Instance members can’t be accessed with class Name.

package atb.classdemo.staticdemo;​
eT


public class Main {​
public static void main(String[] args) {​
Th

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

y
public getter and setter methods to access and modify the data.

m
public class Student {​

de
// data fields are private​
private String name;​
private int age;​

ca
private String address;​
// public getter and setter methods for each field​
public String getName() {​
gA
return this.name;​
}​
public void setName(String name) {​
this.name = name;​
tin

}​
public int getAge() {​
return this.age;​
es

}​
public void setAge(int age) {​
eT

this.age = age;​
}​
public String getAddress() {​
Th

return this.address;​
}​

public void setAddress(String address) {​
this.address = address;​
}​
}
Th
eT
es
tin
gA
Access Modifier

ca
de
m
y
Access modifiers in Java:

y
m
de
ca
gA
tin
es

Polymorphism
eT
Th
Th
eT
es
tin
gA
ca
de
m
y
Th
eT
es
tin
gA
ca
de
m
y
y
m
de
ca Abstraction
gA
Abstract classes and methods
tin

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

●​ Abstract class cannot be final.


●​ An abstract class cannot be instantiated i.e. one cannot create an object of an
abstract class.
eT

●​ Although it is not required, an abstract class may have the declaration of one or more
abstract methods.
●​ Since the body of an abstract method cannot be implemented in an abstract class.
Th

●​ 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.
6.​ Interface can contain the following members:
a.​ public final static variables
b.​ public abstract methods
c.​ public static inner classes

y
7.​ Variables declared in the interface are by default public final and static.
8.​ Methods declared in the interface are by default public and abstract.

m
de
Default Methods in interfaces
●​ Default methods are methods that can have a body.

ca
●​ They provide additional functionality to a given type without breaking down the
implementing classes.
●​ If a new method was introduced in an interface then all the implementing classes
gA
used to break.

default return type name () {}


tin

-​ Solve the Diamond problem by Interface.super.methodName

Static methods in interfaces


es

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

Problem to discuss to check Interface


Th

interface I1{}​
interface I2{}​
class A{}​
class B{}​
class Test1 extends A{ } //0K​
class Test2 extends A,B{ } //Not OK​
class Test3 implements I1{ }//0K​
class Test4 implements I1,I2{ }//0K​
class Test5 extends A implements I1,I2{ }//OK​
class Test6 implements I1 extends A{ } / /Not OK

interface I3 extends A{}​
interface I4 implements A{}​
interface I5 extends A,B{}​
interface I6 extends I1,I2{ }

y
m
de
ca
✅ Problem Statement
gA
Book class which has an abstract method getDetails(),name, author, price.
PrintMyBook class that inherits from the Book class.

abstract
tin

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

// Output
es

"Harry Potter, J.k. Rowling, 100"


eT
Th

Static Keyword
The static keyword in Java is mainly used for memory management. It used to share the
same variable or method of a given class.

The static keyword is a non-access modifier in Java that is applicable for the following:

●​ Blocks
●​ Variables
●​ Methods
●​ Classes
Static blocks, data members, methods, and classes in Java with an example.

1. Class:
A class is a blueprint for creating objects. It defines the properties (data members) and
behaviors (methods) that the objects created from the class will have.

2. Data Members:
Data members (also known as instance variables) are variables that hold the data/state of
an object. These can be instance variables or static variables.

3. Methods:
Methods define the behaviors or functions that an object can perform. These can be

y
instance methods or static methods.

m
4. Static Block:
A static block is a block of code that gets executed when the class is loaded into memory. It

de
is used to initialize static data members.

ca
Nested Class
Class within Class is called Nested class
gA
class OuterClass
{
...
class NestedClass
tin

{
...
}
es

}
eT
Th
y
m
de

ca Static Nested Class


gA
●​ Only a static member of the outer class can be accessed directly.
●​ Inside static nested class, static members can be declared.
tin

class OO{
static int o =100;
int a = 900;
es

static class SNCI{


void show(){
System.out.println(o);
eT

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


// System.out.println(a);
}
}
Th

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

y
4.​ Static declaration is not allowed in the inner class
5.​ Static Inner class, Instance Inner class, Local Inner class, Anonymous inner class

m
There are 4 ways you can create a Class

de
1.​ Inner Class
2.​ Method Level Inner Class
3.​ Nested Class

ca
4.​ Anonymous Class

public class Car {​


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

tin

// inner class​
public class Engine {​
// inner class fields​
es

private int horsepower;​


private String fuelType;​

eT

// inner class constructor​


public Engine(int horsepower, String fuelType) {​
this.horsepower = horsepower;​
Th

this.fuelType = fuelType;​
}​

// inner class method​
public void start() {​
System.out.println("Engine starting...");​
}​
}​

// outer class constructor​
public Car(String make, String model) {​
this.make = make;​
this.model = model;​
}​

// outer class method​
public void drive() {​
System.out.println("Driving the car...");​
}​
}

//
Car myCar = new Car("Toyota", "Camry");
Car.Engine engine = myCar.new Engine(200, "Gasoline");

y
engine.start();

m
de
ca
Upcasting and Downcasting in Class

You can assign a subclass object to the super type reference variable directly. This process
gA
is called UPCASTING.

class Parent{}​
tin

class Child extends Parent{}

Parent parent = new Parent(); // p1


es

Child child = new Child();


eT

parent=child;
// Valid -> Upcasting
Th

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


{

y
// data members and methods
public void test_method()

m
{
........

de
........
}
}

ca
●​ An anonymous class has access to the members of its enclosing class.
●​ An anonymous class cannot access local variables in its enclosing scope that are not
gA
declared as final or effectively final.
●​ constructors can not be declared in an anonymous class.
●​
tin
es
eT
Th

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

y
Student student = new Student() {
@Override

m
public void setId() {
System.out.println(id);
}
};

de
student.setId();
}
}

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

class MyStudent implements Student{


tin

@Override
public void setId() {
System.out.println(id);
}
}
es
eT
Th

Wrapper Classes
●​ A Wrapper class is a class whose object wraps or contains primitive data types.
●​ They convert primitive data types into objects.
●​ Data structures in the Collection framework, such as ArrayList and Vector, store
only objects (reference types) and not primitive types.
●​ An object is needed to support synchronization in multithreading.
y
m
Primitive -> Wrapper , Primitive -> String ,Wrapper -> Primitive

de
ca
1.​ Primitive to String
1.​ Using valueOf()
2.​ toString() of wrapper
2.​ String to Primitive
gA
a.​ A) using parseXO;
3.​ Primitive to Wrapper Object
a.​ A) Using Constructor of Wrapper class
tin

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
es

a.​ A) Using constructor of Wrapper classes


b.​ B) Using valueOf method of Wrapper classes
6.​ Wrapper Object to String
eT

a.​ A) Using toString( method


Th

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;


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

y
Integer X = new Integer(10);
Integer Y = 10;

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

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

ca
📕 Exceptions
gA

An exception is an event that occurs during the execution of a program that disrupts the
tin

normal flow of instructions.

P.S. - If no exceptions are handled, control is passed to the JVM, which terminates the
program.
es

Exception Hierarchy
eT
Th
package thetestingacademy.exceptions; // 0

public class Ex01 {


// 3 PROBLEMs in this problem
public static void main(String[] args) {
String sh = args[0];

y
int x = Integer.parseInt(sh);
int a = 10/x;

m
System.out.println(x);
System.out.println(a);
}

de
}

ca
Solve the three problems in the above program.
1.​ Array.
2.​ Number format
gA
3.​ Arithmetic.
tin

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

Try and Catch


Attempt to catch the block.
eT
Th
y
m
de
ca
gA
tin
es

When Catch will be executed


Only when an exception in public class Ex02 is raised
eT

public static void main(String[] args) {


try {
Th

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 ?

y
m
de
ca
gA
tin
es

Multiple Catch
You can catch multiple exceptions; their execution depends on the execution problem.
eT

package thetestingacademy.exceptions;​

Th

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)

y
P.S. - Please do not write anything between Try and Catch.

m
Please find the problem in this Code.

de
package thetestingacademy.exceptions;​

public class Ex04 {​

ca
public static void main(String[] args) {​
try {​
int a = Integer.parseInt(args[0]);​
gA
}​
catch (NumberFormatException exception) {​
exception.printStackTrace();​
}​
tin

try {​
int b = 10 / a;​
}​
es

catch (ArithmeticException exception) {​


exception.printStackTrace();​
}​
eT

try {​
String ip = args[0];​
}​
catch (ArrayIndexOutOfBoundsException exception) {​
Th

exception.printStackTrace();​
}​
}​
}

Or Catch Concept
After Java 7, We can write them in OR condition with pipe char |
try {​
String ip = args[0];​
int a = Integer.parseInt(args[0]);​
int b = 10 / a;​
} catch (NumberFormatException | ArithmeticException |
ArrayIndexOutOfBoundsException exception) {​
exception.printStackTrace();​
} catch (Exception e) {​
e.printStackTrace();​
}

y
Finally Block

m
The finally block is a block of code that follows a try-catch block and is always executed,

de
regardless of whether an exception is thrown or caught. The finally block is typically used to
release resources or perform other cleanup tasks.

try {​
ca
// code that might throw an exception​
} catch (ExceptionType e) {​
gA
// code to handle the exception​
} finally {​
// code to be executed after the try-catch block​
}
tin

public class Main {​


es

public static void main(String[] args) {​


FileInputStream file = null;​
try {​
eT

file = new FileInputStream("file.txt");​


// read from the file​
} catch (FileNotFoundException e) {​
Th

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) {​

y
FileInputStream file = null;​

m
try {​
file = new FileInputStream("file.txt");​
// read from the file​

de
} catch (FileNotFoundException e) {​
System.out.println("File not found!");​
} finally {​

ca
if (file != null) {​
try {​
file.close();​
gA
} catch (IOException e) {​
// handle the exception​
}​
}​
tin

}​
}​
es

Only in one case, If exit(0) is found, finally will not execute.


eT

Problem 1

public class Ex06 {


public static void main(String[] args) {
Th

ProblemF problemF = new ProblemF();


int x = problemF.show();
System.out.println(x);
}
}

class ProblemF{
int a = 10;
int show(){
try{
System.out.println("In class -> "+ a);
return a;
}catch (Exception e){
System.out.println("Catch");
a = 20;
return a;
}finally {
System.out.println("I am Final");
}
}}

Problem #2

y
package thetestingacademy.exceptions;​

m

public class Ex06 {​

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

}​

}​
ca
gA
class ProblemF{​
int a = 10;​
int show(){​
try{​
tin

// a = 10/0;​
System.out.println("In class -> "+ a);​
return a;​
es

}catch (Exception e){​


System.out.println("Catch");​
a = 20;​
eT

return a;​
}finally {​
System.out.println("I am Final");​
Th

//int[] a1 = new int[-1]; fix it​


}​
}​
}​
Problem #03

y
package thetestingacademy.exceptions;​

m
public class Ex08 {​
public static void main(String[] args) {​

de
try {​
int a = 10 / 10;​
} catch (Exception a) {​
System.out.println("I am Catch 01");​

}​
ca
} finally {​
System.out.println("Finally 01");​
gA
try {​
int a = 10 / 0;​
} catch (Exception a) {​
System.out.println("I am Catch 02");​
tin

} finally {​
System.out.println("Finally 02");​
}​
es

try {​
int a = 10 / 0;​
} catch (Exception a) {​
eT

System.out.println("I am Catch 03");​


System.exit(-1);​
} finally {​
Th

System.out.println("Finally 03");​
}​
try {​
int a = 10 / 20;​
} catch (Exception a) {​
System.out.println("I am Catch 04");​
} finally {​
System.out.println("Finally 04");​
}​
}​
}
Exception Passing Methods

Navigating the Exception Flows from One Method to OTHER

y
m
package thetestingacademy.exceptions;​

de
public class Exception02 {​
public static void main(String[] args) {​
extracted2();​
System.out.println("MAIN Execute");​


}​
ca
private static void extracted2() {​
gA
extracted1();​
System.out.println("extracted2 Execute");​
}​

tin

private static void extracted1() {​


extracted();​
System.out.println("extracted1 Execute");​
es

}​

private static void extracted() {​
eT

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


Integer[] i = new Integer[2];​
System.out.println(i[3]);​
} catch (NullPointerException e) {​
System.out.println("Null");​
e.printStackTrace();​
}catch (ArrayIndexOutOfBoundsException e) {​
System.out.println("Array Index Out");​
e.printStackTrace();​
}catch (Exception e) {​
e.printStackTrace();​
}​
}​
}

Throw and Throws

●​ Till Now JVM created an Exception for us.


●​ Now We will do it

y
Throw exObject.

m
Throws Keyword at Method LEVEL

de
ca
gA
tin
es
eT

Custom Exception

"Exception" class or any of its subclasses, such as "RuntimeException". Custom exceptions


Th

allow you to create specific types of exceptions to represent error conditions that are specific
to your application.

For example, you might create a custom exception to represent an error condition such as
"insufficient funds" in a bank account application. This allows you to handle this error
condition in a specific way, rather than using a more general exception type such as
"Exception" or "RuntimeException".
y
m
de
ca
gA
tin

Important Points
es

throw new Exception();​


throw new Error();​
eT

throw new Throwable();​



throw new Object(); //Not Ok​
Th


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

y
3) StackOverflowError

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

de
4) OutOfMemoryError

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

ca
int arr[]=new int[54453453];

5) UnsupportedClassVersionError
gA
(If JVM version is lower then compiler version.)

6) ExceptionInInitializerError
tin

(if exception occurs at static variable or static block while loading the class.)
static int p;
static {p=Integer.parseInt("SRI");}
}
es
eT

1) ClassCastException
Th

(If you try to convert superclass object into subclass object whitout having the ref. of
subclass.)

Object ob1 = new Object();


String st1=(String)ob1;

2) IllegalStateException

Thread t= new Thread();


t.start();
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;

y
public class Ex11 {

m
public static void main(String[] args) {

de
Hello h = new Hello();
h.process();
System.out.println("Pramod");

}
} ca
gA
class Hello {
public int process() {
tin

throw new NullPointerException();


}
es

}
eT
Th
Collection Framework

Focus on Main Business Logic rather than Low Level Logics

Problem with Arrays

y
●​ Since we have to give size, memory is wasted.

m
●​ Insertion and deletion are heavy.
●​ No built-in support for sorting, searching.

de
We prefer below classes and Interfaces in place of Arrays.

Legacy APIs are provided

ca
Legacy Classes
●​ Vector
gA
●​ Stack
●​ Properties
●​ Hash table
●​ Dictionary
tin

Legacy Interface
●​ Enumeration (cursor)
es

Enumeration
eT

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
Th
y
m
de
ca
Collection vs Collections
●​ Collection Framework” has been defined in JDK 1.2 which holds all the collection
classes and interfaces in it.
gA
●​ Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two
main “root” interfaces of Java collection classes.
tin
es
eT
Th

What is a Framework?
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.

y
Way to Initialize

m
●​ List<String> fruites = List.of("orange","apple");
●​ ArrayList - Underline Array - Get element is easy, inserting, Delete is Costly.
●​ LinkedList - LinkedList

de
●​ Vector - Array

ca
Most of the time, programmers prefer ArrayList over Vector because ArrayList can be
synchronized explicitly using Collections.synchronizedList.
gA
List Functions
Use the javap java.util.List
tin

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

5.​ public abstract java.lang.Object[] toArray();


6.​ public abstract <T> T[] toArray(T[]);
7.​ public abstract boolean add(E);
eT

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

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

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

y
●​ It is fast to access the elements, but slow to insert and delete the elements.

m
de
Array vs Vector

Vector

ca
●​ Vector allows duplicates, and it is implemented as a resizable array.
●​ Vector is a legacy class and elements will be stored internally using indexing
gA
notation.
●​ Vector methods are synchronized, so vector objects can’t be accessed by
multiple threads at a time.(Slow)
tin
es
eT
Th
y
m
de
ca
gA
tin
es
eT
Th

Array vs ArrayList
y
m
de
ca
gA
Array vs LinkedList
tin
es
eT
Th
y
m
de
●​
LinkedList

ca
●​ ​LinkedList allows duplicates and internally implements a doubly-linked list data
structure.
●​ LinkedList elements will be stored internally using node representation.
gA
●​ It is fast to insert or delete the elements, but slow for accessing the elements.
tin
es
eT
Th

Stack
●​ Stack is a legacy subclass of vector and its methods are synchronized, so stack
objects can’t be accessed by multiple threads at a time.
●​ Stack has important operations like peek(), pop(), push(), search() and other
operations are same as Vector. It is a and not in use.
y
m
de
Task
ca ArrayList LinkedList Vector Stack
gA
Order User added User added User added

Duplicate Vaue Yes Yes Yes


tin

Null Value Yes Yes Yes

Random Access Yes No Yes

Sequential Access Yes Yes Yes


es

Iterator (used?) Yes Yes Yes


eT

List Iterator Yes Yes Yes

Enumeration No No Yes
Th

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
●​ used to iterate or traverse or retrieve a Collection or Stream object’s elements one by

y
one and called a Java Cursor is an Iterator.

m
three cursors in Java.

de
1.​ Iterator - For all
2.​ Enumeration - V
3.​ ListIterator - List

ca
Methods in Iterator
gA
tin
es
eT

Problem with Iterator


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

ListIterator
Iterator that is used to traverse all types of lists including ArrayList, Vector, LinkedList, Stack,
etc. It is available since Java 1.2. It extends the iterator interface.
●​ bi-directional traversal.
●​ four CRUD operations(Create, Read, Update, Delete)
●​ Cursor concept.
Methods in ListIterator

y
m
de
Iterator vs ListIterator

ca
gA
tin
es
eT
Th

Spliterator
●​ Spliterator == Splittable Iterator
●​ it can split some source, and it can iterate it too. (2 balanced)
●​ trySplit is for. Splitting is needed for parallel processing.
y
m
de
ca
package thetestingacademy.collections.list;​
gA

import java.util.ArrayList;​
import java.util.Spliterator;​
tin

import java.util.stream.Stream;​

public class SpliteratorDemo {​

es

public static void main(String[] args) {​



eT


ArrayList<Integer> al = new ArrayList<>();​
// Add values to the array list.​
Th

al.add(1);​
al.add(2);​
al.add(-3);​
al.add(-4);​
al.add(5);​
// getting Spliterator object on al​
Spliterator<Integer> splitr1 = al.spliterator();​

// estimateSize method​
System.out.println("estimate size : " +
splitr1.estimateSize());​
// getExactSizeIfKnown method​
System.out.println("exact size : " +
splitr1.getExactSizeIfKnown());​


// Split​

Spliterator<Integer> splitr1_split = splitr1.trySplit();​
// If splitr1 could be split, use splitr2 first.​
if(splitr1_split != null) {​
System.out.println("Output from splitr2: ");​
splitr1_split.forEachRemaining((n) ->

y
System.out.println(n));​

m
}​

// Now, use the splitr​

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


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

tin


}​
}
es
eT

ConcurrentModificationException
●​ Can’t add to the List while iterating.
Th




y
Set

m
●​ Interface, java.util.Set
●​ Unique Only
●​ If o1.equals(o2) Only one will be in the List

de
●​ Set interface has the following concrete subclasses:
○​ o HashSet
○​ o LinkedHashSet

ca○​ o TreeSet .
gA
tin
es
eT

​ ​

Check Implementation of Hash Set in Java doc


Th

HashSet
●​ It is fast for searching and retrieving elements.
●​ It does not maintain any order for stored elements.> A, B, C -> B,C, A, ABC, BAC
y

m
LinkedHashSet

de
●​ LinkedHashSet is a subclass of HashSet.
●​ It stores the data in the order as added by the user. A,B,C -> ABC​

TreeSet

ca
●​ It stores the elements in a sorted order. - 23,45,1 -> A,Z,B -> ABz, s1, s2, s3 -> It
won’t able -> Collections.sort
●​ compareTo() method is used to identify the object uniquely and to manage the order
gA
of elements in TreeSet.
●​ The object you are adding in the TreeSet must be the subtype of Comparable
interface.
●​ If object is not the subtype of Comparable, then it will throw an exception at
tin

runtime
java.lang.ClassCastException
●​ TreeSet allows storing elements of similar type only.
es

●​ Null value cannot be stored in TreeSet.


eT
Th

NavigableSet
●​ NavigableSet is an interface added in Java 6.
●​ It is a subtype of SortedSet.
●​ Its functionality is almost similar to TreeSet except it provides some extra methods for
easy navigation.
●​ Elements from NavigableSet can be accessed in both forward and reverse order.

y
m
de
ca
gA
tin
es
eT
Th
Comparable vs Comparator

Comparable object is capable of comparing itself with another object. The class itself must
implements the java.lang.Comparable interface to compare its instances.

Comparator is external to the element type we are comparing. It’s a separate class

CompareTo(??)
Compare

y
m
de
ca
gA
tin

Queue
●​ Added interface in Java 5.
es

●​ PriorityQueue is one of the commonly used subclasses of Queue


interface.
●​ PriorityQueue doesn’t allow null values.
eT

●​ You can add only comparable objects to PriorityQueue


Th
y
m
de
Task Hashset LinkedHashSet TreeSet

Order No Order User added Default sort

Null Value
ca
Duplicate Vaue No

Yes
No

Yes
No

No
gA
Synchronized No No No
tin

Iterator (used?) Yes Yes Yes

List Iterator No No No
es

Enumeration No No Yes

Index Representation No No No
eT

Node Representation No Yes No

NavigateableSet API used No No No


Th

Serializable Yes Yes Yes

Cloneable Yes Yes Yes


Map

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

y
SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap

m
●​ Map hm = new HashMap();
●​ Map interface has following concrete sub classes:
○​ o HashMap

de
○​ o LinkedHashMap
○​ o TreeMap
○​ o Hashtable

ca
gA
tin
es
eT
Th
y
m
de
HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation
of the Map interface of Java. It stores the data in (Key, Value) pairs.

ca
No Duplicate Key on HashMap
gA
LinkedHashMap is just like HashMap with an additional feature of maintaining an order of
elements inserted into it.
tin

The TreeMap in Java is used to implement the Map interface and NavigableMap along with
the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a
Comparator provided at map creation time, depending on which constructor is used.
es
eT
Th
Th
eT
es
tin
gA
ca
de
m
y
y
m
de
ca
gA
HashTable

●​ It is similar to HashMap, but is synchronized.


tin

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

●​ 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
eT

Sort HashMap by Keys


Th

●​ By using TreeMap
●​ By using LinkedHashMap
●​ Sort HashMap by Values
●​ Sort HashMap by Values using Comparator Interface
y
m
de
ca
gA
tin

●​ Count Occurance of Character in the given String


●​ Count Occurance of Word in the given String
es
eT
Th
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

y
What is the difference between Set and Map?

m
●​ Set contains values only whereas Map contains key and values both.
●​ Set contains unique values whereas Map can contain unique Keys with duplicate
values.

de
●​ Set holds a single number of null value whereas Map can include a single null key
with n number of null values.

ca
What is the difference between HashMap and Hashtable?
gA
tin
es
eT

What is the difference between Collection and Collections?


Th

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

y
m
de
.
ca
gA
How to synchronize List, Set and Map elements?

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


2.​ public static Set synchronizedSet(Set s){}
tin

3.​ public static SortedSet synchronizedSortedSet(SortedSet s){}


4.​ public static Map synchronizedMap(Map m){}
5.​ public static SortedMap synchronizedSortedMap(SortedMap m){}
es

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


eT

The default size of load factor is 0.75. The default capacity is computed as initial capacity *
load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
Th

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?

y
Generics

m
●​ Introduction to Generics, Generics Class
●​ Implementing Generics for the Custom List
●​ Examples

de
"Generics allow the reusability of code, where one single method can be used for different
data-types of variables or objects."

ca
idea is to allow different types like Integer, String, … etc and user-defined types to be a
parameter to methods, classes, and interfaces.
gA
tin
es
eT
Th

MaxtTheerGeneric Demo
Th
eT
es
tin
gA
ca
de
m
y
Th
eT
es
tin
gA
ca
de
m
y

Multithreading

1.​ Multi Tasking


a.​ Multi Thread
b.​ Multi Processing

y
Multitasking

m
●​ CPU executes multiple jobs by switching among them.
●​ typically using a small-time quantum, and these switches occur so frequently that the
users can interact with each program while it is running.

de
ca
gA
tin
es

Multi Processing:
●​ Process is a program.
eT

●​ Each process is treated as a separate execution unit and is assigned to a different


CPU.
○​ Running MS Word C#
Th

○​ Running PPT
○​ Running Zoom
○​ Running WhatsApp
●​ System Level concept. CPU level, Raspberry Pi 1 Single CPU
●​ They will have different memories (written in different languages).
●​ They can share data, but it is a very complex process.
●​ Context switch or control is difficult. (P1 will ask P2, P3 for permission)
Multi Threading:
●​ Thread is part of Program
●​ Thread is a sub process.
●​ E.g. Zoom,
○​ SP1, SP2, SP3 three sub processes each are Thread
○​ SP1 - Audio transfer
○​ SP2 - Video Recordings
○​ SP3 - Chat

y
●​ Application level

m
●​ They can share the memories
●​ They can do it easily in threads.
●​ Switching to control in Threads is easy. ( T1 -> T2)

de
-​
-​ ca
Bank Application allows multiple users to login, bank balance, withdraw amount.
gA
tin
es
eT
Th

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

y
}​
}

m
de
ca
gA
tin
es
eT
Th

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

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

m
1.​ Extend Thread
2.​ Runnable

de
package thetestingacademy.multithreading;​

ca
public class Task03 {​
public static void main(String[] args) {​
gA

Worker worker = new Worker();​
worker.start();​
// Where is the Start ?​
tin

Worker worker2 = new Worker();​


worker2.start();​

es

}​
}​

eT

class Worker extends Thread{​



@Override​
public void run() {​
Th

for (int i = 0; i < 5; i++) {​


try {​
System.out.println(i + " --> ");​
Thread.sleep(2000);​
} catch (InterruptedException e) {​
e.printStackTrace();​
}​
}​
}​
}
y
m
de
ca
gA
tin
es
eT

Why don’t we call run() method directly, why call start() method?

●​ We can call run() method if we want but then it would behave just like a normal
Th

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

y
●​ public Thread (Runnable, String);​

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

de
●​ public Thread(ThreadGroup, Runnable);
Creates a new Thread object by specifying the threadgroup Runnable object.
●​

ca
●​ public Thread(ThreadGroup, Runnable, String);​
gA
Creates a new Thread object by specifying the ThreadGroup, Runnable object and
thread name.
tin
es
eT
Th

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.

y
m
de
ca
Constants from Thread Class
●​ static final int MIN_PRIORITY Constant represents minimum priority of a thread
●​ static final int NORM_PRIORITY Constant represents normal priority of a thread
gA
●​ static final int MAX_PRIORITY Constant represents maximum priority of a thread

Methods from Thread Class


tin
es
eT
Th
y
m
de
Concurrency vs Parallelism

Concurrency refers to the ability of a system to handle multiple tasks or threads at the same

ca
time, allowing them to be executed independently and asynchronously.

Concurrency enables a system to perform multiple tasks simultaneously, but it does not
gA
necessarily mean that the tasks are executed simultaneously.

For example, a web server can handle multiple client requests concurrently, but each
request is handled by a single thread and the server may not be able to process all the
tin

requests at the same time.

Parallelism refers to the ability of a system to execute multiple tasks or threads


es

simultaneously, using multiple cores or processors.

Parallelism enables a system to perform multiple tasks at the same time, rather than one at
eT

a time.

For example, a parallel program can use multiple cores or processors to perform a
large computation in less time.
Th

In summary, concurrency enables a program to handle multiple tasks at the same time,
but it does not necessarily mean that the tasks are executed simultaneously.

Parallelism enables a program to execute multiple tasks simultaneously, using multiple cores
or processors.
y
m
de
ca
gA

Synchronous vs Asynchronous
tin

Synchronous operations block the execution of the program or system until the operation
is completed.
es

This means that the program or system will not execute any other code or perform any other
tasks until the current task is completed.
eT

This can lead to a situation where the program or system is "stuck" waiting for an operation
to complete, and this can make the program or system unresponsive or slow.
Th
y
m
de
Asynchronous operations, on the other hand, do not block the execution of the program or
system.

ca
The program or system can continue to execute other code or perform other tasks while an
asynchronous operation is in progress.
gA
This can make the program or system more responsive and efficient, because it can perform
multiple tasks at the same time.
tin

In summary, synchronous operations block the execution of a program or system until the
operation is completed, while asynchronous operations do not block the execution and allow
the program or system to continue running while the operation is in progress.
es
eT
Th
Thread Priority

y
m
de
ca
gA
tin
es
eT
Th

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

y
4.​ Thread scheduler selects the t1

m
●​ New - Instance of thread created which is not yet started by invoking start() it will be.

de
●​ Runnable - After Invocation of start() and before it is selected to be run by the
scheduler.
●​ Running - After the thread scheduler has selected it.

ca
●​ Non-runnable - Thread alive, not eligible to run.
●​ Terminated - run() method has exited.
gA
tin
es
eT
Th
y
m
de
ca
Synchronization
●​ Lock on an Object.
gA
tin
es
eT

-​ Withdraw example for the Synchronization


Th

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(){ ... }

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{

y
ArrayList al = new ArrayList();

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

de
}

ca
Important points for the Synchronization
gA
●​ Case 1
●​ Case 2
●​ Case 3
●​ Case 4
●​ Case 5
tin

●​ Case 6
es
eT

Deadlocks
Th

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​
Thread t1 = new Thread() {​
public void run() {​

y
synchronized (resource1) {​
System.out.println("Thread 1: locked resource 1");​

m

try {​

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

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


// t2 tries to lock resource2 then resource1​
Thread t2 = new Thread() {​
es

public void run() {​


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


try {​
Thread.sleep(100);​
Th

} 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

y
●​ immediately and the current thread will be moved to WAIT state.

m
●​ Following are the wait() methods defined in Object class:
○​ o public final void wait()
○​ o public final native void wait(long ms)

de
○​ o public final void wait(long ms, int ns)
●​ If you call wait() method on unlocked object then
java.lang.IllegalMonitorStateException

ca
●​ will be thrown at runtime

package thetestingacademy.multithreading.synchronization.WaitDemo;​
gA

public class WaitDemo {​

public static void main(String[] args) {​
tin


WaitForMe waitForMe = new WaitForMe();​

es

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


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

eT

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

}​


class WaitForMe {​

// synchronized void show(){​
synchronized void show() {​
Thread thread = Thread.currentThread();​
for (int i = 0; i < 5; i++) {​
System.out.println(" Name -> " + thread.getName() + " -> " +
i);​
try {​
this.wait(1000);​
} catch (Exception e) {​
e.printStackTrace();​
}​
}​
}​

// Blocking a Block or Third Party Object​
// void show() {​
// Thread th = Thread.currentThread();​
// ArrayList al = new ArrayList();​
// synchronized (al) {​

y
// for (int i = 1; i <= 5; i++) {​
// System.out.println(th.getName() + " - show -" + i);​

m
// try {​
////this.wait(1000);​

de
// al.wait(1000);​
// } catch (Exception ex) {​
// System.out.println(ex);​
// }​
//
//
// }​
ca}​
}​
gA
}​



tin

class CustomThread extends Thread {​


WaitForMe wait;​

es

public CustomThread(WaitForMe wait, String name) {​


super(name);​
this.wait = wait;​
eT

}​

@Override​
Th

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

y
READY TO RUN state.
○​ If resources are not available then the threads go to BLOCKED state.

m
de
Code sample at ATBNotes.zip

Join()
ca
gA
●​ This method will be used to join one thread at the end of another thread.
●​ In Main thread -> t1.join()
○​ Main thread will be joined at the end of t1.
●​ In t1 thread -> t2.join()
tin

○​ t1 thread will be joined at the end of t2.


es

Thread Pool
eT

●​ A thread pool in Java is a collection of worker threads that are used to execute
multiple tasks concurrently.
●​ The main advantage of using a thread pool is that it allows the program to reuse
threads, which can improve performance and reduce the overhead of creating and
Th

destroying threads.
●​ In a thread pool, a fixed number of worker threads are created and are managed by a
thread pool executor. When a task is submitted to the thread pool, it is placed in a
task queue and is executed by an available worker thread. Once a task is completed,
the worker thread is returned to the thread pool and is available for executing another
task.
●​ Java provides the Executor framework, which simplifies the task of creating and
managing thread pools. The Executor interface has a single execute() method, which
is used to submit tasks to the thread pool

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.

y
Instance variables are more prone to the Thread Safty, Local variables are always safe.

m
class MyThreadLocal {​
private static ThreadLocal<Integer> myThreadLocal = new

de
ThreadLocal<>();​
public static void set(Integer value) {​
myThreadLocal.set(value);​
}​
ca
public static Integer get() {​
return myThreadLocal.get();​
gA
}​
}
tin

MyThreadLocal.set(10);​
System.out.println(MyThreadLocal.get()); // 10
es

It's important to note that each thread will have its own copy of the thread-local variable, so
the value of the thread-local variable set by one thread will not affect the value of the
eT

thread-local variable in another thread.

For example, ThreadLocal can be used to store a user's session information in a web
Th

application, where each user's session information is specific to the thread that is handling
the user's request.
y
m
de
ca
gA
tin
es
eT
Th

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.
y
m
de
ca
In this example, the finalize() method is used to delete a file when the MyResource object is
eligible for garbage collection.
gA
However, it's important to note that the finalize() method is not guaranteed to be run before
an object is garbage collected, and it's not guaranteed to be run at all.

So, it's not recommended to rely on finalize() method to release resources, instead use
tin

try-catch-finally or try-with-resources statements to release resources and also use explicit


methods like close() to release resources.
es

it's not recommended to use finalize() method for critical tasks, because it's not
guaranteed to be run and it might cause performance issues.
eT

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


Th

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.

y
m
What is daemon thread?

de
Daemon thread in Java is a low-priority thread that runs in the background to perform tasks
such as garbage collection.
public final void setDaemon(boolean on)

ca
What is race condition in Java?
A condition in which the critical section (a part of the program where shared memory is
accessed) is concurrently executed by two or more threads.
gA
tin
es
eT
Th

You might also like