Java Notes - TheTestingAcademy (Pramod Sir)
✅ Why Learn Java?
Java is a general-purpose, object-oriented programming language that was designed by
James Gosling at Sun Microsystems in 1995.
Compilation of the Java applications results in the bytecode that can be run on any
platform using the Java Virtual Machine. Because of this, Java is also known as a
WORA (Write Once, Run Anywhere)
Java Version - [Link]
High Level, Platform independent & Architecture Neutral
Secure, Robus, Multi Thread, Distributed and OOPs language.
⚠️Why Java is not 100% Object-Oriented?
Primitive data types.
Use of Static.
Wrapper class
⚠️ How is Java Secure?
JVM which protects from unauthorized or illegal access to system resources.
Oops and inner classes
Ref - [Link]
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
Check the Languages, with the Level of Abstraction
Major Features of Java Programming Language
Simple.
Object-Oriented.
Platform Independent.
Portable.
Robust.
Secure.
Interpreted.
Multi-Threaded
⚠️ What is Source Code?
Human understandable code written using High Level Programming language is called as
Source Code. ([Link])
⚠️What is Byte Code?
JVM understandable code generated by Java Compiler is called as Byte Code. Byte code is
also called as Magic Value.
⚠️Why C and C++ are Platform Dependent?
When you compile C or C++ program on one Operating System then compiler generates that
Operating System understandable native [Link] code generated on one OS will not run on
other OS directly. Window -> exe, Mac -> dmg, Linux, deb, pkg
⚠️What is Java Compiler?
Java Compiler is a program developed in C or C++ programming language with the name
“javac”. It will check syntactical or grammatical errors of the programs. It converts source code
to byte code.
⚠️ What is Java Interpreter?
Java Interpreter is a program developed in C or C++ programming language with the name
“Java”. It will convert byte code to native code line by line. It will execute that native code.
⚠️ What is JIT Compiler?
JIT (Just-In-Time) compiler is a component of the Java Runtime Environment. JIT Compiler
compiles or translates or converts the neccessary part of the bytecode into machine code
instead of converting line by line. Because of this, performance of Java program has improved.
Run your First Java Program
1. Install Java and Set path to the Home in Windows / Mac
2. Install IDE (IntelliJ) and you can avoid the first step.
3. Create new command line project and Add the code and run the program.
How to Set JAVA_HOME path in MAC - Click here
1. Download the JDK latest -
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >>
~/.bash_profile
2. If you're using zsh (which probably means you're running macOS Catalina or newer),
then it should instead be:
echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >>
~/.zshrc
3. In either case, restart your shell.
How to Set JAVA_HOME path in Widnows
Set the JAVA_HOME Variable
To set the JRE_HOME or JAVA_HOME variable:
1. Locate your Java installation directory
If you didn't change the path during installation, it'll be something like
C:\Program Files\Java\
jdk21
You can also type where java at the command prompt.
2. Do one of the following:
Windows 7 – Right click My Computer and select Properties > Advanced
Windows 8 – Go to Control Panel > System > Advanced System Settings
Windows 10 – Search for Environment Variables then select Edit the
system environment variables
3. Click the Environment Variables button.
4. Under System Variables, click New.
5. In the Variable Name field, enter either:
JAVA_HOME if you installed the JDK (Java Development Kit)
or
JRE_HOME if you installed the JRE (Java Runtime Environment)
6. In the Variable Value field, enter your JDK or JRE installation path .
If the path contains spaces, use the shortened path name. For example, C:\
Progra~1\Java\jdk1.8.0_65
Note for Windows users on 64-bit systems
Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'
7. Click OK and Apply Changes as prompted
⚠️What is JDK (Java Development Kit) / SDK (Software Development Kit)?
It is a set of various utility programs which are required for developing and executing the java
programs.
It is Platform dependent. Various JDKs are provided for various Operating Systems.
Following are various utility programs provided under JDK:
1) Java Development Tools
i. javac
ii. java
iii. javap
iv. Jar
etc
2) Source Files
3) JRE
etc
⚠️What is JRE?
Ans: JRE stands for Java Runtime Environment. It is an implementation of JVM. It contains
class
libraries, Interpreter, JIT Compiler etc. Only JRE is enough to run the Java program
⚠️What is JVM?
Ans: JVM stands for Java Virtual Machine. It is a specification provided by SUN Microsystem
whose
implementation provides an environment to run our Java applications. JVM becomes an
instance of
JRE at run time.
Sun’s implementations of the Java Virtual Machine (JVM) is itself called as JRE. Sun’s JRE is
availabe
as a part of JDK and also as a separate application.
Many vendors has implemented JVM. Some of them are SUN JRE, IBM JRE, Oracle JRE etc
JDK Vs JRE
Java Editions
1. Enterprise Edition - Servlets, JSP, JDBC etc.
2. Micro Edition - micro devices like Mobiles,Setup Box etc
3. Standard Edition - Used to develop standalone applications using applet and swing.
Edition Description
Java SE The main edition of Java that is used for desktop and server
(Standard applications. It includes the Java language, JVM, class libraries, and
Edition) tools for developing, testing, and deploying Java applications.
A set of specifications and APIs for developing enterprise
Java EE
applications, including web and mobile applications, distributed
(Enterprise
systems, and cloud computing. It includes components like servlets,
Edition)
JSPs, EJBs, JMS, JPA, and more.
A platform for developing applications for mobile and embedded
Java ME
devices, like phones, PDAs, and set-top boxes. It includes a subset of
(Micro
the Java SE APIs and tools, as well as additional libraries for mobile-
Edition)
specific features like user interfaces and networking.
A platform for developing rich client applications and user interfaces,
Java FX
with features like graphics and media support, animation, and web
integration. It includes a set of APIs and tools for developing desktop,
mobile, and web applications.
Note that Java EE has been rebranded as Jakarta EE, as Oracle transferred ownership of the
Java EE specification to the Eclipse Foundation.
Java Versions
Java Version Key Features
Java 1.0 Garbage collection, multi-threading, network programming
Java 1.1 Inner classes, JavaBeans, JDBC
Java 1.2 (Java
Collections framework, reflection, Swing GUI toolkit, JNDI
2)
Java 1.3 (Java
HotSpot JVM, Java Sound API, Bluetooth support
2)
Java 1.4 (Java
Assertions, regular expressions, Java Web Start, JNI
2)
Java 5 (Java Generics, annotations, enhanced for loop, concurrent API
1.5)
Java 6 (Java
JAXB API, Java Compiler API
1.6)
Java 7 (Java Try-with-resources, multi-catch exceptions, Fork/Join Framework,
1.7) NIO.2
Lambda expressions, Stream API, [Link] package,
Java 8 (1.8)
CompletableFuture
Java 9 Module system, private interface methods, JShell
Java 10 Local variable type inference, garbage collector improvements
HttpClient API, var keyword for lambda parameters, Unicode
Java 11
10.0 support
Java 12 Switch expressions, garbage collector improvements
Java 13 Text blocks, Z Garbage Collector improvements
Java 14 Record classes
Java 15 Sealed classes and interfaces, garbage collector improvements
Pattern matching for instanceof, garbage collector and JFR
Java 16
improvements
Java 17 Sealed Types Preview, garbage collector improvements
Java Comments
Comment
Type Syntax Description
A comment that extends from the // marker to the end of the line.
Single-line //
It is ignored by the compiler and used for adding notes and
comment comment
explanations to the code.
A comment that can span multiple lines, starting with the /*
/*
Multi-line marker and ending with the */ marker. It is also ignored by the
comment
comment compiler and used for adding longer explanations or temporarily
*/
disabling code.
Documentation /** A comment that begins with /** and ends with */. It is similar to a
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.
A special type of documentation comment that starts with /** and
includes additional Javadoc tags for generating documentation. It
Javadoc
/** can be used to describe classes, interfaces, methods, fields, etc.
comment
and their functionality. It is a best practice to include Javadoc
comments in your code for documentation purposes.
⚠️Why this Kolavari DI? (Reason for this error)
Install JDK properly
⚠️Difference between Java and C++
⚠️Differences between Oracle JDK and OpenJDK
Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.
Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to
replace licensed proprietary parts / replace with more high-performance items that only work on
specific OS] components without breaking the TCK compatibility.
[Link]
⚠️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 [Link]
Error Could not find or load main class Hello
[Link] : hello(Wrong name Hello)
[Link] : Incompatible magic value ( change in .class)
[Link] : Hello (Compiled with Old )
⚠️What are the ways available to set the PATH?
There are several ways to set the PATH, including using the command line, editing system
environment variables, and using third-party tools or scripts. The specific method used may vary
depending on the operating system being used.
⚠️What is the difference between PRIVATE JRE and PUBLIC JRE?
A PRIVATE JRE is a Java runtime environment that is installed and used by a specific
application or user, and is not shared with other applications or users on the same system. A
PUBLIC JRE is a Java runtime environment that is installed and made available to all
applications and users on the system.
⚠️Which JRE will be used while compiling the Java Source File?
The JRE is not used for compiling Java source files, but rather the Java Development Kit (JDK)
is used, specifically the Java compiler (javac) which is included in the JDK.
⚠️What will happen when I am compiling Java program without PRIVATE JRE?
Compiling a Java program does not require a PRIVATE JRE. However, if the program requires
a specific version of the JRE to execute, and that version is not installed on the system, the
program may not run properly.
⚠️Which JRE will be used while executing Java application?
The JRE that is used to execute a Java application depends on several factors, including the
system's PATH settings, the application's CLASSPATH settings, and any environment variables
that may be set.
⚠️What will happen when I am executing Java program without PUBLIC JRE?
If a PUBLIC JRE is not installed on the system, the Java application will not be able to run. The
user will need to install a JRE before the application can be executed.
⚠️Can we execute java program without setting PATH?
It is possible to execute a Java program without setting the PATH, but it requires specifying the
full path to the Java executable file every time the command is executed.
⚠️What is the difference between JVM and JRE?
JVM (Java Virtual Machine) is a virtual machine that runs Java bytecode, while JRE (Java
Runtime Environment) is a software package that includes the JVM as well as other libraries
and components required to run Java applications.
⚠️What is the difference between JIT Compiler and Java Interpreter?
A JIT (Just-In-Time) compiler is a component of the JVM that dynamically compiles bytecode
into machine code at runtime, while a Java Interpreter executes bytecode directly without
compiling it.
⚠️What is the difference between Byte code and Native code?
Bytecode is a machine-independent code that is generated by the Java compiler and is
designed to be executed by the JVM. Native code, on the other hand, is machine-specific code
that is directly executable by the CPU.
⚠️Is it possible to execute Java program without having JDK in machine?
It is possible to execute a Java program without having the JDK (Java Development Kit)
installed on the machine, but a JRE (Java Runtime Environment) must be installed.
⚠️Can I install multiple JDK versions in my machine?
Yes, it is possible to install multiple JDK (Java Development Kit) versions on the same machine.
It is important to manage the PATH and other environment variables correctly to ensure that the
correct version is used when compiling or executing Java programs.
⚠️Can I install multiple JRE versions in my machine?
Yes, it is possible to install multiple JRE (Java Runtime Environment) versions on the same
machine. It is important to manage the PATH and other environment variables correctly to
ensure that the correct version is used
Explain the main method in Java
The main method in Java is the entry point for any Java program.
It is a predefined method that is executed when a Java program is run, and is required in
every Java program.
The main method has a specific signature, which includes the keyword "public", the
keyword "static", the return type "void", and a parameter of type "String" array named
"args". Here is an example of the main method signature:
public static void main(String[] args) {
// code to be executed
}
The main method takes an optional argument, "args", which is an array of strings that ca
n be used to pass command-line arguments to the program.
Steps that the JVM takes to call the main method:
Loads the necessary classes for the program.
Locates the entry point class specified on the command line.
Locates the main method in the entry point class.
Sets up the environment and executes the code inside the main method.
When the main method completes, the JVM terminates the program.
JDK 11
✅ Keywords & Identifiers
Simple English words which are having predefined meaning in Java Programming
Language.
Keywords are also called as 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.
Identifiers - names those will be used to identify the programming elements like classes,
methods, variables, etc uniquely
Rules to follow when you define an Identifier:
1. Identifier can contain Alphabets, Digits, and two special symbol i.e. Dollar ($),
2. Underscore (_).
3. First character of an identifier must be an Alphabet or Dollar ($) or Underscore (_).
4. Keywords or Reserved words can't be used as Identifier.
✅ Variables and Data Types in Java
Variables
A variable is a container (storage area) used to hold data.
Each variable should be given a unique name (identifier).
Memory will be allocated for the variable while executing the program
Value of the variable can be changed any number of times during the program
execution.
Types of Variables
There are two types of variables based on data type used to declare the variable.
1) Primitive Variables
2) Reference Variables
Some Points
A variable is a storage location paired with an associated symbolic name (an identifier),
which contains some known or unknown quantity of information referred to as a value.
Variables in Java are strongly typed; thus they all must have a data type declared with
their identifier
There are three rules to create an identifier:
o Characters from A to Z, as well as their lowercase counterparts, can be used.
o Numbers from 0-9 can be used.
o Special characters that can be used are $ (the dollar sign) and _ (underscore).
int $ = 34; // 44 - Yes
// int _pramod = 34; // Yes
// int 123 = 34; // NO
// int 123_name = 34; // NO
// int 1name = 34; // no
//int #1 = 34; // No
// [Link]($);
Primitive Variables
Variables declared with primitive data types are called as primitive variables.
int a; int b = 99; double d1; double d2=9.9;
Reference Variables - Variables declared with user defined data types are called as reference
variables.
String str1;
String str2 = “TheTestingAcademy”;
Based On SCOPE variables are 3 types
Instance Variables : Variables declared in the class without using static keyword are
called as Instance Variables.
Static Variables : Variables declared in the class using static keyword are called as
Static variables.
Local Variables - Variables declared in the member of the class like method etc are
called as Local variables.
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.
o 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.
There are eight primitive data types in Java, which are categorized into four groups: integer,
floating-point, character, and boolean.
Data Size Default
Type (bits) Value Example
byte 8 0 byte b = 10;
short 16 0 short s = 100;
int 32 0 int i = 1000;
long l =
long 64 0L
100000L;
float 32 0.0f float f = 1.23f;
double d =
double 64 0.0d
1.23;
char 16 '\u0000' char c = 'A';
boolean b =
boolean 1 false
true;
How byte b = 10 is stored in JVM?
When the statement byte b = 10 is executed in Java, the JVM creates a variable named b of
type byte and assigns it the value 10.
Internally, the value 10 is represented in binary format as 00001010 (since byte data type is 8
bits in size), and it is stored in memory as a sequence of 8 bits. The JVM allocates a specific
memory location for the variable b, and the binary representation of the value 10 is stored at
that memory location.
To illustrate this, let's assume that the memory location allocated for the variable b is 0x1000.
The binary representation of the value 10 is 00001010, which can be stored in a single byte of
memory. Therefore, the value 10 is stored at memory location 0x1000 as follows:
Reference data types are used to store complex objects, such as arrays and classes. These
data types are created using predefined or custom classes.
User Defined Data types
Four types of User Defined Data types:
Class type - String
Interface type
Enum type (From JAVA 5)
Annotation type (From JAVA 5)
Types of Variables There are two types of variables based on data type used to declare the
variable.
1) Primitive Variables - Variables declared with primitive data types are called as primitive
variables.
byte b; int a; double d; char ch;
2) Reference Variables - Variables declared with reference data types are called as reference
variables
String str; Hello h;
✅ Constants
Special variable whose value can't be modified during the program execution.
Constant is also called as final variable.
final int A=99;
final String STR="TTA";
final double D1=999.99;
Variables & Constants
1) Default value of char is either ASCII - 0 or UNICODE \u0000.
2) Default value of char is not space.
3) JVM will not provide default value for Local Variable.
4) Local variable must be initialized before using .
5) JVM will provide default value for static Variable.
6) Static variable can be accessed from Static method (main method).
7) JVM will provide default value for instance Variable.
8) Instance variable cannot be accessed directly from Static method (main method).
9) You can't declare multiple variables of different data types in single variable declaration
statement.
10) You can declare multiple variables of same data types in a single statement.
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.
How many keywords are
Q1 48
available prior to Java 5?
What is the keyword
Q2 enum
added newly in Java 5?
Which of the following
B) goto
are valid Java keywords?
E) struct
A) instanceof B) goto C)
Q3
I) virtual
null D) assert E) struct F)
J) signed
true G) Long H) false I)
virtual J) signed
What are the keywords
Q4 available which can’t be goto, const
used in Java Program?
An identifier is a name assigned to a variable, method, class,
What is an identifier?
or package. The rules to follow while defining an identifier
What are the rules to
Q5 are: i) It should start with a letter or underscore, ii) No
follow to define an
whitespace or special characters allowed except underscore,
identifier?
iii) It should not be a reserved keyword.
What is data type? How Data type defines the type of value a variable can hold. There
Q6 many types of data types are two types of data types: i) Primitive data types, ii)
available? Reference data types.
How many primitive data
Q7 8
types available?
What is the Integral data
Q8 type that will not allow char
negative value?
What is the default value
Q9 '\u0000'
of char data type?
Why the range of short
Q1 and char are different The range of short and char are different because short is
0 even both required 2 signed and char is unsigned.
bytes of memory?
How many types of User
Q1
defined data types 2
1
available up to JDK1.4?
How many types of User
Q1
defined data types 1
2
available from Java 5?
Q1
Is String a data type? No, it is a class.
3
Q1 What is the default value
null
4 of reference data type?
What are the possible
Q1
values can be used for true or false
5
boolean type?
Q1
What is a variable? A variable is a container that stores values.
6
How many types of
Q1
variables are available as 2
7
per the data type?
How many types of
Q1
variables are available as 3
8
per the scope?
What are the differences
Q1 between Primitive Primitive variables hold the actual values, while reference
9 variables and Reference variables hold the memory location of the object.
variables?
Q2 What is the default value There is no default value for a local variable. It must be
0 of local variable? initialized before use.
How can I declare
Q2 multiple types of Not possible. Variables must be declared separately for each
1 variables in one data type.
statement?
How can I declare
Q2 Multiple variables of the same type can be declared in one
multiple variable of same
2 statement by separating each variable name with a comma.
type in one statement?
How can I declare and
Q2 Declare and initialize a variable in one statement by assigning
initialize a variable in one
3 a value to it when it is declared.
statement?
How can I declare and Declare and initialize multiple variables of the same type in
Q2 initialize multiple one statement by separating each variable name with a
4 variables of same type in comma and assigning a value to each variable when it is
one statement? declared.
Can I change the value of
Q2
variable during program Yes
5
execution?
When will the memory be
Q2 Memory for variables is allocated at runtime, while the
allocated for the
6 program is executing.
variables?
UNICODE Characters
UNICODE stands for UNIversal CODE.
Every character will have UNICODE value.
UNICODE Notation
Syntax:
o \uXXXX - X will be hexadecimal digit
Starts with \u followed by four hexadecimal digits.
UNICODE Range
\u0000 (0) to \uFFFF (65535)
Practice QnA
Give the output of the following in the following
1. It will not compile.
2. At runtime error
3. Condition 1
4. Condition 2
Question 1
int enum=9;
[Link](enum);
Question 2
char char='A'; [Link](char);
✅ 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
Floating-point
Numbers with decimal points, such as 3.14 or -0.0025
literals
Character
A single character enclosed in single quotes, such as 'a'
literals
Boolean literals A value of either true or false
A sequence of characters enclosed in double quotes, such
String literals
as "hello world"
A special literal that represents a null reference or a null
Null literals
value
Types of Literals
1) Boolean Literals - true, false
2) Character Literals -
3) String Literals
4) Integral Literals
5) Floating Literals
6) null Literal
1. Boolean Literals
There are two boolean literals 1) true 2) false
2. Character Literals
A char type variable can hold following:
Single character enclosed in single quotation marks
Escape Sequence
ASCII Value
UNICODE Character
Octal Character
Diff between /n and /r
[Link]
Escape Sequence - Task_12.java
ASCII stands for American Standard Code for Information Interchange.
Every character enclosed in single quotation marks will have an integer equivalent value
called as ASCII value.
ASCII Value Range is 0 – 255.
ASCII Value can be assigned to a char type variable
Octal Value as char type ( 0)
061 -> 49
061 = (0 × 8²) + (6 × 8¹) + (1 × 8⁰) = 49
[Link]
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
What is a literal? program without needing to be computed or
evaluated.
There are six types of literals available in
How many types of literals are programming languages: numeric literals,
available? character literals, boolean literals, string
literals, array literals, and null literals.
How many boolean literals are There are only two boolean literals available,
available? which are true and false.
When you assign the value 1 to a boolean type
What will happen when I assign 1 variable, it will be interpreted as true because
to boolean type variable? any non-zero value is considered as true in
boolean expressions.
No, you cannot store an empty character in a
Can we store empty character in
char type variable because it requires at least
char type variable?
one character.
To store a single quote in a char variable, you
How to store single quote in char need to use the escape sequence ' because the
variable? single quote is a reserved character in
programming languages.
An escape sequence is a combination of
characters used to represent special characters
What is Escape Sequence?
or non-printable characters in a string literal. It
usually starts with a backslash () character.
What will be displayed when
The string "UNICODE of A is A" will be displayed
UNICODE value is found in String
because \u0041 represents the Unicode value of
Literal? String str="UNICODE of A
the letter A.
is \u0041";
What will be displayed when Octal
The string "Octal of A is A" will be displayed
representation is found in String
because \101 represents the octal value of the
Literal? String str="Octal of A is \
letter A.
101";
The string "Hello" will be displayed on the first
What will happen when Escape
line, and "Guys" will be displayed on the next
Sequence is found in String
line because \n represents the newline
Literal? String str="Hello\nGuys";
character.
Integer Literals
Decimal Literals- // Base of 10
Octal Literals - int b=0101; // Base of 8
Hexadecimal Literals - int c=0Xface; // base 16 rather than base 10
Binary Literals (From Java 7) - int b2 = 0b101;
Scientific / Exponent N Literals
float f = 129.8763e2F;
double d1 = 129.8763e+2;
double d2 = 12987.63e-2;
[Link](f);
[Link](d1);
[Link](d2);
Null literal
null is a value.
It is default value for any reference variable.
If the value of reference variable is null then it indicates that address/reference is not
available in the variable.
String str2=null;
[Link](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
o Only one operand is required.
2) Binary Operator
o Two operands are required.
3) Ternary Operator
o Three Operands are required.
Types of operator depending on the operation:
Arithmetic Operators
o i. Unary Arithmetic Operators
o ii. Binary Arithmetic Operators
String Concatenation Operator
Assignment Operator
o i. Simple Assignment Operator
o ii. Compound Assignment Operators
Increment & Decrement Operators
Relational Operators
Logical Operators
new Operator
instanceof Operator
Conditional or Ternary Operator
Bitwise Operators.
Unary Arithmetic Operators
unary minus(-)
increment(+)
o Pre
o post
decrement(-)
o Pre
o post
NOT(!) - boolean and condition
Bitwise Complement (~) - unary operator returns the one’s complement representation of
the input value or operand,
a = 5 [0101 in Binary]
result = ~5
Addressof operator(&)
sizeof()
Binary Arithmetic Operators
Remember this
String Concatenation Operator (+)
+ operator can be used for two purposes:
1) Arithmetic Addition
2) String Concatenation
Simple Assignment Operator (=)
It is a binary operator.
It is used to assign the value to a variable. =
o Operand1 must be a variable.
o Operand2 can be a variable, value or expression.
Type Casting
Source type is not same as destination type then source type must be converted to
destination type.
Type casting can be done in two ways:
o Implicit casting
o Explicit Casting
Type casting can be done in two ways:
o Implicit casting
o Explicit Casting
Implicit casting:
When type casting is happening automatically by the compiler then it is called as Implicit
Casting.
Explicit Casting:
When type casting is happening explicitly by the programmer then it is called as Explicit
Casting.
There are two types of conversions:
o Widening
o Narrowing
Widening
Widening is the process of converting lower type to higher type. This is safe conversion.
Ex:
byte b=10;
int a=b; // VALID – Implicit Casting
int a= (int)b; // VALID – Explicit Casting
Narrowing is the process of converting higher type to lower type.
Ex:
int a=300;
byte b=a; // INVALID – Implicit Casting
byte b = (byte)a; // VALID – Explicit Casting
int a=300; -> int means 32 bits memory required
00000000000000000000000100101100
byte b1=(byte)a; -> byte means 8 bits memory required
00101100
Value is
0 * 27 + 0 * 26 + 1 * 25 + 0 * 24 + 1 * 23 + 1 * 22 + 0 * 21 + 0 * 20
0 + 0 + 32 + 0 + 8 + 4 + 0 + 0 = 44.
Compound Assignment Operators
int a=90; a+=9; => a = a+9;
Increment (++) / Decrement (--) Operators
Increment operator will be used to increase the value of the variable by 1.
Decrement operator will be used to decrease the value of the variable by 1.
Increment / Decrement operator can't be applied for value/constant.
Relational Operators
Logical Operators
Logical OR and Logical AND ( || , &&
new Operator
new operator is used to create the new object for class.
It returns of the address of newly created object.
String s1 = new String(“Pramod”);
instanceof Operator
It is used to check whether the given object belongs to specified class or not.
Result of instanceof operator is boolean value.
It returns true if given object belongs to specified class otherwise false.
It is also called aCOMPARISONERATOR.
[Link](s1 instanceof Object);
Conditional Operator
It is ternary operator. ? : Operand1 must be of boolean type.
If Operand1 is true then Operand2 will be returned otherwise Operand3 will be returned.
Bitwise Operators
Bitwise AND o Bitwise OR o Exclusive OR (XOR)
[Link]
1. 7+ (6 + 5 *3) - 4/2
2. boolean b = (boolean)1; b)
3. String str=(String)99;
Interview QnA
Question Answer
What is the use of bitwise Bitwise operators are used to perform bitwise operations
operators? on binary representations of integers.
What is the result type of String The result type of String concatenation operation is
concatenation operation? always a String.
What will happen when I try to
The code will not compile because you cannot assign an
assign int type to String type
int value to a String variable directly.
variable? Ex: String str=99;
What are types of operands Comparison operators can be used with numeric and
allowed for comparison operators? boolean operands.
What is the difference between The prefix form increments the value before it is used,
prefix and postfix forms of while the postfix form uses the value and then increments
increment operator? it.
Type casting is a way to convert a value from one data
What is type casting and what are
type to another. The types available are widening
the types available?
conversion (implicit) and narrowing conversion (explicit).
The new operator is used to create an instance of a class
What is the use of new operator?
or an array.
What is the difference between The String concatenation operator (+) is used to
String Concatenation and concatenate two strings, while the arithmetic addition
Arithmetic Addition operator? operator (+) is used to add two numeric values.
The bitwise operators available are: ~ (bitwise NOT), &
What are the bitwise operators
(bitwise AND), | (bitwise OR), ^ (bitwise XOR), << (left
available?
shift), >> (right shift), and >>> (unsigned right shift).
What are equality operators The equality operators available are: == (equal to) and !=
available? (not equal to).
What is the difference between Implicit casting is done automatically by the compiler,
Implicit casting and Explicit while explicit casting requires the programmer to specify
Casting? the conversion explicitly.
What is the use of assignment The assignment operator is used to assign a value to a
operator? variable or an array element.
2's complement is a way of representing negative
What is 2's Complement? integers in binary. It involves flipping all the bits and
adding 1 to the result.
What are types of operands Arithmetic operators can be used with numeric operands
allowed for arithmetic operators? (int, long, float, double) and char operands.
What is the difference between
Unary arithmetic operators act on a single operand, while
unary arithmetic and binary
binary arithmetic operators act on two operands.
arithmetic operators?
What is the syntax of Explicit
The syntax of explicit casting is: (datatype) value.
casting?
What are types of operands Bitwise operators can be used with integer operands (int,
allowed for bitwise operators? long, short, char, byte).
What is the use of Logical NOT The logical NOT operator (!) is used to negate a boolean
operator? value.
What is the difference between The prefix form decrements the value before it is used,
prefix and postfix forms of while the postfix form uses the value and then
decrement operator? decrements it.
What is the use of instanceof The instanceof operator is used to check if an object is an
operator? instance of a particular class or interface.
What is result type when you add
The result type when you add two byte variables is int.
two byte variables?
What is result type when you add The result type when you add long and float variables is
long and float variables? float.
Question Answer
An operator is a symbol that represents a specific
What is an operator?
operation to be performed between operands.
What are the valid conditions for Division by a positive number or multiplication by a
"Infinity" output? positive infinity.
What is the use of arithmetic Arithmetic operators are used to perform mathematical
operators? calculations between operands.
What is the result type when you
The result type is a float.
add long and float variables?
What is the difference between String concatenation is used to join two or more strings
String Concatenation and together, while arithmetic addition is used to add
Arithmetic Addition operator? numeric values.
The new operator is used to allocate memory for an
What is the result of new operator?
object and returns a reference to that object.
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.
What is the use of bitwise Bitwise operators are used to perform operations at the
operators? bit level.
Type casting is the process of converting one data type
What is type casting and what are
to another. The two types of type casting are implicit
the types available?
casting and explicit casting.
What will happen when I try to It will result in a compilation error because they are
assign int type to String type incompatible types.
variable?
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 operators work on a single operand, while binary
unary arithmetic and binary
operators work on two operands.
arithmetic operators?
What is the use of Logical NOT The logical NOT operator is used to reverse the truth
operator? value of a boolean expression.
What is the difference between Implicit casting is done automatically by the compiler,
Implicit casting and Explicit while explicit casting is done manually by the
Casting? programmer.
What are compound assignment Compound assignment operators combine an arithmetic
operators available? or bitwise operation with an assignment.
2's complement is a binary representation of a signed
What is 2's Complement?
number that uses the most significant bit as a sign bit.
What are types of operands allowed Bitwise operators can be applied to integer types: byte,
for bitwise operators? short, int, and long.
What is the syntax of Explicit The syntax of explicit casting is: (target_type)
casting? expression.
The relational operators compare two values and return
What are the relational operators?
a boolean result: <, >, <=, >=.
What is result type when you add
The result type is an int.
byte and int variables?
What are the bitwise operators
The bitwise operators are: &,
available?
What is the difference between The prefix form evaluates and returns the value after the
prefix and postfix forms of operation, while the postfix form evaluates and returns
decrement operator? the value before the operation.
What is the result type of String
The result type is a String.
concatenation operation?
What is the use of instanceof The instanceof operator is used to test whether an object
operator? is an instance of a particular class or not.
Widening casting occurs when you convert a smaller
What is the difference between
type to a larger type, while narrowing casting occurs
Widening and Narrowing?
when you convert a larger type to a smaller type.
✅ Conditions and Loop
If
condition -> true or false
if(condition)
{ // Statements (IF BLOCK) }
Problem to find the Even and Odd with % Mod
if(a % 2==0)
[Link]("Value is EVEN");
else
[Link]("Value is ODD");
}
Problem to find the MAX three
if(a>b && a> c)
max=a;
else if(b> a && b>c)
max = b;
else
max=c;
[Link]("Max value is
"+max);
Switch : Multi-way branch statement
[ ] Java switch statement executes one statement from multiple conditions.
[ ] Java switch expressions must be of byte, short, int, long(with its Wrapper type),
enums and String. Beginning with JDK7, it also works with enumerated types (Enums
in java), the String class, and Wrapper classes.
[ ] case/s values are not allowed.
[ ] The value for a case must be constant or literal. Variables are not allowed.
[ ] break can’t be used with elseif condition
// switch statement
switch(expression)
{
// case statements
// values must be of same type of expression
case value1 : expression = value 1 ->
// Statements
break; // break is optional
case value2 :
// Statements
break; // break is optional
// We can have any number of case statements
// below is default statement, used when none of the cases is true.
// No break is needed in the default case.
default :
// Statements
}
String browser = "chrome"
switch(browser){
case "chrome" :
sop("chrome started!!");
break;
Default fall through due to missing break - JDK 13
Much improved switch accepts multiple values per case.
switch (itemCode) {
case 001, 002, 003 :
[Link]("It's an electronic gadget!");
break;
case 004, 005:
[Link]("It's a mechanical device!");
yield is used to return a value
A new keyword yield has been introduced. It returns values from a switch branch only.
We don’t need a break after yield as it automatically terminates the switch expression.
int val = switch (code) {
case "x", "y" :
yield 1;
case "z", "w" :
yield 2;
}
Switch can be used as an expression
String text = switch (itemCode) {
case 001 :
yield "It's a laptop!";
case 002 :
yield "It's a desktop!";
case 003 :
yield "It's a mobile phone!";
default :
throw new IllegalArgumentException(itemCode + "is an unknown device!");
}
Switch with arrows
switch (itemCode) {
case 001 -> [Link]("It's a laptop!");
case 002 -> [Link]("It's a desktop!");
case 003,004 -> [Link]("It's a mobile
phone!");
}
For
1.
While
condition of while statement is mandatory and must be boolean type
Do While
When you are using for statement or while statement then it verifies the condition
before executing the block.
So in the case of for statement and while statement, when first time condition is false
then the block will not be executed.
for and while statement are also called as Entry Controlled Loop.
If you want to execute the block at least once then use do-while statement
In the case of do-while first block of statements will be executed and then condition will
be verified.
// While -> Condition -> Body -> Increment
// Do While -> Body -> Condition -> Increment
break Statement and continue
break is a keyword.
It can be used within switch or any looping statement.
It is used to terminate the execution of the current looping/switch statement.
break can be used in two ways:
break;
break <label>;
Continue
continue is a keyword.
It can be used within any looping statements.
It is used to continue the execution of the current looping statement with next iteration.
continue can be used in two ways:
o continue;
o continue <label>;
✅ Arrays
Array is a collection of data which is of similar type.
Array is also called as Homogeneous data structure.
Elements of an array will be stored in contiguous memory locations.
Arrays are objects in Java.
Three tasks to remember while you are working with arrays:
o o Array Declaration
o o Array Construction
o o Array Initialization
Arrays can be constructed with multiple dimensions i.e 1-D Array, 2-D Array etc.
length
Use 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
[Link] 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
✅ Functions
1. No Return Type - void
2. Return Type - data -> Primitive or Ref Type
3. Main method overladoing - Interview.
✅ Object Class in Java
Object class is present in [Link] package.
Every class in Java is directly or indirectly derived from the Object class.
Object class methods are available to all Java classes.
Ref image - geeksforgeeks
toString() method
In Java, the toString() method is a method defined in the Object class that returns a string
representation of an object.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
@Override
public String toString() {
return "Person[name=" + name + ", age=" + age +
"]";
}
}
Person p = new Person("John", 30);
[Link](p); // prints "Person[name=John,
age=30]"
hashCode() method
In Java, the hashCode() method is a method defined in the Object class that returns an integer
hash code value for an object.
The hashCode() method is implemented by converting the internal address of the object into an
integer value. If two objects are equal according to the equals() method, then they should have
the same hash code.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + [Link]();
result = 31 * result + age;
return result;
}
}
Person p1 = new Person("John", 30);
Person p2 = new Person("John", 30);
[Link]([Link]()); // prints a number
[Link]([Link]()); // 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;
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (!(obj instanceof Person)) return false;
Person other = (Person) obj;
return [Link]([Link]) && age ==
[Link];
}
}
Person p1 = new Person("John", 30);
Person p2 = new Person("John", 30);
Person p3 = new Person("Jane", 30);
[Link]([Link](p2)); // prints true
[Link]([Link](p3)); // prints false
getClass() method,
public class Test {
public static void main(String[] args)
{
Object obj = new String("GeeksForGeeks");
Class c = [Link]();
[Link]("Class of Object obj
is : "
+ [Link]());
}
}
Output - Class of Object obj is :
[Link]
finalize() method
This method is called just before an object is garbage collected. It is called the Garbage
Collector on an object when the garbage collector determines that there are no more references
to the object.
// Java program to demonstrate working of
finalize()
public class Test {
public static void main(String[] args)
{
Test t = new Test();
[Link]([Link]());
t = null;
// calling garbage collector
[Link]();
[Link]("end");
}
@Override protected void finalize()
{
[Link]("finalize method
called");
}
}
clone()method
It returns a new object that is exactly the same as this object. For clone() method refer Clone().
public class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
@Override
public Person clone() {
try {
return (Person) [Link]();
} catch (CloneNotSupportedException e) {
// This should never happen, since we are
Cloneable
throw new InternalError(e);
}
}
}
Person p1 = new Person("John", 30);
Person p2 = [Link]();
[Link](p1 == p2); // prints false
Note that the clone() method only creates a shallow copy of the object, which means that it only
copies the references to the object's fields, rather than creating new copies of the objects
themselves. If you want to create a deep copy of an object, you need to create a new copy of
each object contained within the original object.
📙 Arrays in Java
A group of like-typed variables referred to by a common name.
Arrays are stored in contiguous memory.
The variables in the array are ordered, and each has an index beginning from 0.
The size of an array must be specified by int or short value and not long.
The size of the array cannot be altered(once initialized).
JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been
accessed with an illegal index
MyClass
myClassArray[];
Object[] ao,
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Array of Objects
Student[] arr = new Student[5];
int[] numbers = new int[5];
// set the values of the array
elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// print the values of the array
elements
for (int i = 0; i < [Link]; i+
+) {
[Link](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 [Link];
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// create an array to store the numbers
int[] numbers = new int[100];
int size = 0;
// read the numbers from the user
int n;
do {
[Link]("Enter a number: " , -1 to stop
entering”);
n = [Link]();
if (n >= 0) {
numbers[size] = n;
size++;
}
} while (n >= 0);
// find the highest and lowest numbers
int highest = numbers[0];
int lowest = numbers[0];
for (int i = 1; i < size; i++) {
if (numbers[i] > highest) {
highest = numbers[i];
}
if (numbers[i] < lowest) {
lowest = numbers[i];
}
}
// print the highest and lowest numbers
[Link]("The highest number is " + highest);
[Link]("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];
public class multiDimensional {
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4,
2 } };
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
[Link](arr[i][j] + " ");
[Link]();
}
}
}
🧵 String in Java
Sequence of Characters.
String is a built-in class in [Link] package.
String is final class, so you can't define the subclass for String class.
String class implements the following interfaces:
o [Link]
o [Link]
o [Link]
String class has following variable to hold data.
o private final char value[];
String objects are immutable objects. It means once the object is created then the
content or data of the object can't be modified.
When you try to modify the contents of object then new object will be created as a
result.
How String can be represented?
1) String class
2) StringBuffer
3) StringBuilder
4) Array of Characters
5) ArrayList of Characters
Why String is Immutable in Java?
The reason for making strings immutable in Java is to increase efficiency, security, and thread-
safety.
Here is an example that demonstrates the immutability of strings in Java:
String str1 = "Hello";
String str2 = [Link](" World");
[Link](str1); // Output: Hello
[Link](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.
[Link]
Concept of String Pool and New Operator
String class provides a wide range of functions to manipulate strings.
Here are some of the most commonly used functions of the String class:
charAt(int index): Returns the character at the specified index in the string.
Example: "hello".charAt(0) returns 'h'.
concat(String str): Concatenates the specified string to the end of the original string.
Example: "hello".concat(" world") returns "hello world".
contains(CharSequence s): Returns true if the string contains the specified sequence of
characters, otherwise false.
Example: "hello world".contains("world") returns true.
equals(Object obj): Returns true if the string is equal to the specified object, otherwise false.
Example: "hello".equals("world") returns false.
equalsIgnoreCase(String str): Returns true if the string is equal to the specified string,
ignoring case differences, otherwise false.
Example: "HELLO".equalsIgnoreCase("hello") returns true.
indexOf(int ch): Returns the index of the first occurrence of the specified character in the
string, or -1 if the character is not found.
Example: "hello".indexOf('l') returns 2.
length(): Returns the length of the string.
Example: "hello".length() returns 5.
replace(char oldChar, char newChar): Returns a new string resulting from replacing all
occurrences of the specified oldChar with the specified newChar.
Example: "hello".replace('l', 'w') returns "hewwo".
split(String regex): Splits the string into an array of substrings based on the specified regular
expression.
Example: "hello world".split(" ") returns ["hello", "world"].
substring(int beginIndex, int endIndex): Returns a new string that is a substring of the
original string, starting from the specified beginIndex and ending at the endIndex (exclusive).
Example: "hello".substring(1, 3) returns "el".
toLowerCase(): Returns a new string with all characters converted to lowercase.
Example: "HELLO".toLowerCase() returns "hello".
toUpperCase(): Returns a new string with all characters converted to uppercase.
Example: "hello".toUpperCase() returns "HELLO".
== operator checks if two string references point to the same memory location.
equals method compares the actual content of the strings, checking if they contain the same
sequence of characters.
StringBuilder and StringBuffer in Java
StringBuilder and StringBuffer are classes that provide mutable sequences of
characters.
They are designed for efficient string manipulation operations, such as appending,
inserting, or deleting characters from a string.
The main difference between StringBuilder and StringBuffer is that StringBuilder is not
thread-safe, while StringBuffer is thread-safe.
StringBuilder is faster and more efficient in single-threaded environments, while
StringBuffer is safer to use in multi-threaded environments.
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link]([Link]()); // Output: Hello World
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link]([Link]()); // Output: Hello World
StringBuffer and StringBuilder
equals() is not overriden in StringBuilder and StringBuffer class.
hashCode() is not overriden in the StringBuilder and StringBuffer class.
Table summarizing the most commonly used functions of StringBuilder and StringBuffer classes
in Java:
Function Description
append() Appends the specified character(s) or object to the end of the string.
Inserts the specified character(s) or object at the specified index in the
insert()
string.
Deletes the characters from the string between the specified start and end
delete()
indices.
deleteCharAt() Deletes the character at the specified index in the string.
Replaces the characters in the string between the specified start and end
replace()
indices with the specified string.
reverse() Reverses the order of the characters in the string.
Returns a substring of the string between the specified start and end
substring()
indices.
charAt() Returns the character at the specified index in the string.
length() Returns the length of the string.
Sets the character at the specified index in the string to the specified
setCharAt()
character.
capacity() Returns the current capacity of the string builder.
Ensures that the capacity of the string builder is at least the specified
ensureCapacity()
minimum capacity.
trimToSize() Trims the capacity of the string builder to its current length.
Note that StringBuilder and StringBuffer share most of their functions and have very similar
syntax. The main difference between them is that StringBuilder is not thread-safe, while
StringBuffer is thread-safe.
[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;
[Link]("Original word: ");
[Link]("Pramod"); //Example word
for (int i=0; i<[Link](); i++)
{
ch= [Link](i); //extracts each character
nstr= ch+nstr; //adds each character in front of the
existing string
}
[Link]("Reversed word: "+ nstr);
}
Palindrome
Input : str = "abba"
Output: Yes
Input : str =
"pramod"
Output: No
public static boolean isPalindrome(String str)
{
// Initializing an empty string to store the
reverse
// of the original str
String rev = "";
// Initializing a new boolean variable for the
// answer
boolean ans = false;
for (int i = [Link]() - 1; i >= 0; i--) {
rev = rev + [Link](i);
}
// Checking if both the strings are equal
if ([Link](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";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
[Link](input);
// reverse StringBuilder input1
[Link]();
// print reversed String
[Link](input1);
}
Reverse Words in String
Input: s = “i love programming very much”
Output: s = “much very programming love i”
// Java program to reverse a String
import [Link].*;
class TheTestingAcademy {
// Reverse the letters
// of the word
static void reverse(char str[], int start, int
end)
{
// Temporary variable
// to store character
char temp;
while (start <= end) {
// Swapping the first
// and last character
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
// Function to reverse words
static char[] reverseWords(char[] s)
{
// Reversing individual words as
// explained in the first step
int start = 0;
for (int end = 0; end < [Link]; end++)
{
// If we see a space, we
// reverse the previous
// word (word between
// the indexes start and end-1
// i.e., s[start..end-1]
if (s[end] == ' ') {
reverse(s, start, end);
start = end + 1;
}
}
// Reverse the last word
reverse(s, start, [Link] - 1);
// Reverse the entire String
reverse(s, 0, [Link] - 1);
return s;
}
// Driver Code
public static void main(String[] args)
{
String s = "i like this program very much
";
// Function call
char[] p = reverseWords([Link]());
[Link](p);
}}
🧵 Funtions in Java
a function is called a method(class). Methods in Java are blocks of code that perform a specific
task and can be reused throughout your program
1. No Return Type
2. Return Type
int add(int a, int b) {
return a + b;
}
int result = add(5, 3); // Calling the 'add' method with arguments 5 and 3
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
int result = [Link](5, 3); // Calling the 'add' method
[Link]("Result: " + result);
}
}
static String appDutta(String s){
[Link]("Return with Param");
return s+"Dutta";
}
static String appDutta2(){
[Link]("Return and Non Param");
return "Dutta";
}
static void print(String s){
[Link]("Non Return with Param");
[Link]("Print some"+ s);
}
static void print(){
[Link]("Non Return and Non Param");
}
Practice -
Prime Number
Swap Two Numbers
String reverse
Take User input as array
Maximum in Array
Print diagonal Elements 2D array
📗 OOPs ( Java)
1. OOPs vs POP or PPL (Procedural oriented programming)
2. Object vs Functional
PPL Details
Using the Global Struct to create a Complex Data Type and X global primitive
Struct Customer
{
Int id,
String name
String age
Int x = 99;
UpdateCustomer()
FetchCustomer()
Show() can also use the Customer and Primitive x (NO ENCAPSULATION)
Data Security issues (global, local variables)
☯️No Relation between the Struct(Global) and Functions.
How to Use Oops to Build Any Modern-Day Software
Consider this scenario: We are developing an Automation Tester Batch System.
1. Identify the objects
a. Like Student, Course, Payment.
2. Describe those with details
a. Data - Student -> name, id, age, address, email, course taken
b. Operations -> addStudent, deleteStudent
c. Bind them with Encapsulation (Class)
3. Establish the relationship with each other
a. Student -> payment, Student -> Course, Course -> Payment
4. Now implement it via Class and Objects
Abstraction Example
It is a design level concept.
Example - PC Computer
a. User
b. Service Engineer (Hide price)
Object Oriented Programming
Objects are the main building blocks of OOPS i.e your applications will be divided into
multiple objects.
A class with
o Data members
o Methods -
OOPs concepts apply now.
o o Abstraction
o o Encapsulation
o o Inheritance
o o Polymorphism
Everything in the world is an object.
Abstract class
An abstract class, on the other hand, can contain both abstract methods (methods with no
implementation) and concrete methods (methods with an implementation).
abstract class Shape {
// fields (variables) and concrete methods can be defined in an
abstract class
protected String color;
public Shape(String color) {
[Link] = color;
}
// concrete method
public String getColor() {
return [Link];
}
// 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);
[Link] = width;
[Link] = height;
}
// implementation of the abstract method defined in the superclass
@Override
public double getArea() {
return [Link] * [Link];
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius, String color) {
super(color);
[Link] = radius;
}
// implementation of the abstract method defined in the superclass
@Override
public double getArea() {
return [Link] * [Link] * [Link];
}
}
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
1. Example with Student -> Manual , Automation
2. Extra Data members, Operations or Methods
PolyMorphism
+ operator
Remote or on/off button poly behavior
Class and Objects
Inheritance
the different types of inheritance include:
1. Single Inheritance: A class inherits from a single base class.
2. Multiple Inheritance: A class inherits from multiple base classes.
3. Multilevel Inheritance: A class inherits from a derived class, forming a
hierarchy of inheritance.
4. Hierarchical Inheritance: Multiple derived classes inherit from a single
base class.
5. Hybrid Inheritance: A combination of multiple inheritance and multilevel
inheritance.
Some Questions for Revision :
Question Answer
The purpose of a programming model is to provide a systematic
approach to develop computer programs. It defines the rules,
Q1) What is the
principles, and guidelines to be followed while designing and
purpose of any
implementing software solutions. It also helps programmers to
programming model?
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
available to develop programming (OOP), functional programming (FP), event-driven
applications? programming (EDP), and aspect-oriented programming (AOP).
The main components of the Procedure Oriented Programming
Q3) What are the main model include procedures or functions, which are a set of
components of the instructions that perform a specific task, and data structures, which
Procedure Oriented are used to organize and store data. POP follows a top-down
Programming model? approach, which means the program flow starts from the main
function and then calls other functions or procedures as required.
The limitations of the Procedure Oriented Programming model
Q4) What are the
include a lack of data security, difficulty in maintaining and
limitations of the
modifying code, and low reusability of code. POP is also not suitable
Procedure Oriented
for large-scale applications as the program logic becomes complex
Programming model?
and difficult to manage.
OOPs (Object-Oriented Programming) is a programming concept that
emphasizes the use of objects, which are instances of classes, to
Q5) What is OOPs
represent real-world entities and their behavior. OOPs focuses on
concept?
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 used to define the attributes and
Q6) What are the main
behavior of objects, and objects are instances of classes that
components of Object-
represent real-world entities. Encapsulation provides data security by
Oriented Programming
hiding the implementation details of classes, while inheritance allows
model?
the creation of new classes by extending existing classes.
Polymorphism enables the use of the same code for different types
of objects.
Q7) Who is the father of Alan Kay is considered the father of OOPs, as he introduced the
OOPs? concept of object-oriented programming in the 1960s.
The major principles of Object-Oriented Programming include
inheritance, encapsulation, abstraction, and polymorphism.
Q8) What are the major Inheritance allows the creation of new classes by extending existing
principles of Object- classes, encapsulation provides data security by hiding the
Oriented Programming? implementation details of classes, abstraction allows the creation of
complex systems by hiding unnecessary details, and polymorphism
enables the use of the same code for different types of objects.
Abstraction is a programming concept that involves hiding
unnecessary details and exposing only essential information. It
Q9) What is
allows the creation of complex systems by breaking them down into
abstraction?
smaller, manageable parts. In OOPs, abstraction is achieved through
the use of abstract classes and interfaces.
Encapsulation is a programming concept that involves hiding the
implementation details of classes and exposing only their interfaces
Q10) What is
or public methods. It provides data security by preventing
encapsulation?
unauthorized access 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
inheritance?
promotes the creation of modular and scalable applications
Assignment - What happens if we do it
Class Book{
Int id;
String name;
String author;
Book s1 = new
Book();
1. JVM allocates 8 bytes for each reference variable.
2. All variables are assigned a memory.
3. Referq
Abstract classes and methods
Override the methods if the child extends the Parent or adds itself as Abstract.
No object for Abstract, only reference.
Interfaces
1. Full Abstract - no implantation of any method apart from default.
2. Public static final variables
3. Public abstract methods.
Important Class Members
1. Variables
2. Blocks
3. Constructors
4. Methods
5. Inner Class
package [Link];
public class Book {
// Instance Variables
int id; // -> Instance Primitive variable
String name; // -> Instance Reference
variable
String author;
// Block
{
[Link]("I am block");
}
// Default constructor
Book(){
[Link]("Default Con");
}
// Parameters constructor
public Book(int id, String name, String
author) {
[Link] = id;
[Link] = name;
[Link] = author;
}
// Method
void show(){
[Link]("Data");
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
'}';
}
// Inner Classe
class Publisher{
String name;
void show(){
[Link]([Link]);
}
}
Type of Variables
1. Instance Variable
a. Primitive variable
b. Reference variable
2. Local Variables
3. Static Variables
package
[Link];
public class StaticDemo {
int a = 10;
static int b= 20;
void m1(){
[Link](a);
[Link](b);
}
static void m2(){
//[Link](a);
[Link](b);
}
}
Static members can be accessed with Class Name.
Instance members can’t be accessed with class Name.
package [Link];
public class Main {
public static void main(String[]
args) {
StaticDemo.m2(); // How?
}
}
Class Loaders
Moving the file from src file to memory
Class loaders are responsible for loading Java classes dynamically to the JVM (Java Virtual
Machine) during runtime.
Encapsulation
Refers to the bundling of data and methods that operate on that data within a single unit,
or object.
Encapsulation helps to promote the principle of "data hiding".
This is achieved by declaring the object's data fields as private and providing public
getter and setter methods to access and modify the data.
public class Student {
// data fields are private
private String name;
private int age;
private String address;
// public getter and setter methods for each
field
public String getName() {
return [Link];
}
public void setName(String name) {
[Link] = name;
}
public int getAge() {
return [Link];
}
public void setAge(int age) {
[Link] = age;
}
public String getAddress() {
return [Link];
}
public void setAddress(String address) {
[Link] = address;
}
}
Access Modifier
Access modifiers in Java:
Polymorphism
Abstraction
Abstract classes and methods
In Java Abstract is the keyword.
Remember, abstract can be a class or method both.
If the class doesn’t have any abstract method, then it is a concrete class.
Abstract class cannot be final.
An abstract class cannot be instantiated i.e. one cannot create an object of an abstract
class.
Although it is not required, an abstract class may have the declaration of one or more
abstract methods.
Since the body of an abstract method cannot be implemented in an abstract class.
Non-abstract/normal methods can be implemented in an abstract class.
To use an abstract class it needs to be inherited from.
The class which inherits from the abstract class must implement all the abstract methods
declared in the parent abstract class.
An abstract class can have everything else as same as a normal Java class has i.e.
constructor, static variables and methods.
You cannot use the following modifier with abstract methods:
Private, static, final, strictfp, synchronized, native.
Interface
1. Interface variables will be inherited to subclasses.
2. interface is a keyword which is used to define User Defined Datatypes.
3. Interfaces can be used to achieve multiple inheritance in Java.
4. One interface can extend one or more interfaces.
5. One class can implement one or more interfaces.
6. Interface can contain the following members:
a. public final static variables
b. public abstract methods
c. public static inner classes
7. Variables declared in the interface are by default public final and static.
8. Methods declared in the interface are by default public and abstract.
Default Methods in interfaces
Default methods are methods that can have a body.
They provide additional functionality to a given type without breaking down the
implementing classes.
If a new method was introduced in an interface then all the implementing classes used to
break.
default return type name ()
{}
Solve the Diamond problem by [Link]
Static methods in interfaces
static methods in interfaces are similar to default methods but the only difference is that you
can’t override them.
Problem to discuss to check Interface
interface I1{}
interface I2{}
class A{}
class B{}
class Test1 extends A{ } //0K
class Test2 extends A,B{ } //Not OK
class Test3 implements I1{ }//0K
class Test4 implements I1,I2{ }//0K
class Test5 extends A implements
I1,I2{ }//OK
class Test6 implements I1 extends A{ } /
/Not OK
interface I3 extends A{}
interface I4 implements A{}
interface I5 extends A,B{}
interface I6 extends I1,I2{ }
✅ Problem Statement
Book class which has an abstract method getDetails(),name, author, price.
PrintMyBook class that inherits from the Book class.
asbtract
Book myBook = new PrintMyBook("Harry Potter", "J.k. Rowling", "120");
// Output
"Harry Potter, J.k. Rowling, 100"
Nested Class
Class within Class is called Nested class
class OuterClass
{
...
class NestedClass
{
...
}
}
Static Nested Class
Only a static member of the outer class can be accessed directly.
Inside static nested class, static members can be declared.
class OO{
static int o =100;
int a = 900;
static class SNCI{
void show(){
[Link](o);
//Only a static member of outer class can be accessed directly.
// [Link](a);
}
}
}
public class SNC {
public static void main(String[] args) {
[Link] oo = new [Link]();
[Link]();
}
}
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
[Link] io2 = new Outer().new Inner();
4. Static declaration is not allowed in the inner class
5. Static Inner class, Instance Inner class, Local Inner class, Anonymous inner class
There are 4 ways you can create a Class
1. Inner Class
2. Method Level Inner Class
3. Nested Class
4. Anonymous Class
public class Car {
// outer class field
private String make;
private String model;
// inner class
public class Engine {
// inner class fields
private int horsepower;
private String fuelType;
// inner class constructor
public Engine(int horsepower, String
fuelType) {
[Link] = horsepower;
[Link] = fuelType;
}
// inner class method
public void start() {
[Link]("Engine starting...");
}
}
// outer class constructor
public Car(String make, String model) {
[Link] = make;
[Link] = model;
}
// outer class method
public void drive() {
[Link]("Driving the car...");
}
}
//
Car myCar = new Car("Toyota", "Camry");
[Link] engine = [Link] Engine(200,
"Gasoline");
[Link]();
Upcasting and Downcasting in Class
You can assign a subclass object to the super type reference variable directly. This process is
called UPCASTING.
class Parent{}
class Child extends Parent{}
Parent parent = new Parent(); /
/ p1
Child child = new Child();
parent=child;
// Valid -> Upcasting
class Hello{}
class Child extends Hello{}
Hello hello = new Child();
Child hai=hello; // Invalid
Child hai= (Child)hello; // Valid -
>Downcasting
Anonymous Inner class
It is an inner class without a name and for which only a single object is created.
An anonymous inner class can be useful when making an instance of an object with certain
“extras” such as overriding methods of a class or interface, without having to actually subclass a
class.
Test t = new Test()
{
// data members and methods
public void test_method()
{
........
........
}
}
An anonymous class has access to the members of its enclosing class.
An anonymous class cannot access local variables in its enclosing scope that are not
declared as final or effectively final.
constructors can not be declared in an anonymous class.
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 [Link];
public class Anony02 {
public static void main(String[] args) {
// MyStudent myStudent = new MyStudent();
// [Link]();
Student student = new Student() {
@Override
public void setId() {
[Link](id);
}
};
[Link]();
}
}
interface Student{
int id = 11;
void setId();
}
class MyStudent implements Student{
@Override
public void setId() {
[Link](id);
}
}
Wrapper Classes
A Wrapper class is a class whose object wraps or contains primitive data types.
They convert primitive data types into objects.
Data structures in the Collection framework, such as ArrayList and Vector, store only
objects (reference types) and not primitive types.
An object is needed to support synchronization in multithreading.
Primitive -> Wrapper , Primitive -> String ,Wrapper -> Primitive
1. Primitive to String
1. Using valueOf()
2. toString() of wrapper
2. String to Primitive
a. A) using parseXO;
3. Primitive to Wrapper Object
a. A) Using Constructor of Wrapper class
b. B) Using valueOf method of Wrapper class
4. Wrapper Object to Primitive
a. A) Using xxValue0 method of Wrapper classes
5. String to Wrapper Object
a. A) Using constructor of Wrapper classes
b. B) Using valueOf method of Wrapper classes
6. Wrapper Object to String
a. A) Using toString( method
Comparison of Autoboxed Integer
Integer x = 400, y = 400;
if (x == y)
[Link]("Same");
else
[Link]("Not Same");
// Les than 127
Integer x = 40, y = 40;
if (x == y)
[Link]("Same");
else
[Link]("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)
[Link]("Same");
else
[Link]("Not Same");
Integer X = new Integer(10);
Integer Y = 10;
// Due to auto-boxing, a new Wrapper object
// is created which is pointed by Y
[Link](X == Y);
📕 Exceptions
An exception is an event that occurs during the execution of a program that disrupts the normal
flow of instructions.
P.S. - If no exceptions are handled, control is passed to the JVM, which terminates the
program.
Exception Hierarchy
package [Link]; // 0
public class Ex01 {
// 3 PROBLEMs in this problem
public static void main(String[] args) {
String sh = args[0];
int x = [Link](sh);
int a = 10/x;
[Link](x);
[Link](a);
}
}
Solve the three problems in the above program.
1. Array.
2. Number format
3. Arithmetic.
Exception Handling in Java is a mechanism for handling runtime errors so
that the application's normal flow can be maintained.
Try and Catch
Attempt to catch the block.
When Catch will be executed
Only when an exception in public class Ex02 is raised
public static void main(String[] args) {
try {
String name = null;
[Link]();
}catch (Exception e){
[Link]();
}
[Link]("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 ?
Multiple Catch
You can catch multiple exceptions; their execution depends on the execution problem.
package [Link];
public class Ex03 {
public static void main(String[] args) {
try {
String ip = args[0];
int a = [Link](args[0]);
int b = 10 / a;
} catch (NumberFormatException exception) {
[Link]();
} catch (ArithmeticException exception) {
[Link]();
} catch (ArrayIndexOutOfBoundsException
exception) {
[Link]();
}
}
}
Matching Catch it executes
If NumberFormat -> Number Ex
If Arth - Arth
If Array -> Array
// Keep the Biggest at the last Exception E ( bigger basket)
⚠️P.S. - Please do not write anything between Try and Catch.
Please find the problem in this Code.
package [Link];
public class Ex04 {
public static void main(String[] args) {
try {
int a = [Link](args[0]);
}
catch (NumberFormatException exception) {
[Link]();
}
try {
int b = 10 / a;
}
catch (ArithmeticException exception) {
[Link]();
}
try {
String ip = args[0];
}
catch (ArrayIndexOutOfBoundsException
exception) {
[Link]();
}
}
}
Or Catch Concept
After Java 7, We can write them in OR condition with pipe char |
try {
String ip = args[0];
int a = [Link](args[0]);
int b = 10 / a;
} catch (NumberFormatException | ArithmeticException |
ArrayIndexOutOfBoundsException exception) {
[Link]();
} catch (Exception e) {
[Link]();
}
Finally Block
The finally block is a block of code that follows a try-catch block and is always executed,
regardless of whether an exception is thrown or caught. The finally block is typically used to
release resources or perform other cleanup tasks.
try {
// code that might throw an exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// code to be executed after the try-catch
block
}
public class Main {
public static void main(String[] args) {
FileInputStream file = null;
try {
file = new
FileInputStream("[Link]");
// read from the file
} catch (FileNotFoundException e) {
[Link]("File not
found!");
} finally {
[Link]();
}
}
}
If the file cannot be found, a FileNotFoundException is thrown, which is caught by the catch
block.
Regardless of whether the exception is thrown or not, the finally block is always executed, and it
closes the file.
Attempting to catch in the final is also permitted.
Yes
public static void main(String[] args) {
FileInputStream file = null;
try {
file = new FileInputStream("[Link]");
// read from the file
} catch (FileNotFoundException e) {
[Link]("File not found!");
} finally {
if (file != null) {
try {
[Link]();
} catch (IOException e) {
// handle the exception
}
}
}
}
Only in one case, If exit(0) is found, finally will not execute.
Problem 1
public class Ex06 {
public static void main(String[] args) {
ProblemF problemF = new ProblemF();
int x = [Link]();
[Link](x);
}
}
class ProblemF{
int a = 10;
int show(){
try{
[Link]("In class -> "+ a);
return a;
}catch (Exception e){
[Link]("Catch");
a = 20;
return a;
}finally {
[Link]("I am Final");
}
}}
Problem #2
package [Link];
public class Ex06 {
public static void main(String[] args) {
ProblemF problemF = new ProblemF();
int x = [Link]();
[Link](x);
}
}
class ProblemF{
int a = 10;
int show(){
try{
// a = 10/0;
[Link]("In class ->
"+ a);
return a;
}catch (Exception e){
[Link]("Catch");
a = 20;
return a;
}finally {
[Link]("I am Final");
//int[] a1 = new int[-1]; fix it
}
}
}
Problem #03
package [Link];
public class Ex08 {
public static void main(String[] args)
{
try {
int a = 10 / 10;
} catch (Exception a) {
[Link]("I am Catch
01");
} finally {
[Link]("Finally
01");
}
try {
int a = 10 / 0;
} catch (Exception a) {
[Link]("I am Catch
02");
} finally {
[Link]("Finally
02");
}
try {
int a = 10 / 0;
} catch (Exception a) {
[Link]("I am Catch
03");
[Link](-1);
} finally {
[Link]("Finally
03");
}
try {
int a = 10 / 20;
} catch (Exception a) {
[Link]("I am Catch
04");
} finally {
[Link]("Finally
04");
}
}
}
Exception Passing Methods
Navigating the Exception Flows from One Method to OTHER
package [Link];
public class Exception02 {
public static void main(String[] args) {
extracted2();
[Link]("MAIN Execute");
}
private static void extracted2() {
extracted1();
[Link]("extracted2
Execute");
}
private static void extracted1() {
extracted();
[Link]("extracted1
Execute");
}
private static void extracted() {
try {
// String name = null;
// [Link]();
Integer[] i = new Integer[2];
[Link](i[3]);
} catch (NullPointerException e) {
[Link]("Null");
[Link]();
}catch (ArrayIndexOutOfBoundsException
e) {
[Link]("Array Index
Out");
[Link]();
}catch (Exception e) {
[Link]();
}
}
}
Throw and Throws
Till Now JVM created an Exception for us.
Now We will do it
Throw exObject.
Throws Keyword at Method LEVEL
Custom Exception
"Exception" class or any of its subclasses, such as "RuntimeException". Custom exceptions
allow you to create specific types of exceptions to represent error conditions that are specific to
your application.
For example, you might create a custom exception to represent an error condition such as
"insufficient funds" in a bank account application. This allows you to handle this error condition
in a specific way, rather than using a more general exception type such as "Exception" or
"RuntimeException".
Important Points
throw new Exception();
throw new Error();
throw new Throwable();
throw new Object(); //Not Ok
catch(Exception){}
catch(Error){}
catch(Throwable){}
catch(Object){} //Not Ok
void m1() throws Exception
void m1() throws Error
void m1() throws Throwable
void m1() throws Object
//Not Ok
Some Errors Asked in the Interview :
1) NoSuchMethodError:main
(if main() method is not found upto jdk1.6.)
2) NoClassDefFoundError
(if class name is wrong while executing.)
3) StackOverflowError
In recursive method call, if memory is not available in stack.)
4) OutOfMemoryError
(While creating the object, if there is no memory in heap.)
int arr[]=new int[54453453];
5) UnsupportedClassVersionError
(If JVM version is lower then compiler version.)
6) ExceptionInInitializerError
(if exception occurs at static variable or static block while loading the class.)
static int p;
static {p=[Link]("SRI");}
}
1) ClassCastException
(If you try to convert superclass object into subclass object whitout having the ref. of
subclass.)
Object ob1 = new Object();
String st1=(String)ob1;
2) IllegalStateException
Thread t= new Thread();
[Link]();
[Link]();//Here this err will occur
3) IllegalArgumentException
[Link](30);
Thread priority must be b/w 1-10.
Try Out
package [Link];
public class Ex11 {
public static void main(String[] args) {
Hello h = new Hello();
[Link]();
[Link]("Pramod");
}
}
class Hello {
public int process() {
throw new NullPointerException();
}
}
Collection Framework
Focus on Main Business Logic rather than Low Level Logics
Problem with Arrays
Since we have to give size, memory is wasted.
Insertion and deletion are heavy.
No built-in support for sorting, searching.
We prefer below classes and Interfaces in place of Arrays.
Legacy APIs are provided
Legacy Classes
Vector
Stack
Properties
Hash table
Dictionary
Legacy Interface
Enumeration (cursor)
Enumeration
It is an interface used to get elements of legacy collections(Vector, Hashtable)
Vector access with Enumeration
Vector v - new Vector();
Enumeration e = [Link](); and hasNext functions
Collection vs Collections
Collection Framework” has been defined in JDK 1.2 which holds all the collection
classes and interfaces in it.
Collection interface ([Link]) and Map interface ([Link]) are the two
main “root” interfaces of Java collection classes.
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
[Link]
Ordered Collection
Control over the insertion
List allows Duplicate.
Way to Initialize
List<String> fruites = [Link]("orange","apple");
ArrayList - Underline Array - Get element is easy, inserting, Delete is Costly.
LinkedList - LinkedList
Vector
Most of the time, programmers prefer ArrayList over Vector because ArrayList can be
synchronized explicitly using [Link].
List Functions
Use the javap [Link]
1. public abstract int size();
2. public abstract boolean isEmpty();
3. public abstract boolean contains([Link]);
4. public abstract [Link]<E> iterator();
5. public abstract [Link][] toArray();
6. public abstract <T> T[] toArray(T[]);
7. public abstract boolean add(E);
8. public abstract boolean remove([Link]);
9. public abstract boolean containsAll([Link]<?>);
10. public abstract boolean addAll([Link]<? extends E>);
11. public abstract boolean addAll(int, [Link]<? extends E>);
12. public abstract boolean removeAll([Link]<?>);
13. public abstract boolean retainAll([Link]<?>);
14. public default void replaceAll([Link]<E>);
15. public default void sort([Link]<? super E>);
16. public abstract void clear();
17. public abstract boolean equals([Link]);
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([Link]);
24. public abstract int lastIndexOf([Link]);
25. public abstract [Link]<E> listIterator();
26. public abstract [Link]<E> listIterator(int);
27. public abstract [Link]<E> subList(int, int);
28. public default [Link]<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.
It is fast to access the elements, but slow to insert and delete the elements.
Array vs Vector
Vector
Vector allows duplicates, and it is implemented as a resizable array.
Vector is legacy class and elements will be stored internally using indexing notation.
Vector methods are synchronized, so vector objects can’t be accessed by multiple
threads at a time.
Array vs ArrayList
Array vs LinkedList
LinkedList
LinkedList allows duplicates and internally implements a doubly-linked list data structure.
LinkedList elements will be stored internally using node representation.
It is fast to insert or delete the elements, but slow for accessing the elements.
Stack
Stack is a legacy subclass of vector and its methods are synchronized, so stack objects
can’t be accessed by multiple threads at a time.
Stack has important operations like peek(), pop(), push(), search() and other operations
are same as Vector. It is a and not in use.
Task ArrayList LinkedList Vector Stack
Order User added User added User added
Duplicate Vaue Yes Yes Yes
Null Value Yes Yes Yes
Random Access Yes No Yes
Sequential Access Yes Yes Yes
Iterator (used?) Yes Yes Yes
List Iterator Yes Yes Yes
Enumeration No No Yes
Index Representation Yes No Yes
Node Representation No Yes No
DeQue API can be No Yes No
used
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.
[Link]
iterator
Iterator
used to iterate or traverse or retrieve a Collection or Stream object’s elements one by
one and called a Java Cursor is an Iterator.
three cursors in Java.
1. Iterator - For all
2. Enumeration - V
3. ListIterator - List
Methods in Iterator
Problem with Iterator
In CRUD Operations, it does NOT support CREATE and UPDATE operations.
only Forward direction.
only Sequential iteration.
ListIterator
Iterator that is used to traverse all types of lists including ArrayList, Vector, LinkedList, Stack,
etc. It is available since Java 1.2. It extends the iterator interface.
bi-directional traversal.
four CRUD operations(Create, Read, Update, Delete)
Cursor concept.
Methods in ListIterator
Iterator vs ListIterator
Spliterator
Spliterator == Splittable Iterator
it can split some source, and it can iterate it too. (2 balanced)
trySplit is for. Splitting is needed for parallel processing.
package [Link];
import [Link];
import [Link];
import [Link];
public class SpliteratorDemo {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
// Add values to the array list.
[Link](1);
[Link](2);
[Link](-3);
[Link](-4);
[Link](5);
// getting Spliterator object on al
Spliterator<Integer> splitr1 = [Link]();
// estimateSize method
[Link]("estimate size : " +
[Link]());
// getExactSizeIfKnown method
[Link]("exact size : " +
[Link]());
// Split
Spliterator<Integer> splitr1_split = [Link]();
// If splitr1 could be split, use splitr2 first.
if(splitr1_split != null) {
[Link]("Output from splitr2: ");
splitr1_split.forEachRemaining((n) ->
[Link](n));
}
// Now, use the splitr
[Link]("\nOutput from splitr1: ");
[Link]((n) -> [Link](n));
ArrayList<Integer> tempList = new ArrayList<>();
while([Link]((n) ->
[Link]([Link](n))));
Spliterator<Integer> splitr2 = [Link]();
while([Link]((n) -> [Link](n)));
}
}
ConcurrentModificationException
Can’t add to the List while iterating.
Set
Interface, [Link]
Unique Only
If [Link](o2) Only one will be in the List
Set interface has the following concrete subclasses:
o o HashSet
o o LinkedHashSet
o o TreeSet .
Check Implementation of Hash Set in Java doc
HashSet
It is fast for searching and retrieving elements.
It does not maintain any order for stored elements.> A, B, C -> B,C, A, ABC, BAC
LinkedHashSet
LinkedHashSet is a subclass of HashSet.
It stores the data in the order as added by the user. A,B,C -> ABC
TreeSet
It stores the elements in a sorted order. - 23,45,1 -> A,Z,B -> ABz, s1, s2, s3 -> It won’t
able -> [Link]
compareTo() method is used to identify the object uniquely and to manage the order 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
runtime
[Link]
TreeSet allows storing elements of similar type only.
Null value cannot be stored in TreeSet.
NavigableSet
NavigableSet is an interface added in Java 6.
It is a subtype of SortedSet.
Its functionality is almost similar to TreeSet except it provides some extra methods for
easy navigation.
Elements from NavigableSet can be accessed in both forward and reverse order.
Comparable vs Comparator
Comparable object is capable of comparing itself with another object. The class itself must
implements the [Link] interface to compare its instances.
Comparator is external to the element type we are comparing. It’s a separate class
CompareTo(??)
Compare
Queue
Added interface in Java 5.
PriorityQueue is one of the commonly used subclasses of Queue interface.
PriorityQueue doesn’t allow null values.
You can add only comparable objects to PriorityQueue
Task Hashset LinkedHashSet TreeSet
Order No User added Default sort
Order
Duplicate Vaue No No No
Null Value Yes Yes No
Synchronized No No No
Iterator (used?) Yes Yes Yes
List Iterator No No No
Enumeration No No Yes
Index Representation No No No
Node Representation No Yes No
NavigateableSet API used No No No
Serializable Yes Yes Yes
Cloneable Yes Yes Yes
Map
Map is an interface available in [Link] package and introduced in the Collection
Framework API.
a key and a value.
The key is always unique in the Map.
A Map cannot contain duplicate keys and each key can map to at most one value. Some
implementations allow null key and null values like the HashMap and LinkedHashMap,
but some do not like the TreeMap.
The order of a map depends on the specific implementations. For example, TreeMap
and LinkedHashMap have predictable orders, while HashMap does not.
There are two interfaces for implementing Map in java. They are Map and SortedMap,
and three classes: HashMap, TreeMap, and LinkedHashMap
Map hm = new HashMap();
Map interface has following concrete sub classes:
o o HashMap
o o LinkedHashMap
o o TreeMap
o o Hashtable
HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of
the Map interface of Java. It stores the data in (Key, Value) pairs.
No Duplicate Key on HashMap
LinkedHashMap is just like HashMap with an additional feature of maintaining an order of
elements inserted into it.
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.
HashTable
It is similar to HashMap, but is synchronized.
Hashtable stores key/value pairs in hash table.
In Hashtable we specify an object that is used as a key, and the value we want to
associate to that key. The key is then hashed, and the resulting hash code is used as
the index at which the value is stored within the table.
The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast
Enumeration
Sort HashMap by Keys
By using TreeMap
By using LinkedHashMap
Sort HashMap by Values
Sort HashMap by Values using Comparator Interface
Count Occurance of Character in the given String
Count Occurance of Word in the given String
What are the main differences between array and collection?
Arrays are always of fixed size, Collection, size can be changed dynamically as per
need.
Arrays can only store homogeneous or similar type objects, but in Collection,
heterogeneous objects can be stored.
Arrays cannot provide the ?ready-made? methods for user requirements as sorting,
searching, etc. but Collection includes readymade methods to use
What is the difference between Set and Map?
Set contains values only whereas Map contains key and values both.
Set contains unique values whereas Map can contain unique Keys with duplicate values.
Set holds a single number of null value whereas Map can include a single null key with n
number of null values.
What is the difference between HashMap and Hashtable?
What is the difference between Collection and Collections?
The Collection is an interface whereas Collections is a class.
The Collection interface provides the standard functionality of data structure to List, Set,
and Queue. However, Collections class is to sort and synchronize the collection
elements.
The Collection interface provides the methods that can be used for data structure
whereas Collections class provides the static methods which can be used for various
operation on a collection.
new Student(); ox2323232, Student0x23323
What does the hashCode() method?
The hashCode() method returns a hash code value (an integer number).
The hashCode() method returns the same integer number if two keys (by calling equals()
method) are identical.
However, it is possible that two hash code numbers can have different or the same keys.
If two objects do not produce an equal result by using the equals() method, then the
hashcode() method will provide the different integer result for both the objects.
.
How to synchronize List, Set and Map elements?
1. public static List synchronizedList(List l){}
2. public static Set synchronizedSet(Set s){}
3. public static SortedSet synchronizedSortedSet(SortedSet s){}
4. public static Map synchronizedMap(Map m){}
5. public static SortedMap synchronizedSortedMap(SortedMap m){}
What is the default size of load factor in hashing based collection?
The default size of load factor is 0.75. The default capacity is computed as initial capacity * load
factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
Collection Framwwork 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<>();
[Link](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<>([Link](fromIndex, toIndex));
How do you check if an element exists in an ArrayList?
Generics
Introduction to Generics, Generics Class
Implementing Generics for the Custom List
Examples
"Generics allow the reusability of code, where one single method can be used for different data-
types of variables or objects."
idea is to allow different types like Integer, String, … etc and user-defined types to be a
parameter to methods, classes, and interfaces.
MaxtTheerGeneric Demo
Multithreading
1. Multi Tasking
a. Multi Thread
b. Multi Processing
Multitasking
CPU executes multiple jobs by switching among them.
typically using a small-time quantum, and these switches occur so frequently that the
users can interact with each program while it is running.
Multi Processing:
Process is a program.
Each process is treated as a separate execution unit and is assigned to a different CPU.
o Running MS Word C#
o Running PPT
o Running Zoom
o 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,
o SP1, SP2, SP3 three sub processes each are Thread
o SP1 - Audio transfer
o SP2 - Video Recordings
o SP3 - Chat
Application level
They can share the memories
They can do it easily in threads.
Switching to control in Threads is easy. ( T1 -> T2)
Bank Application allows multiple users to login, bank balance, withdraw amount.
Multitasking vs Multithreading vs Multiprocessing
public class Task02 {
public static void main(String[] args) throws
InterruptedException {
Thread t = [Link]();
[Link](t);
for (int i = 0; i < 10; i++) {
[Link](i+" - "+[Link]());
[Link](i+" - "+[Link]());
[Link](5000);
}
}
}
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 [Link]() ( [Link]()) by JVM
13. The main thread will execute your program.
14.
15. JVM will sJVM will clear garbagehut down.
Main Thread - Main Method
There are two ways you can create the Threads in Java.
1. Extend Thread
2. Runnable
package [Link];
public class Task03 {
public static void main(String[] args) {
Worker worker = new Worker();
[Link]();
// Where is the Start ?
Worker worker2 = new Worker();
[Link]();
}
}
class Worker extends Thread{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
try {
[Link](i + " --
> ");
[Link](2000);
} catch (InterruptedException e)
{
[Link]();
}
}
}
}
Why don’t we call run() method directly, why call start() method?
We can call run() method if we want but then it would behave just like a normal method
and we would not be able to take the advantage of multithreading.
When the run method gets called though start() method then a new separate thread is
being allocated to the execution of run method, so if more than one thread calls start()
method that means their run method is being executed by separate threads (these
threads run simultaneously).
public Thread():
Creates a new Thread object. When started, then run() will be invoked from the current
object.
public Thread(String);
Creates a new Thread object by specifying the name.
public Thread(ThreadGroup, String);
Creates a new Thread object by specifying the ThreadGroup name.
public Thread(Runnable);
Creates a new Thread object. When started then run() will be invoked from specified
Runnable object.
public Thread (Runnable, String);
Creates a new Thread object by specifying the Runnable object and thread name.
public Thread(ThreadGroup, Runnable);
Creates a new Thread object by specifying the threadgroup Runnable object.
public Thread(ThreadGroup, Runnable, String);
Creates a new Thread object by specifying the ThreadGroup, Runnable object and
thread name.
Methods from ThreadGroup Class
public final String getName() Returns the name of this thread group.
public final ThreadGroup getParent() Returns the parent of this thread group
public final boolean parentOf(ThreadGroup)
Tests if this thread group is either the thread group argument or parent of that thread
group
public final int getMaxPriority() Returns the maximum priority of this thread group.
public final void setMaxPriority(int) Sets the maximum priority of the group.
public final boolean isDaemon() Tests if this thread group is a daemon thread group.
public final void setDaemon(boolean) Changes the daemon status of this thread group.
public synchronized boolean isDestroyed()
Tests if this thread group has been destroyed.
public int activeCount() Returns an estimate of the number of active threads in
this thread group and its subgroups.
public final void stop() Stops this thread group.
Constants from Thread Class
static final int MIN_PRIORITY Constant represents minimum priority of a thread
static final int NORM_PRIORITY Constant represents normal priority of a thread
static final int MAX_PRIORITY Constant represents maximum priority of a thread
Methods from Thread Class
Concurrency vs Parallelism
Concurrency refers to the ability of a system to handle multiple tasks or threads at the same
time, allowing them to be executed independently and asynchronously.
Concurrency enables a system to perform multiple tasks simultaneously, but it does not
necessarily mean that the tasks are executed simultaneously.
For example, a web server can handle multiple client requests concurrently, but each
request is handled by a single thread and the server may not be able to process all the requests
at the same time.
Parallelism refers to the ability of a system to execute multiple tasks or threads simultaneously,
using multiple cores or processors.
Parallelism enables a system to perform multiple tasks at the same time, rather than one at a
time.
For example, a parallel program can use multiple cores or processors to perform a large
computation in less time.
In summary, concurrency enables a program to handle multiple tasks at the same time,
but it does not necessarily mean that the tasks are executed simultaneously.
Parallelism enables a program to execute multiple tasks simultaneously, using multiple cores or
processors.
Synchronous vs Asynchronous
Synchronous operations block the execution of the program or system until the operation is
completed.
This means that the program or system will not execute any other code or perform any other
tasks until the current task is completed.
This can lead to a situation where the program or system is "stuck" waiting for an operation to
complete, and this can make the program or system unresponsive or slow.
Asynchronous operations, on the other hand, do not block the execution of the program or
system.
The program or system can continue to execute other code or perform other tasks while an
asynchronous operation is in progress.
This can make the program or system more responsive and efficient, because it can perform
multiple tasks at the same time.
In summary, synchronous operations block the execution of a program or system until the
operation is completed, while asynchronous operations do not block the execution and allow the
program or system to continue running while the operation is in progress.
Thread Priority
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 ( [Link]() ) , T1, T2.
3. Initial state will be ready TO Run (waiting for CPU).
4. Thread scheduler selects the t1
New - Instance of thread created which is not yet started by invoking start() it will be.
Runnable - After Invocation of start() and before it is selected to be run by the scheduler.
Running - After the thread scheduler has selected it.
Non-runnable - Thread alive, not eligible to run.
Terminated - run() method has exited.
Synchronization
Lock on an Object.
Withdraw example for the Synchronization
Method Level Synchronization
Applying synchronized keyword to the method is called Method Level Synchronization.
You can apply synchronized keyword for both instance methods and static methods.
When instance method is synchronized then the object which is used to invoke the
synchronized method will be locked by the current thread.
When static method is synchronized then the default object of the invoking class will be
locked by the current thread.
public synchronized void show()
{ ... }
Block Level Synchronization
Applying synchronized keywords for local blocks is called as Block Level
Synchronization.
You must specify some object as a parameter to synchronized block.
When a local block is synchronized, then the object which you are passing as a
parameter to the synchronized block will be locked by the current thread.
class Pramod{
ArrayList al = new ArrayList();
void show(){ ...
synchronized(al){ ... } ...
}
}
Important points for the Synchronization
Case 1
Case 2
Case 3
Case 4
Case 5
Case 6
Deadlocks
Solution in [Link] (or Github URL)
package [Link];
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() {
synchronized (resource1) {
[Link]("Thread 1: locked resource
1");
try {
[Link](100);
} catch (Exception e) {
}
synchronized (resource2) {
[Link]("Thread 1: locked
resource 2");
}
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
[Link]("Thread 2: locked resource
2");
try {
[Link](100);
} catch (Exception e) {
}
synchronized (resource1) {
[Link]("Thread 2: locked
resource 1");
}
}
}
};
[Link]();
[Link]();
}
}
Wait.
wait() method is an instance method available in [Link] class.
When you call wait() method on any locked object then lock of that object will be
released
immediately and the current thread will be moved to WAIT state.
Following are the wait() methods defined in Object class:
o o public final void wait()
o o public final native void wait(long ms)
o o public final void wait(long ms, int ns)
If you call wait() method on unlocked object then [Link]
will be thrown at runtime
package [Link];
public class WaitDemo {
public static void main(String[] args) {
WaitForMe waitForMe = new WaitForMe();
CustomThread customThread = new CustomThread(waitForMe, "A");
CustomThread customThread2 = new CustomThread(waitForMe,
"B");
[Link]();
[Link]();
}
}
class WaitForMe {
// synchronized void show(){
synchronized void show() {
Thread thread = [Link]();
for (int i = 0; i < 5; i++) {
[Link](" Name -> " + [Link]() + " ->
" + i);
try {
[Link](1000);
} catch (Exception e) {
[Link]();
}
}
}
// Blocking a Block or Third Party Object
// void show() {
// Thread th = [Link]();
// ArrayList al = new ArrayList();
// synchronized (al) {
// for (int i = 1; i <= 5; i++) {
// [Link]([Link]() + " - show -" + i);
// try {
////[Link](1000);
// [Link](1000);
// } catch (Exception ex) {
// [Link](ex);
// }
// }
// }
// }
}
class CustomThread extends Thread {
WaitForMe wait;
public CustomThread(WaitForMe wait, String name) {
super(name);
[Link] = wait;
}
@Override
public void run() {
[Link]();
}
}
Notify & NotifyAll()
These methods are instance methods available in [Link] class.
When you call notify() method on any locked object then following task will happen:
o Only one thread which has been waiting for long time will be picked.
o Checks whether the resources released by the thread are available or not.
o If resources are available, then the thread acquires the resources and goes to
READY TO RUN state.
o 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:
o All or some required number of threads as per the requirement which are in
WAIT state will be picked.
o Checks whether the resources released are available or not.
o If resources are available then the threads acquire the resources and goes to
READY TO RUN state.
o If resources are not available then the threads go to BLOCKED state.
Code sample at [Link]
Join()
This method will be used to join one thread at the end of another thread.
In Main thread -> [Link]()
o Main thread will be joined at the end of t1.
In t1 thread -> [Link]()
o t1 thread will be joined at the end of t2.
Thread Pool
A thread pool in Java is a collection of worker threads that are used to execute multiple
tasks concurrently.
The main advantage of using a thread pool is that it allows the program to reuse threads,
which can improve performance and reduce the overhead of creating and destroying
threads.
In a thread pool, a fixed number of worker threads are created and are managed by a
thread pool executor. When a task is submitted to the thread pool, it is placed in a task
queue and is executed by an available worker thread. Once a task is completed, the
worker thread is returned to the thread pool and is available for executing another task.
Java provides the Executor framework, which simplifies the task of creating and
managing thread pools. The Executor interface has a single execute() method, which is
used to submit tasks to the thread pool
Executor executor =
[Link](5);
[Link](new RunnableTask());
Thread Local
ThreadLocal is a class in the Java standard library that allows you to create variables that are
specific to a single thread. These variables are called "thread-local" variables, because they are
local to the thread that accesses them.
Instance variables are more prone to the Thread Safty, Local variables are always safe.
class MyThreadLocal {
private static ThreadLocal<Integer> myThreadLocal = new
ThreadLocal<>();
public static void set(Integer value) {
[Link](value);
}
public static Integer get() {
return [Link]();
}
}
[Link](10);
[Link]([Link]());
// 10
It's important to note that each thread will have its own copy of the thread-local variable, so the
value of the thread-local variable set by one thread will not affect the value of the thread-local
variable in another thread.
For example, ThreadLocal can be used to store a user's session information in a web
application, where each user's session information is specific to the thread that is handling the
user's request.
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.
In this example, the finalize() method is used to delete a file when the MyResource object is
eligible for garbage collection.
However, it's important to note that the finalize() method is not guaranteed to be run before an
object is garbage collected, and it's not guaranteed to be run at all.
So, it's not recommended to rely on finalize() method to release resources, instead use try-
catch-finally or try-with-resources statements to release resources and also use explicit
methods like close() to release resources.
it's not recommended to use finalize() method for critical tasks, because it's not
guaranteed to be run and it might cause performance issues.
Can I overload the run() method in thread class?
Overloading of run() method is possible
Can I define the run() method as synchronized?
Yes, we can synchronize a run() method in Java, but it is not required because this method has
been executed by a single thread only.
Can I define a thread class without overriding the run () method?
If we don't override run() method, compiler will not flash any error and it will execute run()
method of Thread class that has empty implemented, So, there will be no output for this thread.
How do I pause thread execution for specified amount of time?
sleep() method can be used to pause the execution of the current thread for a specified time in
milliseconds.
What is the difference between sleep() and wait() method?
Wait() method releases lock during Synchronization. Sleep() method does not release the lock
on object during Synchronization.
What is daemon thread?
Daemon thread in Java is a low-priority thread that runs in the background to perform tasks
such as garbage collection.
public final void setDaemon(boolean on)
What is race condition in Java?
A condition in which the critical section (a part of the program where shared memory is
accessed) is concurrently executed by two or more threads.