You are on page 1of 198

JAVA

WHAT IS JAVA?
JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation.
It was developed by James Gosling and Patrick Naughton.

It is a simple programming language. Writing, compiling and debugging a program is easy in


java. It helps to create modular programsand reusable code.
WHY JAVA
Platform Independence :
Java is designed to be platform-independent, allowing developers to write code once and
run it anywhere (WORA).

Object-Oriented :
Java is an object-oriented programming language, promoting modular and reusable code
structures.

Robust and Secure :


Java's strong memory management and built-in security features contribute to robust and
secure applications.

Community Support::
Java has a large and active community, providing extensive libraries, frameworks, and
resources for developers.
WHEN TO USE JAVA?
Enterprise Applications: Java is commonly used for developing large-scale enterprise
applications.

Web Development: Java is used for server-side development in web applications.

Mobile Applications: Android applications are often developed using Java.

Big Data: Java is used in big data processing frameworks like Apache Hadoop.
WHERE IS JAVA USED?
Web Development: Java is widely used for server-side development in web applications.

Mobile Development: Android applications are primarily written in Java.

Enterprise Systems: Java is extensively used in building large-scale enterprise applications.

Cloud Computing: Many cloud-based services and platforms use Java.


PHASES OF A JAVA PROGRAM

Edit : - Write the Java source code using a text editor or an integrated development
environment (IDE).

Compile : - Use the javac compiler to convert the source code into bytecode.

Load : - The class loader loads the bytecode into memory.

Verify: - The bytecode verifier checks the code for integrity and security.

Execute : -The Java Virtual Machine (JVM) executes the bytecode.

Unload : - When the program finishes, the class unloader unloads the classes from
memory.
JAVAVIRTUAL MACHINE (JVM)
This is generally referred as JVM. Before, we discuss about JVM lets see the phases of
program execution. Phases are as follows: we write the program, then we compile the
program and at last we run the program.

Writing of the program is of course done by java programmer like you and me.

Compilation of program is done by javac compiler, javac is the primary java compiler
included in java development kit (JDK). It takes java program as input and generates java
bytecode as output.

In third phase, JVM executes the bytecode generated by compiler. This is called program
run phase.

The JVM is the runtime engine that executes Java bytecode. It provides platform
independence and memory management.
BYTECODE
java compiler of JDK compiles the java source code
into bytecode so that it can be executed by JVM. The
bytecode is saved in a.class file by compiler
JAVA DEVELOPMENT KIT (JDK)
While explaining JVM and bytecode, I
have used the term JDK.

Let's discuss about it. As the name


suggests this is complete java
development kit that

It includes JRE (Java Runtime


Environment), compilers and various
tools like JavaDoc, Java debugger etc.

In order to create, compile and run Java


program you would need JDK installed
on your computer.
JAVA RUNTIME ENVIRONMENT (JRE)
JRE is a part of JDK which means that
JDK includes JRE.

When you have JRE installed on your


system, you can run a java program
however you won't be able to compile it.

JRE includes JVM, browser plugins and


applets support. When you only need to
run a java program on your computer,
you would only need JRE.

JIT is a technique used by the JVM to


improve performance by dynamically
compiling Java bytecode into native
machine code.
10
JAVA FEATURES
Platform Independent

Compiler(javac) converts source code (.java file) to the byte code(.class file). As mentioned
above, JVM executes the bytecode produced by compiler. This byte code can run on any
platform such as Windows, Linux, Mac OS etc.

Which means a program that is compiled on windows can run on Linux and vice- versa.

Each operating system has different JVM, however the output they produce after execution
of bytecode is same across all operating systems. That is why we call java as platform
independent language

Object Oriented - follows principle of OOPs


(Abstraction,Encapsulation,Inheritance,Polymorphism)

Memory Management - automatic memory management through garbage collector,reducing


risk of memory leaks and improving application performance.
JAVA FEATURES
Secure
We don't have pointers and we cannot access out of bound arrays (you
ArrayIndexOutOfBoundsException if you try to do so) in java. That's why several security flaws like
stack get corruption or buffer overflow is impossible to exploit in Java.
Multithreading
Java supports multithreading. Multithreading is a Java feature that allows concurrent execution of
two or more parts of a program for maximum utilisation of CPU
Portable
As discussed, java code that is written on one machine can run on another machine. The platform
independent byte code can be carried to any platform for execution that makes java code portable
Strong Typing
Java is statically-typed language meaning variable types are explicitly declared compile time. This
helps catch type-related errors early in the development process.
JAVA FEATURES
Simple Language : Java is considered as one of simple language because it does not have
complex features like Operator overloading, Multiple inheritance, pointers and Explicit
memory allocation.

Robust Language : Robust means reliable, Java programming language is developed in a


way that puts a lot of emphasis on early checking for possible errors, that's why java
compiler is able to detect errors that are not easy to detect in other programming languages.
The main features of java that makes it robust are garbage collection, Exception Handling
and memory allocation.

Distributed : Using java programming language we can create distributed applications.


RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating
distributed applications in java.

In simple words: The java programs can be distributed on more than one systems that are
connected to each other using internet connection. Objects on one JVM (java virtual
machine) can execute procedures on a remote JVM
13
KEYWORDS IN JAVA
1. Abstract
Specifies that a class or method will be implemented later, in a subclass
2. Assert
Assert describes a predicate placed in a java program to indicate that the developer thinks that
the predicate is always true at that place.
3. Boolean
A data type that can hold True and False values only.
4. Break
A control statement for breaking out of loops.
KEYWORDS
5. Byte

A data type that can hold 8-bit data valu

6. Char

A data type that can hold unsigned 16-bit Unicode characters

7. Class

Declares a new class

8. Continue

A control statement for breaking out of loops


KEYWORDS
9. Do

<<< Swipe

Starts a do-while loop.

10. Double

A data type that can hold 64-bit floating- point numbers

11. Else

Indicates alternative branches in an if statement

12. For

Used to start a for loop

13. Enum

A Java keyword is used to declare an enumerated type. Enumerations extend the base class.
KEYWORDS
14. Import

Used to import the modules.

15. Extends

Indicates that a class is derived from another class or interface.

16. Final

Indicates that a variable holds a constant value or that a method will not be overridden.

17. Finally

Indicates a block of code in a try- catch structure that will always be executed

18. Float

A data type that holds a 32-bit floating-point number


KEYWORDS
19. If
Testsa true/false expression and branches accordingly.
20. Implements
Specifies that a class implements an interface
21. Interfaceof
Indicates whether an object is an instance of a specific class or implements an interface
22. Int
A data type that can hold a 32-bit signed integer.
23. Interface
Declares an interface
KEYWORDS
24. Long

<<< Swipe

A data type that holds a 64-bit integer.

25. Native

Specifies that a method is implemented with native (platform- specific) code

26. New

Creates new objects

27. Null

This indicates that a reference does not refer to anything.

28. Package - Declares a Java package


KEYWORD
29. Return

Sends control and possibly a return value back from a called method.

30. Short

A data type that can hold a 16-bit integer

31. Switch

A statement that executes code based on a test value

32. This

Refers to the current object in a method or constructor


DATATYPES
Data types specify the different sizes and values
that can be stored in the variable. There are two types
of data types in Jav½±:

1. Primitive data types: The primitive data types


include boolean, char, byte, short, int, long, float and
double.

2. Non-primitive data types: The non primitive data


types include Classes, Interfaces and Arrays
Primitive Data Types
In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and double.

• byte, short, int and long data types are used for storing whole numbers.

• float and double are used for fractional numbers.

• char is used for storing characters (letters).

• boolean data type is used for variables that holds either true or false
Data types in Java with default value table
NON-PRIMITIVE DATATYPES
Non-primitive data types are called reference types because they refer to objects.
VARIABLES IN JAVA
What is Variable?
A variable is a name given to the initial memmory address, which is associated with a value that can be
changed.
For example when I write
int i=10;
here variable name is i which is associated with value 10, int is a data type that represents that this
variable can hold integer values.
Declare a Variable
To declare a variable, follow this syntax:
data_type variable_name = value;
here value is optional. because in java, you can declare the variable first and then later assign the
value to it.
Example: int a;
VARIABLES NAMING CONVERSATION

A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and two special
characters such as underscore and $ dollar sign.
The first character must not be a digit.
Blank spaces cannot be used in variable names.
Java keywords cannot be used as variable names.
Variable names are case-sensitive.
There is no limit on the length of a variable name but by convention, it should be between 4 to 15
chars.
Types of Variable
1. Local variable
2. Instance variable
3. Static variable
LOCAL VARIABLE:
A variable declared inside the body of the method is called local variable.
Youcan use this variable only within that method and the other methods in the class aren't even aware
that the variable exists
A local variable cannot be defined with static keyword. X
INSTANCEVARIABLE
A variable declared inside the class but outside the body of the method, is called an instance variable.
Its value is instance-specific and is not shared among instances.
It is not declared as static.
STATICVARIABLE
A variable that is declared as static is called a static variable.
Youcan create a single copy of the static variable and share it among all the instances of the class.
It cannot be local.
LITERALS IN JAVA
What is Literal?
A literal is a fixed value
that we assign to a variable in a Program.
int num=10; //Here value 10 is a Integer literal.
char ch = 'A'; //Here A is a char literal.
Integer literals are assigned to the variables of data type byte, short, int and long.
byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;
LITERALS IN JAVA
Float Literals
Used for data type float and double.
double num1 = 22.4;
float num2 = 22.4f;
Note: Always suffix float value with the else compiler will consider it as double.
Char and String Literal
Used for char and String type.
char ch = 'Z';
String str = "BeginnersBook"
OPERATORS IN JAVA
What is Operator?
An operator is a character or symbol that represents an action, for example + is an arithmetic operator
that represents addition.
These are used to perform specific operations.
Types of operators are discussed in next frame.
ARITHMETIC OPERATORS
Arithmetic operator are used in
mathematical expressions in the same
way that they are used in algebra.

The following table lists the arithmetic


operators.
Assume integer variable A
holds 10 and variable B holds 20, then
LOGICAL OPERATORS
Logical Operators are used
with binary variables. They are mainly used in
conditional statements and loops
for evaluating a condition.
Assume Boolean variables A
holds true and variable B holds false, then
RELATIONALOPERATORS
There are following
relational operators
supported by Java
language.
Assume variable A holds 10
and variable B holds 20,
then
BITWISE OPERATORS
Bitwise operator works on
bits and performs bit-by-bit
operation. Assume if a = 60
and b = 13;
now in binary format they
will be as follows
ASSIGNMENT
Assignment operators are
used in Java to assign
values to variables.
CONDITIONAL OPERATORS
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to
decide, which value should be assigned to the variable.
The operator is written as -
variable x = (expression)? value if true: value if false
METHODS IN JAVA
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to
decide, which value should be assigned to the variable.
The operator is written as -
variable x = (expression)? value if true: value if false
CONTROL STATEMENTSIN JAVA
if, if else statements in java
When we need to execute a set of statements based on a condition then we need to use control flow
statements.
we will see four types of if statements that you can use in java programs based on the requirement:
a) if statement
b) if-else statement
c) if-else-if statement
d) nested if statement
IF STATEMENT
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
Statement(s);
}
IF ELSE STATEMENT
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
IF ELSE IF STATEMENT
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if conditionl is true
}else if(condition2){
//code to be executed if
condition2 is true }
else if(condition3){ //code to be executed if condition is true }
else{ //code to be executed if all the conditions are false }
NESTED IF STATEMENT
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
CONTROL STATEMENTIN JAVA
Switch Case in java
Switch case statement is
used when we have number of options (or choices) and we may need to perform a different task for
each choice.
Syntax:
switch (variable or an
integer expression)
{
case constant:
//Java code
case constant:
//Java code
default://Java code
}}
POINTS TO REMEMBER
There can be one or N number of case values for a switch expression.
The case value must be of switch expression type only.
The case value must be literal or constant. It doesn't allow variables.
The case values must be unique. In case of duplicate value, it renders compile-time error.
The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
Each case statement can have a break statement which is optional. When control reaches to the
break statement, it jumps the control after the switch expression. If a break statement is not found, it
executes the next case.
The case value can have a default label which is optional.
BREAK STATEMENTIN SWITCH
Break statement is optional in switch case but you would use it almost every time you deal with
switch case.
When to use Break statement
Break statements are used when you want your program-flow to come out of the switch body.
Whenever a break statement is encountered in the switch body,the execution flow would
directly come out of the switch, ignoring rest of the cases

Syntax with break


switch(expression) {
case x: // code block break;
case y: // code block break;
Default: // code block
}
BREAK STATEMENTIN SWITCH
INCREAMENT AND DECREAMENT OPERATOR
++ (Increment)
Increases the value of operand by 1.
A + B will give 30
A-B will give -10
AB will give 200
B/A will give 2
B % A will give 0
- -(Decrement)
Decreases the value of operand by 1.
B++
gives 21
B -- gives 19
LOOPS IN JAVA
Loops are a fundamental concept in programming..
Let's took some real life example
Consider your daily routine
Youwake up
You brush
Youwear clothes
Head off to work
Come back
Eat
Sleep Off
LOOPS IN JAVA
Again the next day, you do the same things in the same order
This cycle keeps on repeating. This concept of repetitive actions performed time and again is
called a loop
In this post, we will learn about the loops in java.
Definition
Looping in Java is defined as performing some lines of code in an ordered fashion until a condition is
false.
There are three types of loops
1. For loop
2. While loop
3. Do-While loop
FOR LOOP
The for statement consumes the initialization, condition and increment/
decrement in one line thereby providing a shorter, easy to debug structure of
looping.
We have to initialize the loop counter to some value. for e.g. int i=1;
In this expression, we have to test the condition for e.g. i <= 10

for (initialization; test condition; inc/dec)


{
// body of the loop
// statements we want to execute
}
this expression increments/decrements the loop variable for e.g. i++;
WHILE LOOP
While loop
The while loop is considered as a repeating if statement. If the number of
iterations is not fixed, it is recommended to use the while loop.
If the condition evaluates to true then we will execute the body of the loop for
e.g. i <= 10

while (test_expression){
// statements
update_expression;
}
this expression increments/decrements the loop variable for e.g. i++;
DO-WHILE LOOP
The Java do-while loop is used to iterate a part of the program repeatedly, until the
specified condition is true. If the number of iteration is not fixed and you must
have to execute the loop at least once, it is recommended to use a do-while loop.
do statement while(boolean-expression);

do {
statement(s)
} while(boolean-expression);
BREAK & CONTINUE IN JAVA
Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the program
control resumes at the next statement following the loop.
Syntax : break;
The Java break statement is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Continue Statement
The continue statement is used in loop control structure when you need to jump to the next iteration of the
loop immediately. It can be used with for loop. or while loop.
Syntax : continue;
The Java continue statement is used to continue the loop. It continues the current flow of the program and
skips the remaining code at the specified condition. In case of an inner loop,it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop
CLASSES & OBJECTS IN JAVA
Java is an Object-Oriented Programming
language..
Everything in Java is associated with classes
and objects, along with its attributes and
methods.
What is class?
A class is a logical template to create the
objects that share common properties and
methods.
What is Object?
An object is an instance of a class. An entity
that has state and behavior.
CLASS CREATEAND OBJECT CREATE
Create a class
public class Student
{
String name; int age; int
Classs;
}
Create an object
Student S1 = new Student();
OBJECT & CLASS CHARACTERISTIC
Object has three characteristics
State: Represents the data
Behavior: Represents the functionality
Identity: Identify each object uniquely
Class can contain
Fields
Methods
Constructors
Blocks
Nested class and interface
JAVA PACKAGES
A package in Java is used to group related classes. Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a better maintainable code.
Real life example
We pack in daily life. I put a certain category of products in a box. For example; Winter clothes
somewhere, summer somewhere, and so on. [ summer, Winter, Rainy ]
Real life example
Or consider scenario like this: I put all clothes in same box winter, summer, spring clothes.
In this case, things get mixed up, right? I would have a hard time finding what I am looking for..
Summer+Winter+Rainy
TYPES OF PACKAGES
The Java API is a library of prewritten classes that are free to use, included in the Java
Development Environment. Packages are divided into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own packages)
BUILT-INPACKAGE
These packages consist of a large number of classes which are a part of Java API. Here are
some of the commonly used built-in packages:

java.lang

java.io

java.util

java.applet

java.awt

java.net
BUILT-INPACKAGE
First Statement is used to import Scanner class from util package

// import the Scanner class from util package. import java.util.Scanner;

// import all the classes from util package import java.util.*;

Second statement imports all the classes from util package


USER-DEFINED PACKAGE
These are the packages that are defined by the user
First we create a directory myMathPackage (name should be same as the name of the package).
package myMathPackage;
public class fourTransaction{
public int divide (int s1, int s2)
{
return s1/s2;
}}
First we create a directory myMathPackage (name should be same as the name of the package).
CONSTRUCTOR IN JAVA
constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created.

Syntax:
class ClassName {
public ClassName() {
}}
Need of Constructor
Constructors are used to assign values to the class variables at the time of object creation, either
explicitly done by the programmer or by Java itself (default constructor).

Does Constructor return any value?


There are no "return value" statements in constructor, but constructor returns current class
instance. We can write 'return' inside a constructor.
TYPES OF CONSTRUCTORS

There are two types of constructors in Java:

Default constructor: A constructor that has no parameter is known as default constructor.


If we don't define a constructor in a class, then compiler creates default constructor(with no
arguments) for the class. Default constructor provides the default values to the object like 0,
null, etc. depending on the type.

Parameterized constructor: A constructor that has parameters is known as parameterized


constructor.
If we want to initialize fields of the class with your own values, then use a parameterized
constructor.
METHOD AND ITS TYPES
What is method?
A method is a block of code which only runs when it is called.
Youcan pass data, known as parameters into a method.

Typesof methods in java

Predefined Method:
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods.
It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any point.

User-defined Method:
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
METHOD USES,DECLARATION,PARAMETER
Uses of methods
It is used to achieve the reusability of code. We write a method once and use it many times.
We do not require to write code again and again.
It also provides the easy modification and readability of code, just by adding or removing a
chunk of code.
The method is executed only when we call or invoke it.

Method declaration
A method must be declared within a class. It is defined with the name of the method, followed
by parentheses ().

What is parameters ?
Information can be passed to methods as parameter. Parameters act as variables inside the
method.
public int skill (int a)
Parameters
Youcan add as many parameters as you want, just separate them with a comma.
METHOD DECLARATION WITH PARAMETER
METHOD CALL,NAME,RETURN TYPE
How to call a method?
Tocall a method in Java, write the method's name followed by parentheses () and a semicolon;
Skillbout();

Method name
A method can also be called multiple times.

Return type
If you want the method to return a value, you can use a primitive data type (such as int, char, etc.)
The void keyword used to indicates that the method should not return a value.
STATICKEYWORD IN JAVA
The static keyword in Java is used for memory management mainly.

We can apply static keyword with

1. Variable

2. Method

3. Block

4. Nested class
STATICVARIABLE
The static variable can be used to refer to the common property of all objects.
Cor example, the company name of employees, college name of students, etc.
The static variable gets memory only once in the class area at the time class loading.
Example of static variable
class Test{
static int a = m1(); // static variable
static { // static block
System.out.println("Inside static block");
}
static int m1() { // static method
System.out.println("from ml");
return 26;
}
public static void main(String[] args) { //main method
System.out.println("Value of a: "+a);
}
System.out.println("from main");
}}
STATICMETHOD
A static method belongs to the class ratherthanthe object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can changethevalue of it.
Example of static method
class Test {
static int a = 16;
int b = 20;
staticvoid ml() {
a = 20;
System.out.println("from ml");
b = 10;
m2();
System.out.println(super.a);
}
void m2() {// Instance method
System.out.println("from m2");
}
public staticvoid main(String[] args){
// main method
}}
STATICBLOCK
Is used to initialize the static data member.
It is executed before the main method at the time of classloading.
class Test(
// static variable
static int a = 10;
static int b;
// static block
static {
b=a4;
}
public static void main(String[] args) {
System.out.println("from main");
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}}
NESTED CLASS
A class can be made static only if it is a nested class. We cannot declare a top-level class with a static modifier but can
declare nested classes as static.
Such types of classes are called Nested static classes. Nested static class doesn't need a reference of Outer class. In
this case, a static class cannot access non-static members of the Outer class.
Example of nested class
import java.io.*;
public class GFG {
private static String str = "GeeksforGeeks";
static class MyNestedClass {
public void disp(){
System.out.println(str);
}}
public static void main(String args[]){
GFG.MyNestedClass obj
= new GFG.MyNestedClass();
}
obj.disp();
}
LIST INTERFACE IN JAVA
The List interface in Java provides a way to store the ordered collection.

It is a child interface of Collection.

The List interface is found in java.util package and inherits the Collection interface.

The implementation classes of the List interface are ArrayList, LinkedList, Stack, and Vector.
LIST IMPLEMENTATIONS
ArrayList and LinkedList are widely used in Java
programming. The Vector class is deprecated since
Java 5.
1. ADDING ELEMENTS TO LIST CLASS USING
ADD() METHOD
In order to add an element to the list, we can use the add() method. This method is
overloaded to perform multiple operations based on different parameters.

Parameters: It takes 2 parameters, namely:

add(Object): This method is used to add an element at the end of the List.

add(int index, Object): This method is used to add an element at a specific index in the List.
2. UPDATING ELEMENTS
After adding the elements, if we wish to change the element, it can be done using the set()
method.

Since List is indexed, the element which we wish to change is referenced by the index of the
element.

Therefore, this method takes an index and the updated element which needs to be inserted
at that index.
3. SEARCHING FOR ELEMENTS
Searching for elements in the List interface is a common operation in Java programming.
The List interface provides several methods to search for elements, such as the indexOf(),
lastIndexOf() methods.

Parameters:

indexOf(element): Returns the index of the first occurrence of the specified element in the
list, or -1 if the element is not found.

lastIndexOf(element): Returns the index of the last occurrence of the specified element in
the list, or -1 if the element is not found
4. REMOVING ELEMENTS
In order to remove an element from a list, we can use the remove() method. This method is
overloaded to perform multiple operations based on different parameters. They are:

remove(Object): This method is used to simply remove an object from the List. If there are
multiple such objects, then the first occurrence of the object is removed.

remove(int index): Since a List is indexed, this method takes an integer value which simply
removes the element present at that specific index in the List. After removing the element,
all the elements are moved to the left to fill the space and the indices of the objects are
updated
5. ACCESSING ELEMENTS
In order to access an element in the list, we can use the get() method, which returns the
element at the specified index

Parameters:

get(int index): This method returns the element at the specified index in the list.

[07/02, 6:35 pm] Birajdar: 6. Checking if an element is present in the list

In order to check if an element is present in the list, we can use the contains() method. This
method returns true if the specified element is present in the list, otherwise, it returns false.

Parameters:

contains(Object): This method takes a single parameter, the object to be checked if it is


present in the list.
COLLECTION FRAMEWORK IN JAVA
What is Collection?

A Collection represents a single unit of objects, i.e., a group.

What is Framework?

It provides readymade architecture. It represents a set of classes and interfaces. It is


optional.

Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
HIERARCHY OF COLLECTION FRAMEWORK
In java.util package contains all
the classes and interface for the
collection framework.
THROW AND THROWS
Java throw keyword

The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some message
with it that provides the error description. These exceptions may be related to user inputs,
server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword.

We can also define our own set of conditions and throw an exception explicitly using throw
keyword

For example, we can throw ArithmeticException if we divide a number by another number.


CODE EXAMPLE
if(age<18) {

//throw Arithmetic exception if not eligible to vote

throw new ArithmeticException("Person is not eligible to vote");

} else {

System.out.println("Person is eligible to vote!!"); |

Note: If we throw unchecked exception from a method, it is must to handle the exception or
declare in throws clause.
CHECKED EXCEPTION HANDLED BY THROWS
KEYWORD
public static void method() throws FileNotFoundException {
FileReader file = new FileReader("abc.txt");
BufferedReader fileInput = new BufferedReader (file);
//Throwing exception from the method which is handled using throws
throw new FileNotFoundException(); }
public static void main(String args[]){ //main method
try { method();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("rest of the code...");
}
JAVA THROWS KEYWORD
The Java throws keyword is used to declare an exception. It gives information to the
programmer that there may occur an exception.

So, it is better for the programmer to provide the exception handling code so that the normal flow
of the program can be maintained

Syntax : return_type method_name() throws exception_class_name{//method code }


ADVANTAGEOF THROWS KEYWORD
The Java throws keyword is used to declare an exception. It gives information to the
programmer that there may occur an exception.
So, it is better for the programmer to provide the exception handling code so that the normal flow
of the program can be maintained
Syntax : return_type method_name() throws exception_class_name{//method code }
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
class M{
void method() throws IOException{
throw new IOException("device error");
}}
TRY FINALLYBLOCK
Java finally block

Java finally block is a block used to execute important code such as closing the connection,
etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not. The finally block follows the try- catch block
WHY USE JAVA FINALLYBLOCK
finally block in Java can be used to put "cleanup" code such as closing a file, closing connection,
etc.

The important statements to be printed can be placed in the finally block.


WHY USE JAVA FINALLYBLOCK
finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
The important statements to be printed can be placed in the finally block.
Even If exception is not caught, finally block will be executed.
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0; System.out.println(data); }
//cannot handle Arithmetic type exception , //can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e); }
finally {
//executes regardless of exception occured or not System.out.println("finally block is always
executed");
}
System.out.println("rest of the code...");
TRY CATCH BLOCK
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
If an exception occurs at the particular statement in the try block, the rest of the block code will not
execute. So, it is recommended not to keep the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Syntax- try with catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax- try with finally
try{ //code that may throw an exception
}finally{ }
JAVA CATCH BLOCK
Java catch block is used to handle the Exception by declaring the type of exception within the parameter. The
declared exception must be the parent class exception (i.e., Exception) or the generated exception type.
However, the good approach is to declare the generated type of exception.
The catch block must be used after the try block only.Youcan use multiple catch block with a single try
block.
Code- with exception class
try { int data=50/0; //may throw exception
} // handling the exception by using Exception class
catch(Exception e) { System.out.println(e); }
System.out.println("rest of the code");
//Code- with specific exception class
try { int data=50/0; //may throw exception , // if exception occurs, the remaining statement will n
}
System.out.println("rest of the code"); // handling the ArithmeticException
catch(ArithmeticException e) {
System.out.println(e); }
TRY WITH MULTIPLE CATCH BLOCK
A try block can be followed by one or more catch blocks. Each catch block must contain a different
exception handler. So, if you have to perform different tasks at the occurrence of different exceptions,
use java multi-catch block.
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Code- with multiple catch block
try{ int a[]=new int[5]; a[5]=30/0; }
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}catch(Exception e) {
System.out.println("Parent Exception occurs");
} System.out.println("rest of the code");
TYPES OF EXCEPTION IN JAVA

In Java, the main class for exception


handling is Throwable Which is parent
of both Exception and Error class.
Error is a type of exception that is not
expected to be caught under normal
circumstances by your program.
So in this series, we will only discuss
Exception Class.
TYPES OF EXCEPTION
Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
CODE- WITHOUT EXCEPTION HANDLING
class Exco {
public static void main(String args[]) {
int d = 0;
int a = 42/d;
} } java.lang.ArithmeticException: / by zero at Exco.main(Exco.java:4)
When the Java runtime system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception. This causes the execution of Exc0 to stop,
because once an exception has been thrown, it must be caught by an exception handler and
dealt with immediately. In this example, we haven't supplied any exception handlers of our
own, so the exception is caught by the default handler provided by the Java runtime system
EXCEPTION HANDLING IN JAVA
Introduction
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained
What is exception?
An exception is an abnormal condition that arises in a code sequence at run time. In other
words, an exception is a runtime error.
In computer languages that do not support exception handling, errors must be checked and
handled manually- typically through the use of error codes, and so on.
A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code.
When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error.
That method may choose to handle the exception itself, or pass it on. Either way, at some
point, the exception is caught and processed.
Exceptions can be generated by the Java runtime system, or they can be manually generated
by your code.
CODE- WITH TRY-CATCHBLOCK
class Exc2 {
public static void main(String args[]) {
int d, a,
try { // monitor a block of code.
d = 0; a42/d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
} System.out.println("After catch statement.");
}}
This program generates the following output:
Division by zero.
After catch statement.
HIERARCHY OF JAVA EXCEPTION CLASSES
Syntax : try {
// block of code to monitor for errors
}catch (Exception Type 1 exOb) {
// exception handler for Exception Type1
}catch (Exception Type2exOb) {
// exception handler for Exception Type2
}finally {
// block of code to be
executed after try block ends. }
HOW GARBAGE COLLECTION WORKS IN JAVA
We will understand the working of Garbage Collector by 6
steps:
1. Object Creation
When you create objects in a Java program using the new
keyword or other means, memory is allocated on the heap
to store these objects. The heap is the region of memory
used for
dynamic allocation of objects.
Let say we created 5 object of coder class from main
method with name (cl, C2, C3, C4, C5) Coders c = new
Coders();
All 5 object will be stored in Eden space
Now let suppose 2 coders class object out of 5 are not
used anywhere. Unused object are marked as red circle
C1, C3, C5 are in use
C2, C4 not in use
2. REFERENCE TRACKING
Java uses a system of references to track
which objects are actively being used by the
program. When an object is referenced by a
variable or another object, it is considered
"reachable."
Now let suppose you want to create 2 more
coder class object.But Eden space is already
full
Now Garbage Collector will come into picture
Garbage Collector will remove the unused
object from Eden space and move the other
object from S0 area.
3. REACHABILITY ANALYSIS
Periodically,the garbage collector performs a
reachability analysis starting from a set of root
objects, such as the main method's local
variables, static fields, and references held by
active threads. The goal is to find all objects
that are reachable from the roots.
C1, C3, C5 are in use
C2, C4 not in use
4. MARKING PHASE
During reachability analysis, the garbage
collector marks objects that are reachable
from the root set as "live" or "in-use." It
traverses object graphs through references to
identify these objects.
Now let suppose you want to create 3 more
coder class object. But Eden Space is already
full
Now Garbage Collector will come into picture
Garbage Collector will remove the unused
object from Eden space and move the other
object into SO area
After the first garbage collection cycle
C1, C3, C5- moved to SO area
C6, C7, C8-newly created object in Eden space
5. SWEEPING PHASE
After marking live objects, the garbage
collector sweeps through the heap and
identifies objects that are not marked as live.
These unmarked objects are considered
garbage" because they are no longer reachable
from the root set.
6. MEMORY RECLAMATION
In this phase, the garbage collector reclaims
the memory occupied by the garbage objects.
The memory is now available for future object
allocations.
Now lets suppose - C1, C5, C6, C7 are now not
in used. Only C3, C8 are in use
Now you want to create 5 more object but
heap is full. Then Garbage Collector will start 2
cycle
After 2nd cycle
All the in used object will be moved into SI
area.
EXAMPLE OF GARBAGE COLLECTION
public class GarbageCollectionExample {
public static void main(String[] args) {
// Creating two objects
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
// Nullifying the reference to obj1
obj1 = null;

// At this point, obj1 is unreachable and can be garbage collected


// obj2 is still reachable, and its memory is not eligible for collection
// Explicitly requesting garbage collection (Note: This is just for demonstration)
System.gc();
}}

class MyClass {
// Class definition
}
HEAP
In Java, the "heap" refers to a specific region of
a computer's memory where the Java Virtual
Machine (JVM) stores objects and data
dynamically allocated during the execution of
a Java program.
This is how Heap memory internally looks
HEAP MEMORY INTERNALLYDIVIDED IN THE
TWO SECTION

YoungGeneration and Old Generation.


YoungGeneration internally divided in the two section. Survivor Space from (SO) and Survivor
To(S1)
YoungGeneration
The YoungGeneration is the portion of the heap where new objects are initially allocated (more
specific - Eden Space).
So when you create a new object with new keyword that will be store in this area.
It further divides in the 3 region. Eden Space, Survivor space (SO and S1)
"YoungGeneration is optimized for short- lived objects"
EDEN SPACE

When an object is first created, it is allocated in the Eden space.


Survivor Space
This area S0, S1 stores objects who survived after Garbage Collections in the Eden Space or
other survivor space.
The survivor spaces are used in a way that allows objects to be moved back and forth between
them to minimize fragmentation.
Old (TenuredGeneration)
The Old Generation, also known as the TenuredGeneration, is where long-lived objects are
eventually promoted after surviving multiple garbage collection cycles in the YoungGeneration
Objects in the Old Generation are typically larger and have a longer lifespan.
PERMANENT GENERATION (JAVA 7 AND EARLIER) OR
METASPACE(JAVA 8 AND LATER)

The Permanent Generation (PermGen) in Java 7 and earlier, and Metaspace in Java 8 and later,
store metadata related to classes, methods, and other classloader-related information.
In Java 8 and later, Metaspace is more flexible and dynamically managed compared to the
fixed-size PermGen.
Metaspace can automatically grow or shrink as needed, depending on the number of classes
loaded and other factors.
CODE CACHE
the code cache is a reserved area in the heap for storing compiled native code generated by the
just-in-time (jit) compiler. it is used for optimizing and executing java bytecode.
DEADLOCK IN JAVA
synchronized keyword is used to make the class or
method thread-safe which means only one thread can
have lock of synchronized method and use it, other
threads have to wait till the lock releases and anyone
of them acquire that lock.
It is important to use if our program is running in
multi-threaded environment where two or more
threads execute simultaneously. But sometimes it
also causes a problem which is called Deadlock.
Below is a simple example of Deadlock condition.
AVOID DEADLOCK CONDITION

We can avoid dead lock condition by knowing its possibilities. It's a very complex process and
not easy to catch. But still if we try, we can avoid this. There are some methods by which we can
avoid this condition. We can't completely remove its possibility but we can reduce.
Avoid Nested Locks: This is the main reason for dead lock. Dead Lock mainly happens when we
give locks to multiple threads. Avoid giving lock to multiple threads if we already have given to
one.
Avoid Unnecessary Looks: We should have lock only those members which are required.
Having lock on unnecessarily can lead to dead lock.
Using thread join: Dead lock condition appears when one thread is waiting other to finish. If this
condition occurs we can use Thread.join with maximum time you think the execution will take.
IMPORTANT POINTS

If threads are waiting for each other to finish, then the condition is known as Deadlock.
• Deadlock condition is a complex condition which occurs only in case of multiple threads.
• Deadlock condition can break our code at run time and can destroy business logic.
• We should avoid this condition as much as we can.
ASYNCHRONOUS PROGRAMMING IN JAVA
Before understanding about
Asynchronous programming, let's
understand how synchronous
programming works.
In your program, if you are fetching
some data from an API then your
program execution flow will stop
till the API returns the response,
then it will continue the execution
of rest of the program.
Asynchronous programming was
devised to accommodate for the
lag between when a function is
called to when the value of that
function is returned.
ASYNCHRONOUS PROGRAMMING IN JAVA
An asynchronous model allows
multiple things to happen at the
same time.When your program
calls a long-running function, it
doesn't block the execution flow,
and your program continues to run.
When the function finishes, the
program knows and gets access to
the result (if there's a need for
that).
ASYNCHRONOUS VS MULTITHREADING

multithreading programming is all about concurrent execution of different functions. Async


programming is about non-blocking execution between functions.
let's take an example
Async is when you say to your friend, "Yougo to the store and buy pasta. Let me know when you
get back, to make dinner together. Meanwhile, I'll prepare sauce and drinks." Threading is, "You
boil the water. I'll heat the tomato sauce. While the water is boiling, ask me and I'll put the pasta
in. When the sauce is hot, you can add cheese. When both are done, I'll sit down and you serve
dinner. Then we eat.". In the threading analogy, we can see the sequence of "When, Do" events,
which represent the sequential set of instructions per each person (thread).
GARBAGE COLLECTION IN JAVA

Background
In programming languages like C,C++ a programmer was basically responsible for allocating
and deallocating memory of objects.
As it was a manual process, many a times it use to result into memory leaks, application crash,
etc.Then came Garbage Collection.

Garbage collection (GC)


GC is a memory manager which automatically performs memory allocation and deallocation of
objects.
It frees up memory occupied by objects no longer in use, ensuring efficient memory usage and
preventing memory leaks.
FOUR COMMON GC ALGORITHMS (IN JAVA)

Serial - All GC events are executed serially with single thread to perform the clean up.
Parallel - Multi threaded where multiple GC events are executed in parallel
Concurrent Mark-Sweep (CMS) - CMS is designed to minimize pause times during garbage
collection by running most of its processes concurrently with the application threads
GI (Garbage-First) - Gl is a more recent garbage collection algorithm designed for better
performance and scalability, particularly for large heap sizes. It divides the heap into smaller,
equally-sized regions and performs garbage collection on a per-region basis.
BENEFITS OF GARBAGE COLLECTION

Prevents memory leaks


Simplifies memory management for developers
Reduces the risk of application crashes
Enhances performance by optimizing memory usage
THREAD SCHEDULER IN JAVA

A component of Java that decides which thread to run or execute and which thread to wait is
called a thread scheduler in Java.
In Java, a thread is only chosen by a thread scheduler if it is in the runnable state. However, if
there is more than one thread in the runnable state, it is up to the thread scheduler to pick one of
the threads and ignore the other ones
There are some criteria that decide which thread will execute first. There are two factors for
scheduling a thread i.e. Priority and Time of arrival.
' Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it means
that thread has got a better chance of getting picked up by the thread scheduler.
Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority
cannot be the factor to pick a thread from these two threads. In such a case, arrival time of
thread is considered by the thread scheduler. A thread that arrived first gets the preference over
the other threads.
THREAD SCHEDULER ALGORITHMS

First Come First Serve Scheduling


Time-slicing scheduling
Preemptive-Priority Scheduling

How to set a priority of a thread


Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling).
SETTER & GETTER METHOD OF THREAD PRIORITY

Let's discuss the setter and getter method of the thread priority.
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the
given thread.
public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates
or assign the priority of the thread to newPriority. The method throws IllegalArgumentException
if the value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).
3 CONSTANTS DEFINED IN THREAD CLASS:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY).
The value of MIN_PRIORITY is 1 and the value of MAX PRIORITY is 10.
HOW TO CREATE THREAD IN JAVA

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.
1. By Extending Thread Class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi tl-new Multi();
tl.start();
}
HOW TO CREATE THREAD IN JAVA

2. By implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 ml-new Multi3();
Thread t1 =new Thread(m1);//constructor->Thread(Runnable r)
tl.start();
}}
THREAD CLASS & IT'S METHOD IN JAVA

Thread Class
Thread class is the main class on which Java's Multithreading system is based. Thread class,
along with its companion interface Runnable will be used to create and run threads for utilizing
Multithreading feature of Java.
It provides constructors and methods to support multithreading. It extends object class and
implements Runnable interface.
Class signature
public class Thread extends Object implements Runnable
Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)
COMMONLYUSED METHODS OF THREAD CLASS:

public void run(): is used to perform action for a thread.


public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep (long miliseconds): Causes the currently executing thread to sleep (temporarily
cease. execution) for the specified number of milliseconds.
public void join(): waits for a thread to die.
public void join (long miliseconds): waits for a thread to die for the specified miliseconds.
public int getPriority(): returns the priority of the thread.
public int setPriority (int priority): changes the priority of the thread.
public String getName(): returns the name of the thread.
public void setName(String name): changes the name of the thread.
public Thread currentThread(): returns the reference of currently executing thread.
public int getid(): returns the id of the thread.
COMMONLYUSED METHODS OF THREAD CLASS:

public Thread.State getState(): returns the state of the thread.


public boolean is Alive(): tests if the thread is alive. public void yield(): causes the currently
executing thread object to temporarily pause and allow other threads to execute.
public void suspend(): is used to suspend the thread (depricated).
public void resume(): is used to resume the suspended thread (depricated).
public void stop(): is used to stop the thread (depricated).
public boolean isDaemon(): tests if the thread is a daemon thread.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public void interrupt(): interrupts the thread.
public boolean isinterrupted(): tests if the thread has been interrupted.
public static boolean interrupted(): tests if the current thread has been interrupted.
PROCESS VS THREAD IN JAVA

Process
When you start Chrome browser in your system. Yoursystem OS will create a process for
chrome. But there can be multiple processes for a single program.
Most people think a program and process are the same, but actually a single program can have
multiple processes.
Tofacilitate communication between processes, most operating systems support Inter Process
Communication (IPC) resources, such as pipes and sockets.
IPC is used not just for communication between processes on the same system, but processes
on different systems.
A process has a self-contained execution environment. A process generally has a complete,
private set of basic run-time resources in particular, each process has its own memory space.
Thread
All programmers are familiar with writing sequential programs. You'veprobably written a
program that displays "Hello World!" or sorts a list of names or computes a list of prime
numbers.
PROCESS VS THREAD IN JAVA
These are sequential programs. That is, each has a
beginning, an execution sequence, and an end. At any
given time during the runtime of the program, there is
a single point of execution.
A thread is similar to the sequential programs
described previously.
A single thread also has a beginning, a sequence, and
an end. At any given time during the runtime of the
thread, there is a single point of execution.
PROCESS VS THREAD IN JAVA
A Web browser is an example of a
multithreaded application. Within a typical
browser, you can scroll a page while it's
downloading an applet or an image, play
animation and sound concurrently,print a
page in the background while you download
a new page, or watch three sorting
algorithms race to the finish.
LIFE CYCLE OF A THREAD IN JAVA
Introduction
In Java, a thread always exists in any one of the
following states. These states are:
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
LIFE CYCLE OF A THREAD IN JAVA

1. Newborn State
When a thread object is created it is said to be in a new born state.
When the thread is in a new born state it is not scheduled running from this state it can be scheduled for
running by start() or killed by stop().
If put in a queue it moves to runnable state.
2. Runnable State
It means that thread is ready for execution and is waiting for the availability of the processor i.e. the
thread has joined the queue and is waiting for execution.
If all threads have equal priority,then they are given time slots for execution in round robin fashion.
The thread that relinquishes control joins the queue at the end and again waits for its turn.
A thread can relinquish the control to another before its turn comes by yield().
3. Running State
It means that the processor has given its time to the thread for execution.
The thread runs until it relinquishes control on its own or it is pre-empted by a higher priority thread.
LIFE CYCLE OF A THREAD IN JAVA

4. Blocked State
A thread can be temporarily suspended or blocked from entering into the runnable and running state by
using either of the following thread method.
1. Suspend()
2. Wait()
3. Sleep()
suspend(): Thread can be suspended by this method. It can be rescheduled by resume().
wait(): If a thread requires to wait until some event occurs, it can be done using wait method and can be
scheduled to run again by notify().
sleep(): We can put a thread to sleep for a specified time period using sleep(time) where time is in ms. It
re- enters the runnable state as soon as period has elapsed /over
5. Dead State
Whenever we want to stop a thread form running further we can call it's stop(). The statement causes
the thread to move to a dead state.
A thread will also move to dead state automatically when it reaches to end of the method.
The stop method may be used when the premature death is required.
MULTI THREADING IN JAVA
understanding Multithreading, we need to understand
what a "Thread" is.
A Process is a series of actions or steps taken in
order to achieve a particular end.
Imagine you want to cook something. Now, this
cooking can be taken as a process.
Cutting vegetables, boiling water and so on are all a
part of the process which is "cooking".
But each process requires some sub- process or you
can say sub-tasks to accomplish the full task or goal
of the process.
These sub-tasks or sub-processes are a Thread.
MULTI THREADING IN JAVA
A single thread in programming is basically a lightweight and the smallest unit of a
process.
Now that you know what thread is let's see what is multithreading.
Any application can have multiple processes (instances).
Each of these processes can be assigned either as a single thread or multiple threads
Multithreading in programming is a process of executing two or more threads
simultaneouslyto maximize the utilization of the CPU.
Multithreading is beneficial for tasks that can be performed concurrently,improving
program responsiveness and efficiency.
MULTI THREADING IN JAVA
Multithreaded applications execute two or more
threads and run concurrently (at the same time).
Hence, it is also known as Concurrency in
programming languages like Java
Each thread runs parallel to the other. Multiple
threads don't allocate separate memory areas, hence
they save memory.
ADVANTAGESOF MULTI THREADED

The users are not blocked because threads are independent, and we can perform multiple
operations at times
As such the threads are independent, the other threads won't get affected if one thread meets an
exception.
Web Server:

In a Spring Boot web application, the web server handles multiple incoming requests
simultaneously. Each incoming request is typically processed in a separate thread, allowing the
server to handle multiple clients concurrently without blocking.
Parallel Processing:

Imagine a Spring Boot application that needs to perform a complex computation or data
processing task. By dividing the task into smaller units and processing them concurrently using
threads, the application can achieve parallel processing, improving performance.
ADVANTAGESOF MULTI THREADED

Background Tasks:
Spring Boot applications often have tasks that run in the background, such as sending emails, updating
caches, or performing periodic cleanup. Using threads, you can run these tasks concurrently without
affecting the main application flow.
File Upload/Download:
When handling file uploads or downloads, multithreading can be beneficial. For instance, in a Spring
Boot application serving file downloads, each download request can be processed in a separate thread,
allowing multiple users to download files concurrently
Asynchronous Processing:
Spring Boot supports asynchronous processing, where tasks can be executed asynchronously using
threads. This is commonly used in scenarios like handling long-running operations, such as making
external API calls or processing large data sets, without blocking the main application thread.
Database Operations:
In a Spring Boot application interacting with a database, multithreading can be employed to handle
concurrent database operations. For example, multiple database queries or updates can be executed
simultaneously, improving overall database access performance.
STRING BUFFER VS STRING BUILDER

StringBuffer is present in Java.


StringBuilder was introduced in Java 5.
StringBuffer is synchronized. This means that multiple threads cannot call the methods of
StringBuffer simultaneously.
StringBuilder is asynchronized. This means that multiple threads can call the methods of
StringBuilder simultaneously.
Due to synchronization, StringBuffer is called a thread safe class.
Due to its asynchronous nature, StringBuilder is not a thread safe class.
Due to synchronization, StringBuffer is lot slower than StringBuilder.
Since there is no preliminary check for multiple threads, StringBuilder is a lot faster than
StringBuffer.
STRING METHODS IN JAVA
charAt()
It returns char value for the particular index.
Syntax:public char charAt(int index)
length()
It returns string length.
Syntax:public int length()
format()
It returns a formatted string.
Syntax:String.format();
substring()
It returns substring for given begin index.
Syntax:public String substring(int beginIndex, int endIndex)
contains()
It returns true or false after matching the sequence of char value.
Syntax:public boolean contains(CharSequence sequence)
STRING METHODS IN JAVA

join()
Iit returns a joined string.
Syntax: public static String join(CharSequence delimiter, CharSequence... elements)
equals()
It checks the equality of string with the given object.
Syntax: public boolean equals(Object anotherObject)
CompareTo(), Concat(), EndsWith(), EqualsignoreCase(), IndexOf(), IsEmpty(),
LastIndexOf(), Replace(), Split(), StartWith, ToUpperCase(), ToLowerCase(), Trim(),
valueOf() etc.
STRING IN JAVA
Java String
Generally, String is a sequence of characters But in Java, string are object that represents
a sequence of characters.
It is an object of String class.
Syntax:String txt = "skillbout";
In Java string is immutable
string references are used to store various attributes like username, password, etc.
Immutable simply means unmodifiable or unchangeable
Once string object is created its data or state can't be changed but a new string object is
created.
STRING IN JAVA
class Testimmutablestring{
public static void main(String
args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat()
method appends the string at the
end
System.out.println(s);//will print
Sachin because strings are
immutable objects
} }
JAVA STRING COMPARE
By Using equals() Method
By Using == Operator
By compareTo() Method
HOW TO CREATE STRING OBJECT?

There are two ways to create String object:


1. By string literal
2. By new keyword
1. STRING LITERAL
Java String literal is created by using
double quotes.
For Example: string s="skillbout";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the
pool, a new string instance is created and placed in the pool.
For example:
string sl="skillbout";
string s2="skillbout";//It doesn't create a new instance
Note: String objects are stored in a special memory area known as the "string constant pool".
2. BY NEW KEYWORD

//creates two objects and one reference variable String s=new String("skillbout");
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "skillbout" will be placed in the string constant pool. The variable s will refer to the object in a
heap (non-pool).
CONSTANTPOOL '
Strings that are created without using new keyword are allocated memory on this pool. Duplicates
are not allowed
NON-CONSTANTPOOL X
Strings that are created using new keyword are allocated memory on this pool. Duplicates are
allowed.
FINAL KEYWORD IN JAVA
Final keyword
The final keyword in java is used to restrict the user.
We can apply final keyword with
1. Variable
2. Method
3. class
JAVA FINAL VARIABLE
If you make any variable as final, you cannot change the value of final variable.
class Bike9{
final int speedlimit=90%;//final variable
void run(){
speedlimit=400;
}
Public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}}
JAVA FINAL METHOD
If you make any method as final, you cannot override it.
class Bike{ final void run(){System.out.println("running");} }
class Honda extends Bike{
void run(){ System.out.println("running safely with 100kmph"); }
public static void main(String args[]){
Honda honda new Honda();
honda.run();
}
}
JAVA FINAL CLASS
If you make any class as final, you cannot extend it.
final class Bike{}
class Hondal extends Bike{
void run()
{
System.out.println("running safely with 100kmph");
public static void main(String args[]){
Hondal honda= new Hondal();
honda.run();
}
}
GENERICS
Generics in Java provide a way to create classes, interfaces, and methods with
parameters that can work with any data type.
They allow you to write code that is more flexible, reusable, and type-safe. Here's
an example to illustrate the use of generics
GENERICS EXAMPLE
// Generic class with a type parameter T
class Box<T> {
private T value;
// Constructor
public Box(T value) {
this.value = value;
}
public T getValue() { // Getter
return value;
}
public void setValue(T value) { //Setter
this.value = value;
} }
public class Main {
public static void main(String[] args) {
// Creating a Box for Integer
Box<Integer> intBox = new Box<>(42);
System.out.println("Integer Value: " + intBox.getValue());
// Creating a Box for String
Box<String> strBox = new Box<>("Hello, Generics!");
System.out.println("String Value: " + strBox.getValue());
}}
OBJECT CLASS
Object class is an parent class of all class.
equals(Object obj):
Indicates whether some other object is "equal to" this one.
By default, it checks for reference equality.
hashCode():
Returns a hash code value for the object.
Used for hash-based data structures like HashMap.
toString():
Returns a string representation of the object.
By default, it returns a string consisting of the class name followed by "@" and the object's
hashcode.
OBJECT CLASS
getClass():
Returns the runtime class of an object.
Useful for obtaining information about the class.
clone():
Creates and returns a copy of this object.
The class must implement the Cloneable interface.
finalize():
Called by the garbage collector before the object is reclaimed.
Deprecated in recent Java versions. Use try-with-resources or AutoCloseable instead.
notify(), notifyAll(), wait():
Used for inter-thread communication and synchronization.
OOPS CONCEPT
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes for organizing code.
Java is an object-oriented programming language, an OOP principles play a fundamental role in Java development.
Class
A class is a blueprint or template that defines the structure and behavior of objects.
It encapsulates data (attributes) and methods (functions) that operate on the data.
object
An object is an instance of a class, representing a real-world entity.
Objects have state (attributes) and behavior (methods).
Abstraction
Abstraction is the process of simplifying complex systems by modeling classes based on their essential
properties and behaviors.
It hides the implementation details and exposes only relevant features. Abstract classes and interfaces are used to
achieve abstraction.
Abstract Class: Shape with abstract methods like draw() and calculateArea().
ENCAPSULATION

Encapsulation is the bundling of data (attributes) and methods that operate on the data within a single unit (class).
It restricts direct access to some of an object's components and can prevent unintended interference.
Encapsulation: Private attributes like accountNumber and public methods like deposit() and withdraw().
ENCAPSULATIONEXAMPLE
// Class representing a Bank Account
class BankAccount {
private String accountNumber;
private double balance;

// Constructor
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}

// Getter and Setter methods


public String getAccountNumber() {
return accountNumber;
}

public double getBalance() {


return balance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. New balance: " + balance);
} else {
System.out.println("
INHERITANCE & POLYMORPHISM
Inheritance is a mechanism that allows a new class (subclass or derived class) to inherit properties and
behavior from an existing class (superclass or base class).
It promotes code reuse, extensibility, and the creation of a hierarchy of classes.
Superclass: Vehicle Subclass: Car (inherits from Vehicle)
We will see this() and super()

POLYMORPHISM
Polymorphism allows objects are treated as instances of their parent class rather than their actual class.
It enables methods to be invoked on objects of different types, leading to flexibility and extensibility.
Twotypes of polymorphism: compile-time (method overloading) and runtime (method overriding).
Compile-time Polymorphism:
Method Overloading in a class, e.g., calculateArea(int side) and calculateArea(int length, int width).
Runtime Polymorphism:
Method Overriding in a subclass, e.g., draw() in Shape overridden in Circle and Square.
HOW DO WE IMPLEMENT ABSTRACTION
In Java, we implement abstraction using Abstract classes & Interface.
Data abstraction referes to providing only essential information about data to outside world, hiding the
background details or implementation.
In other words, Abstraction means showing essential features and hiding non-essential feature to the user.
ENCAPSULATIONVS ABSTRACTION
Encapsulation:
• It is concerned with hiding the internal details of an object.
• It provides data hiding.

Abstraction:
• It is concerned with hiding the implementation. details of a class.
• It provides a way to represent complex systems in a simplified way.
ENCAPSULATION& ABSTRACTION
Introduction:

!’ After Java 8, the interfaces can now have default methods with implementations.
!’ The interface can now have static methods with implementations.
!’ But why It's required make changes in Interface?

The Reason:

!’ Tosupport lambda functions better,the default method is introduced without breaking the existing
implementations.
!’ Toprovide backward compatibility to the Collection Framework with the new lambda functions.
!’ And, static methods are introduced to directly add the utils method in the interface without having to
create a new class.

The Real confusion


!’ Previously,Abstract classes can have implementations and after Java 8, the interfaces can also have it
now.
!’ So ain't they same now? !’ Let's find out, how they're still different.
POLYMORPHISM
Polymorphism is one of the core concepts in OOP languages and describes the concept wherein you can
use different classes with the same interface.
Each of these classes can provide its own implementation of the interface.
Typesof Polymorphism
1. Compile time Polymorphism
2. Run time Polymorphism

Compile Time Polymorphism


Youcan overload a method with different sets of parameters.
This is called static polymorphism because the compiler statically binds the method call to a specific
method.

Run Time Polymorphism


Within an inheritance hierarchy, subclass can override a method of its superclass.
If you instantiate the subclass, the JVM will always call the overridden method, even if you cast the
subclass to its superclass. That is called dynamic polymorphism.
POLYMORPHISMIN JAVA
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as
the ability of a message to be displayed in more than one form.
In school behave like a student
In home behave like a son
In bus behave like a passenger
In shopping mall behave like a customer
Real life example:
real-life example of polymorphism is a person who at the same time can have different characteristics.
In school behave like a student
In bus behave like a passenger
In home behave like a son
In shopping mall behave like a customer
Constructor:
!’ Abstract classes can have constructors.
!’ Interfaces cannot have any constructor hence we cannot write any logic on object creation.

Access Modifiers:
!’ An abstract class can declare instance variables, with all possible access, and modifiers they can be
accessed in child classes.
!’ An interface can only have public, static, and final variables and can't have any instance variables

Methods and Blocks


!’ An abstract class can declare instances and static blocks, which is not possible. with interfaces.
!’ The interface can have a single abstract method that can refer to a lambda expression. But abstract
class can't.

Conclusion
!’ Always try to prefer an Interface.
!’ Because, you can use multiple Interfaces in concrete classes and also extend one parent class.
!’ Use Abstract class only when required bcause then you can't extend other classes so it's a bit
METHOD OVERLOADING -VS METHOD OVERRIDING
Method overloading is a compile-time polymorphism.
Method overriding is a run-time polymorphism.
It helps to increase the readability of the program.
It is used to grant the specific implementation of the method which is already provided by its parent class
or superclass.
It occurs within the class.
It is performed in two classes with inheritance relationships.
Method overloading may or may not require inheritance.
Method overriding always needs inheritance.
In method overloading, methods must have the same name and different signatures.
In method overriding, methods must have the same name and same signature.
method overloading, the return type can or can not be the same, but we just have to change the parameter.
In method overriding, the return type must be the same or co-variant.
INHERITANCE IN JAVA
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object.
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
• The new class created is called "derived class" or "child class".
• The existing class is known as the "base class" or "parent class".
• The derived class now is said to be inherited from the base class.

WHY USE INHERITANCE IN JAVA


Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.
Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by
which java achieves Run Time. Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all details is achieved through
inheritance.
Abstraction only shows the functionality to the user.
SYNTAXAND EXAMPLE
Syntax:
class Subclass-name extends Superclass-name {
//methods and fields
}
The extends keyword is used for inheritance in java. Using the extends keyword indicates you are derived
from an existing class.

Real life example: Mother and daughter


Some properties of mother inherits by her daughter.
SINGLE LEVEL INHERITANCE
In single inheritance, subclasses inherit the
features of one superclass.
In the image below, class A serves as a base
class for the derived class B.

Class A Child Inherits qualities from parent


MULTI LEVEL INHERITANCE
In Multilevel Inheritance, a derived class will be
inheriting a base class, and as well as the
derived class also acts as the base class for
other classes.
HIERARCHICAL INHERITANCE
In Hierarchical Inheritance, one class serves
as a superclass (base class) for more than
one subclass.
MULTIPLE INHERITANCE
In Multiple inheritance, one class can have
more than one superclass and inherit features
from all parent classes.

Please note that Java does not support


multiple inheritances with classes. In java, we
can achieve multiple inheritances only through
Interfaces.
HYBRID INHERITANCE

It is a mix of two or more of the all types of


inheritance.

Since java doesn't support multiple


inheritances with classes, hybrid inheritance is
also not possible with classes. In java, we can
achieve hybrid inheritance only through
Interfaces.
SUPER KEYWORD IN JAVA
The "super" keyword refers to the parent class of the class in which the keyword is used. It
is used for following three purposes,
For calling the methods of the super class.
For accessing the member variables of the super class.
For invoking the constructors of the super class.

Usage of Super Keyword


Super can be used to refer immediate parent class instance varible.
Super can be used to invoke immediate parent class method.
Super () can be used to invoke immediate parent class constructor.
INVOKING CONSTRUCTOR OF SUPER CLASS
class Parent { int age;
Parent(int age) { this.age age;
}
}

public class Child extends Parent {


int childInt;
Child(int age, int childInt) {
super(age); // Parent class constructor will set the age this.childInt = childInt; // this
constructor will set this }
Child(int age) {
super(age)
}
// any number of constructors...
}
THIS KEYWORD IN JAVA
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.
State This Behaviour reference variable Object

Usage of Java this keyword


Here is given the 6 usage of java this keyword.
this can be used to refer current class instance variable. 1
this() can be used to invoke current class constructor.
this can be used to invoke current class method (implicitly) 2
this can be passed as an argument in the method call
this can be passed as argument in the constructor call. 5
this can be used to return the current class instance from the method.

This: to refer current class instance variable


The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity.
THIS KEYWORD IN JAVA
EXAMPLE THIS: TO REFER CURRENT CLASS INSTANCEVARIABLE
class Test {
int a;
int b;
Test(int a, int b){
this.aa;
}
this.b = b;
void display(){
System.out.println("a"+a+" b=" + b);
}
public static void main(String[] args){
Test object = new Test(10,20);
object.display();
}
}
THIS: TO INVOKE CURRENT CLASS METHOD
Youmay invoke the method of the current class by using the this keyword. If you don't use
the this keyword, compiler automatically adds this keyword while invoking the method.

class Test {
void display() {
this.show();
System.out.println("Inside display function");
}
void show() {
System.out.println("Inside show function");
}
public static void main(String args[]) {
Testt1 = new Test();
t1.display();
}}
THIS(): TO INVOKE CURRENT CLASS CONSTRUCTOR
The this() constructor call can be used to invoke the current class constructor.
It is used to reuse the constructor.
In other words, it is used for constructor chaining.

class Test {
int a; int b;
Test() {
this(10, 20);
System.out.println("Inside default constructor \n");
Test(int a, int b) {
this.aa;
this.bb;
System.out.println("Inside parameterized constructor");
}
public static void main(String[] args) {
Test object = new Test();
}
THIS(): TO PASSAS AN ARGUMENT IN THE METHOD
The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling.
class Test {
int a; int b;
Test(){
a=10; b=20;
}
vold display(Testobj) { }
System.out.println("a" obj.a + b = " + obj.b);
void get() { }
display(this);
public static void main(String[] args){
Test object = new Test();
}
object.get();
}}
THIS(): TO PASSAN ARGUMENT IN THE CONSTRUCTOR CALL
We can pass the this keyword in the constructor also.
It is useful if we have to use one object in multiple classes.
class A {
B obj;
A(B obj) {
this.obj obj;
obj.display();
class B {
int x = 5;
B() {
A obj = new A(this);
void display() {
System.out.println("Value of x in Class B + x);
}
public static void main(String[] args) {
B obj = new B();
}}
THIS(): CAN BE USED TO RETURN CURRENT CLASS INSTANCE
We can return this keyword as an statement from the method.
In such case, return type of the method must be the class type (non-primitive).
class Test {
int a; int b;
Test() {
a = 10; b = 20;
}
Test get() {
return this;
}
void display() {
System.out.println("a=" b = " + b);
}
public static void main(String[] args){
Test object new Test();
object.get().display();
}
ENCAPSULATIONIN JAVA
Encapsulation is a programming technique that binds the class members (variables and methods)
together and prevents them from being accessed by other classes.
Take an example of medical capsules
Where the actual medicine is encapsulated by the outer layer

Imagine the outer layer as a class


Outer Layer is like a class
And the inner medicine is like the data (variables + methods)
variables + methods inside class
Both of these are like encapsulation
ABSTRACTION IN JAVA
Data abstraction refers to providing only essential information about the data to the outside world, hiding
the background details or implementation.
In other words, Abstraction means showing essential features and Hiding non-essential features to the
user.
Abstraction reduces the programming efforts and thereby the complexity.
We hide the implementation details from the user and expose only the functionality to the end-user.
Real Life Example
There by the user will only know "what it does" rather than "how it does" like Atm, Car and Phone.

These above are some real life examples of abstraction, which we are experiencing on the daily basis.
REAL LIFE EXAMPLE : ATM
It has hidden its process by showing only the main things like getting
inputs and giving the output.
REAL LIFE EXAMPLE : CAR
The car internal implementation and complex logic is completely hidden from the user.
REAL LIFE EXAMPLE : MOBILE
A mobile user uses various mobile phone functionalities, But the actual implementation details of these
functions are hidden from the mobile user.
ARRAYS IN JAVA
Array is collection of similar type of elements which has continues memory location.
Need of an array ?
If you want to store Empid of the employee , you use variable to store it.

But what if you want to store empid of 500 employees.


We can create 500 variables but it is very worst Approach.
Youcan create an single array to store all 500 empid in one place.
ARRAY IN JAVA
An array is a collection of elements of the same type stored in contiguous memory locations.
Arrays may be stored in contiguous memory.
The variables in the array are ordered, and each has an index beginning with 0.
Syntax : datatype_name[] arr_name = new datatype_name[size];
Int[] arr; //declare an Array of integers.
Arr = new int[5]; //allocating memory for 5 integers.also int[] myNum = {10, 20, 30, 40};
int[] a;//valid
int[5] a;//invalid
Arr[0] =10 ; // initialize the first elements of the array.
Length of an Array: int length = numbers.length;
RULES IN ARRAY
At the time of array creation compulsorywe should specify the size otherwise we will get compile time error.

It is legal to have an array with size zero in java.

If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.

The allowed data types to specify array size are byte, short, char, int. By mistake if we are using any other type we
will get compile time error.

The maximum allowed array size in java is maximum value of int size [2147483647].

Example:
int[] a1=new int[2147483647];(valid)
int[] a2=new int[2147483648];//C.E:integer number too large: 2147483648(invalid)
ARRAYS IN JAVA
Array is collection of similar data elements stored at contiguous memory location.
It is a simplest data structure where each data element can be accessed directly by only using its
index number.
ARRAYS DECLARATION
Todeclare an array, define the variable type with square brackets :
ARRAYS CREATION
We use "new" operator to create an objects.
In java, Array is an object so we use "new" operator to create Array.

At the time of array creation compulsory , we have to specify the size


ARRAYS INITIALIZATION
Once we can create an array,everyelement of the array by default initialized with the default values

Example : Public class Main{


Public static void main(String[] args){
Int [ ] a = new int [ 2 ];
a [0 ] =10; a[1] =20;
}}
DIFFERENT WAYS OF CREATINGAN ARRAY OF

Primitive Type
int[] numbers1 new int[3]; // Array for 3 int values, default value is 8
{1, 2, 3}; // Array literal of 3 int values
int[] numbers2 3 int[] numbers3 new int[] {1,2,3}; // Array of 3 int values initialized
int[][] numbers4 {{1, 2}, {3,4,5} }; // Jagged array literal
int[][] numbers5 new int[5] []; // Jagged array, one dimension 5 long
int[][] numbers6 new int[5] [4]; // Multidimensional array: 5x4

Non-Primitive Type(Object)

You might also like