Professional Documents
Culture Documents
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.
Object-Oriented :
Java is an object-oriented programming language, promoting modular and reusable code
structures.
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.
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.
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.
Verify: - The bytecode verifier checks the code for integrity and security.
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.
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
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
6. Char
7. Class
8. Continue
<<< Swipe
10. Double
11. Else
12. For
13. Enum
A Java keyword is used to declare an enumerated type. Enumerations extend the base class.
KEYWORDS
14. Import
15. Extends
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
<<< Swipe
25. Native
26. New
27. Null
Sends control and possibly a return value back from a called method.
30. Short
31. Switch
32. This
• byte, short, int and long data types are used for storing whole numbers.
• 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.
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
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).
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.
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.
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.
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.
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:
What is Framework?
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
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 also define our own set of conditions and throw an exception explicitly using throw
keyword
} else {
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
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.
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
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
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.
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
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
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:
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:
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
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?
//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;
}
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.
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
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.
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
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.
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.
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)