Java (AutoRecovered)
Java (AutoRecovered)
Java (AutoRecovered)
Java is high level programming language and it is developed by sun microsystems company.
Java is designed for some reasons that reasons we called know as oops concepts.
Desktop Applications:
Java provides frameworks like JavaFX, Swing, and AWT for building desktop applications
Web Applications:
Java is commonly used for developing web applications. Frameworks like Spring, Java Server Pages (JSP) and
hibernate are frequently employed in Java web development.
Mobile Applications:
Java is the primary programming language for developing Android applications. Android SDK and Android Studio offer
the necessary tools and APIs for building Android apps using Java.
Enterprise Applications:
Game Development:
Java can be used in game development on both desktop and mobile platforms. Libraries like LibGDX and
jMonkeyEngine provide game development frameworks and tools in Java
Java Editions:
we have the 4 Editions Each edition is used to develop the different applications.
Java SE (Java Standard Edition) is the most basic edition of Java and is used to develop desktop, mobile, and web
applications.
Java EE (Java Enterprise Edition) is a more advanced edition of Java that is used to develop large-scale enterprise
applications.
Java ME (Java Micro Edition) is a lightweight edition of Java that is used to develop applications for mobile devices
and embedded systems.
JavaFX is a set of APIs that can be used to develop rich, interactive user interfaces for desktop, mobile, and web
applications.
Features:
Simple:
java is based on the c/c++ syntax so easy to understand and write and Unnecessary concept are removed in java like
pointers, operrator overloading etc.
Object-oriented:
java is based on the class and object so we can easily write the clear code and organize the structure easiy , object is
real world entity which contains the state and behvaiour and class is used to define the state and bebhaiour of the
objects
eg: example mobile phone is object is contains the state like color, brand , an these are reprented by the instance
variables and behaviour like calling , messaging, etc and these are represented by the methods.
Platform indepdendant:
If you develop an application using C++ specifically for the Windows operating system, it will typically be specific to
that platform and may not run on other operating systems so that’s why java is came to picture. Why is not run
because c++ programming language is executed by the compiler that compiler convert the code into that particular
machine code that’s why it is not run on other platform because they designing is different.
So when we run create a application in java then java compiler convert the source code into the byte code not
directly to machine code that byte code is platform independent that byte is run on any system that byte is not
readable format so with the help of jvm we convert byte code into the machine specified code then what ever the
machine is there.
Architectural Neutral:
We create a application by using the java then user is using the application in window system then sometime after
user want to upgrade his operating system, hardware changing everything after doing everything still our java
application is run without any problem bcz java is platform independant and doesn’t depending upon the system
architecture.
Portable:
Java is portable bcz of Byte code that byte code is platform independent is executed by JVM on any platform that
means java code can be written once and run anywhere without the need to recompile if for each platform.
Robust:
Java is a robust programming language because it has a number of features that make it resistant to errors and
crashes. These features include:
Automatic garbage collection: Java uses automatic garbage collection to free up memory that is no longer being used
by objects. This prevents memory leaks, which can cause programs to crash.
Strong typing: Java is a strongly typed language, which means that the types of variables and expressions are checked
at compile time. This helps to prevent errors caused by type mismatch.
Exception handling: Java supports exception handling, which allows programs to recover from errors gracefully.
Security features: Java has a number of security features that help to protect programs from malicious code. These
features include bytecode verification and sandboxing.
Interpreted:
The compiler converts the Java source code into Java bytecode, which is a platform-independent format. The
bytecode is then interpreted by the Java Virtual Machine (JVM), which is a software program that runs on the target
platform.
The compiler is used to create Java bytecode, which is a portable format that can be run on any platform that has a
JVM. The interpreter is used to run Java bytecode on a specific platform.
Biggest Advantage of java having both is compiler is used to identifies he syntactical errors at compile time and
interpreter is used to identifies the errors at runtime..so it improves the performance.
High performance:
JIT Compiler:
Java uses a combination of interpretation and JIT compiler in JVM to execute the byte code.
EG: suppose we have one method it contains the 1000 lines of code and we calling the first method number of time
in the code in jvm without jit compiler every time we call the method 1000 lines of code is executed by interpreter
each due to performance is decreased and time also increase.
jit compiler analyze the code and identifies the frequently executed portion of code known as hotspots. then these
hotspots are compiled into the machine code by Jit compiler when the method is called again no need to execute the
1000line code the interpreter execute the Machine code.
every time Jit compiler it not need for the smaller portion of the code
Garbage Collectior:
Java incorporates automatic memory management through its built-in garbage collection mechanism. The garbage
collector identifies and reclaims memory that is no longer in use, eliminating the need for manual memory
management.
Secure:
Java programms are run the on the Virtual Machine is called as Sandbox
NO Pointers
Exception Handling
Dynamic:
Ditributed.
Class:
Class is blueprint that is used to Define the state and Behaviour of the object. With the help of the Class we can
create the number of Objects.
Example:
consider an example of a Banking Application bank application provides Every customer to a bank account, which
contains details such as the Account Number, Account Holder's Name, Balance, and more. With the help of the bank
account, customers can withdraw money, deposit money, and inquire about their balance.
Based on the above things we want to create the bank application then we need the blueprint or structure of the
bank application with help of the class we can create the blueprint and we need to store the customer details so help
of instance variables we store the customer details and customer perform the actions like Deposit and withdw
money with help method we create the action with help of constructor we insert the values of customers.
Finally we create the blueprint then we don’t have single customer we have multiple customer so with help of
blueprint we create more bank account in these case we called cutomer is object finaly we create the multiple object
based on the single class.
Inheritence:
Inheritence is used to create the new class based on the Existing class , Existing class is called as parent class or super
class and New Created class is called as sub class or derived class.
The Advantage of Inheritence is we can Acquire the properties and method of the parent class in the sub class. So
code is reusable and code reduced , No duplicate Code and Time saves
Example:
Consider an example banking application provides the every customer to create the different kind of accounts such
as saving account , current account .
Based on realtime we want to create the banking application we create the banking account structure using the class
it stores the all the customer details and customer actions like withdraw and Diposit but for the create saving
account and current we need the customer details for the two account customer details are common what we do is
inherit the customer details for the both class.
Multilevel inheritance means sub class is derived from the super class and super class is derived from the its super
class.
Consider an example banking application bank provides the way to customer able to create the different type of
accounts such as saving account ,current account and old people able to create the new seniorcitizen account with
associated with the saving account or current account.
We want to develop the banking application such we also provides same kind features like saving account , current
account and senior account first we create the class account it contains properties of Bank account details like
cutomer number , account name, email , password etc and bank account action like withdraw and desposit. So
inorder to create the saving account , current account in both cases the account we need the account class dettails
so we inherit the the account so we get the properties after cutomer become old he is eliable for the create
seniorcitizen account in that customer want to create we need the again customer account details like he having
saving account or current account then in order to get the saving account details we again extend the saving account
or current account.
Bank—phoneph—user
Constructor:
Constuctor is a special type of method which is used to initialize the objects and Initilze the object means provides
the values to the instance variables.
Constructor name must be class name and constructor don’t have any return type
Final keyword indicate that the class , method ,variable cannot be override , constructor are explicity final that means
cannot be override then no need to mention.
Abstract keyword is used to declare the abstract class, methods abstract having the other purpose like provide the
common functionlites when once the constructor is defined with the abstract is must be override or inherit what
constructor cannot be override and constructor having other responsibilities.
Static keyword used to define the variables and methods that belongs to class rather than the instance of class.
Constructor is used to initlize the instance of variables when the object is created. When the static is used to
constructor is called at compile time then who will be initialize the instance variables. That why not used.
Synchronized keyword is used to achieve the thread safety when multiple thread are allowing the only one thread to
access the resources at a time. But constructor is executed only on single thread during object creation. Object is not
created with multiple thread it is created with single thread.
3 Types.
default constructor
parameterized constructor
copy constructor
Default Constructor: A default constructor is automatically provided by Java in the class if you do not define any
constructors explicitly.
It is a no-argument constructor that initializes the instance variables with default values.
Parameterized Constructor: A parameterized constructor is a constructor that accepts one or more parameters. It
allows you to initialize the instance variables based on the provided values.
Example:
When creating a banking application, we provide the option for customers to create a bank account. Customers can
create their account by providing their details. We use a constructor to initialize the values of the bank account based
on the information provided by the customer. The constructor allows us to set the initial values of attributes such as
the account number, account holder name, and initial balance when the account is created.
Copy Constructor: A copy constructor is used to create a new object by copying the values of another object of the
same class.
Static:
We can use the static keyword with the variable, method, block, nested classes.
Once static variable are declared then it part of class and not part of the instance of object.
Example:
When we create Account class it is used to create the account for the students that account class contains the
variables like std name, college name , mobile etc. so every time new user create the account each time memory is
created but the problem is college name is same for all the student then every time we create account collegename
variable memory is created it waste of memory so what we do is when variable as static then then the variable is part
of class not instance of class and static memory is created once and when we want variables in multiple account it
direct access the static memory through the reference.
Variables: Variables used where same value is used by multiple people then that situcations we use
Method: when method is calling by multiple people then everytime memeory is waste we use.
Blocks--- static block are executes first bcz it loads at compile time and it used for in the college portal we must
require to initialize the database connection first before peforming anykind of operations.
Nested Class:
THIS:
This keyword which is used to refer to the current class object within the non-static area.
This keyword is not used in static area bcz static area is created in compile and object is created at runtime that’s why
so that’s why this cannot be used.
By using this keyword we can access the properties and method of an object.
This keyword is used to call the another constructor in the same class then it is called as constructor chaining .what is
the use calling another constructor is reduce the code like when we want to constructor we must create the object so
memory also waste.
When we call the another constructor in default constructor with instance variable it give you the error bcz it that
time instance variable are not initilzed they are only initized after completion of defulat constructor.
Example:
Suppose take an example like we want create a portal we declaration two variable student name , student id is same
as local variable and instance variable so in order to differentiate we use this.
Super:
Super keyword which is refers to the parent class it can be user subclass to access the variable or Invoke the method
defined in the superclass.
Super keyword also useful in the situations like sub class variables and methods having the same name by the default
jvm gives the priority to the local variables in the sub class so inorder to give the priority to the super class properties
we use the super keyword.
Super keyword also usefull to call parent class constructor in sub class bcz it is usefull in situvations like when we
want to initialize the parent class instance variable before initialzing the sub class.
Final:
Once final keyword is used to variable it value cannot be changed and when we use final keyword with class the class
cannot be extend and with method the method is cannot be override. .
Final keyword is usefull in the situvations like behaiour of the variable or method , class must be constant therir
values not possible to change by others.
Packages:
Packages is like a container which is contains all the classes , interfaces and sub packages .
All the java developers written some predefined code in the form of classes and interfaces and they all are arranged
like a folder structure with the help of folder structure we can easily access the class and intefaces. suppose packages
are not there then developers class and interfaces and they are stored them in single folder so it is not easy to access
and relocate the class and interface easily and another problem is naming collision is occurs like same class name and
interface may be built that problem is occurs.
Benefits:
Access easily
Naming collision
Easily Maintained
Code Reusability
import keyword: most used way with help of import keyword we include the package and once we include the
package no need to specify the fullyQualified name of the package like is we directly create the object for the class at
that moment we don’t specify the fulyqulified name of the package class.
fullyQulified: we use fullpackage name to use the class and interface and with import we get all the unnecessary class
and interface to the project. Naming collison we be resolved using the fullyqualified .
2 types of packages
User-defined packages----depending upon the requirement we can create the our packages so that packages are
helpful in the projects.
Built-in Packages
Regular import
Static import--- suppose class contains the static members so by using the static import we can directly use the static
member without the object.
Access Modifers:
Access modifers are used to control the accessability and visablity of the class, interface, method ,variable
constructor within the program.
Default—Not specified any access specifier by default it is default access specifier it is accessible within the package
and not possible within the sub class
Protected—accessiable within the package and outside package through extending the parent class in diffetnt
pacakges.
Abstraction:
Abstraction means hiding the implantation details from the user and providing only the essential information to the
user .
Example: suppose Example of bank application , bank application provide the option to user to create the bank
account and bank account contains the account_holder_name, account_number , age, number etc.and user perform
action like widraw and deposit and getbalance etc.
After understanding we want to create bank application , with help of abstraction create that we provides the
essential information like withdraw. Deposit option getbalance option and other important features and with help of
abstraction we hides the internal details from the user means the user no need to know the implantation details and
how it is working and there is no use to provide the implementation details.
Abstract Class:
Class is declared with abstract keyword then class is called as abstract class.
Abstract class is act as blueprint it is used to provide the common functionalities for the requirement.
Abstract class cannot be created the object bcz In the abstract class we just declared the abstract method we not
provide any implantation bcz of we creating the abstract class for provide the essential things and common things for
all if we provide the implementation then it is not common to all the things.
Abstract class object is not directly created in created in-directly with the sub class .
Abstract methods
Static methods
Constructors
Non-Abstract Methods
Instance Variables
Interface:
Interface cannot create the object bcz it contains the abstract classes
Interface contains:
Abstract Method
Static method
Default methods
Instance variables
both are used to achieve the abstraction but some difference is there.
Interface have only abstract methods and static and default methods.
Abstract can support the access modifiers like private, protected etc.
Encapsulation:
Encapsulation is the process of wrapping the variables and methods into a single unit is called as class.
Encapsulation is achieved with help of access modifiers such as private, protected, public.
Encapsulation main use is to hide internal details from that means no one can able to access the data.
Example:
suppose Example of bank application , bank application the user to create the bank account and bank account
contains the account_holder_name, account_number , age, number etc.and user perform action like widraw and
deposit and getbalance etc.
so above data we want to create the bank application we also provide the option to user he able to create the
account with the help of personal information like name, mobile number, email id, so we must provide the security
for the his information so by using the encapsulation make his account information private so no one is will be able
to access information only he can access his information. And also we provide an option to customer like he want to
change his information like mobile number so with the help of setter and getter method user can change the mobile
number and display message like mobile number wat changes.
Polymorphisam:
Example: Take an example like audio player the audio players play the different kind of audios like mp3, mp4 mpeg .
That means single audio player performing different kind of operations.
Compile time
Runtime
Compile_Time Polymorphisam—It is happens at compile time and with help of method overloading we can achieve
the compile time polymporphisam
Method overloading means method name is same for all the methods but different parameters.
Example: we want to develop the audio player by using the method overloading to we create , first we create the
different method with same name and different paramters and each method having separate audio code and
Execution is different suppose whenever the user select the mp3 audio format then it matches the particualar
method and it is executed.
Runtime Polymorphisam---it happens at runtime and with the help of Method Overriding we can achieve the these.
Method overriding means method is having the same and same paramters.
Example: we Develop the audio player with method overrding and also help of Abstract class or interface ,first we
create the abstract class inside class we create the one abstract methods that is play method after that we create
the individual audio format classes like mp3 class , mp4 class bcz we write the separate code for each and every
format but one things is common is like play the song so we extend the abstract we create the abstract method after
with help of overrding we can override the play method we write the individual code for each and every abstract
method..
Method Overloading happens at compile time and Method overriding happens at runtime
Method overload with same method name but different paramters and method overrding having the same method
name and same paramters
Method overloading may or may not need of inheritance and Method overriding need the Inheritence
Method Overloading is called static binding and Method Overriding is called dynamic binding.
Method Overloading can be private and final and method overriding cannot be final and private.
Exceptions:
Exception is Type of Error and an Unexpected Event occurred in the programme and it is disturb the normal flow of
the programme and It Terminate the programme That means remaining code will not be executed.
Exception Handling:
Exception Handling is used to Handle the Exception. Exception Handling just provide the solution for the Unexpected
Event.
Example:
We build the video streaming application that is used to watch the videos online, while user is watching the video his
internet connection was failed that is unexpected event and Unwanted event when these is happened video
streaming application it leads to the problems like it crash and not work well so that situvations we must handled the
event using the exception handling when in these user lost his connection then by by using execption handling we
handle the event and we provide an user frieldly message like internet was failed try to connect please.
Java is having their own defulat exception Handler suppose when the excpetion is occurs in the programme the jvm
creates the Excpetion object that object contains the information exception type, excpetion like , exception address
after the jvm is look for the Exception Handler if Exception handler is found it handles if the exception if the
exception handler is not found jvm is having their own excpetion handler to handler exception these default
exception handler not the abnormal flow the execution it just display the exception information .
Exception
Error
Exception:
Checked Exceptions----- these are called as compile time exceptions bcz they are checked at compile time
The Main advantage is checking the exception at compile bcz we can easily detect the exception before code is
compiled.
Example: We devlope the video streaming plaform that used to play the video and also user can create their account
with his data we store the data in the database some days there is a problems with the database like database
connectivity issue or logic issue then user cannot create the account that is then the sql exception is occurs then our
application not work properly bcz of these issue so we must handled the Sql exception
IO exceptions: These Exception are comes when we are working the Input and output operations . IO exception is a
super class .
FIlenotfoundexception Eg: suppose when want to perform the read or write operation on the file then the file path is
found Then these FileNotFoundException is occured.
EOException--end of the file- This exception is thrown when an attempt to read or write data from a file or stream
reaches the end unexpectedly
SQL Exceptions: these exceptions are occurs while working with the database.
ClassNotFoundException: when we try lo load a class , if the class loader is not able to find the class at speified path
then compiler throw classnotfoundexcpetion .
InstantiationException: This exception ocuurs when the we tries to create an instance of a class for the class but the
specified class object cannot be instantiated. Abstract class or interface.
Unchecked Exceptions—these are called as runtime Exceptions bcz they are checked at runtime.
Eg: when we create the a calculator application then user perform the different kind of operation like 2+2 or 2-2 or
0/1 our application gives the answer but user enter the one operation like 1/0 then our application cannot be work
the arthimtic exception will occurred bcz we not unable to answer the question same way our application can’t do
also we identified these problems then by using the exception handler we handle the event we provide the
arthimetic exception and we proved the userfirendly message like we cannot perform the zero by number operation
when ever the user enter same operation he will got the message.
Arthimetic Exception: these exception occurs when the user tries to peform operation like zero by number
NullPointer----these comes when the object is null but we tryies to perform the operation on the object .
String a=null ;
a.length()
IllegalArgumentException: These exception indicate that method has been was passed with the illegalparameter..
Try-----Try block contains the code that code might may be get the exception occurs then when the exception is
occurs is try block then jvm transfer exception to the catch block.
Catch ---Catch Block is used to Handle the Exception and it provide the solution for the exception that is thrown by
try block . catch only executs if the exception is thrown and if the exception is not occured exception block is not
executed.
try block can have multiple catch blocks to handle different types of exceptions. When an exception is thrown within
the try block, the JVM searches for the nearest catch block that can handle the type of exception that was thrown.
Finally --------------these block executed regarding the exception is occured or not , it is commnly used for cleanup
operation such as closing files , database connections.
Finalize() method-------these method defined in objects. it is called by the garbage collector before object is cleanup.
Throws----- used to declare the exception that methods might throws for one exception we are include more
exceptions like
Multithreading:
Multi Tasking---executes the multiple tasks simultaneously and It Improves the performance and save the time.Multi
tasking is achieved in two ways process and thread.
in these multiple tasks are running simultaneously where each task is independent to each other and each task
having the their own memory and own resources and ow work.
Example:
Take an example of web browser in these we open the 3 tabs each tab is doing the different task like 1 tab is palying
the videos , 2nd tab palying the game , 3rd tab browding the web so each tab is consisder as task and each tab is
running simultenously and each tab is having their own memoery and own work and own resoureces if you close the
one tab another tab will not effect bcz they are independent to each other.
Thread based multitasking means executing the multiple threads withing a single big task and each and small part of
the task and each thread is independant to each other and every thread is share the same memory space of big task
bcz there thread are executing inside the big task. We can thread as sub task of the big task.
Example: we want to create a web application in our web application contains the lots of individual task like Loading
the webapplication , connect to database ,Execute the Js , Loading Images etc so with the help of multithreading we
divided the web application to threads each thread is perform the one operation of the web application like one
thread is connect the web application to database , another thread is load the web application , another thread load
the images etc.with the help multithreading all the thread is executed simultaneously it gives to good user
experience bcz user longer to wait for the applications.
Thread:
Thread is individual small unit in the process and each thread having the separate flow of execution and every
thread having the their own work and each thread is independent to each other .
We having the Thread class it is used to create the Threads. Thread class contains the all the method and properties
of the thread.
Multithreading:
Multithread is a process of creating the Multiple Threads and execute the threads the same time and each thread is
independent to each others.
Example: Take an example of Banking Application the banking application developed without multithreading one day
10 customers want to withdraw the money from the bank but banking application can accept one request at a time
so first customer get the access to withdraw other customer must wait till the customer completed its work then only
other customer gets the access due to these multiple customers cannot access the bank that problems so
By using the Multithreading we can possible to create the bank application like multiple customer can access the
bank application simultaneously we create the new thread for each customer and each thread is performing the
different operation.
Advantages:
Disadvantages:
Designing the thread is a complex process it having the lots of problems like race condition, deadlocks. Etc
Each thread is sharing the same memory so it leads to large consume the memory
Thread Lifecycle:
NEW STATE:
When thre is created with new keyword and thread gets the memory and resources it present in the new state.
RUNNABLE STATTE:
Once thread is start with the start method that thread is present in the runnable state.
RUNNING STATE:
Waiting state:
When the thread is pause or delay that thread is goes to the waiting state
Terminated state:
When the thread is completes its execution thread is goes to terminated state.
Java programming is already running on one thread that is main thread these main thread is created by the jvm when
the java programme that running , suppose you create the thread manually main thread for the main class it
becomes the child class not the orginal main thread and what ever the threads you create they all are part of the
main thread are they are child threads.
Thread Class:
Constructor:
Thread(runnable)--- we create thread class object indirectly with respect to runnable interface.(providesan the
runnable object)
Method:
Run()—it contains the thread code these run method is called automatically when the thread is start .
Join()—if we want to complete the execution of child threads first then we have to stop the execution the main
thread with help of join method we stop the execution of main thread then that thread is goes to the waiting state.
Getstate()---return the current state of the thread it returns the enum value like NEW , RUNNABLE, RUNNING,
BLOCKED , WAITING.
Isinterepted()---any thread in the waiting state then using the interrupt method we can break the thread from
waiting state.
These method is work only when the thread is on the waiting state.
getId()---When thread is created each thread is assigned a unique Id when it is created it returns the Thread Id.
getPriority()---return the priority of the thread.
Suspend()—when the thread is running these method is put the thread into waiting state.
Resume()---Once its moved then we want to run the thread resume method moves the thread into waiting state to
running state.
Yield----these method allow to run another thread which is having same priority is pause the current thread
execution and after current thread is executed.
Synchronization:
Multiple Threads are very useful in the situations whenever we want to completed the our task at same time. But
problem is multiple Threads accessing the same resources at same time then it gives the inconsistent results. With
the help of synchronization only one thread executed and thread can access the resources at a time while other
threads are in the waiting state. so it prevent the race conditions, corrupt data.
Example:
When we create the movie ticket platform with multithreading and without synchronization and suppose in one
situation like one seat is available but 3 people are want to book that seat so our application cannot provide the 1
seat for 3 people and 3 people trying to access the 1 seat our application will not work properly like 1 seat is
allocated to 3 people or 1 seat allocated for one people we don’t know what is happening then with help of
synchronization we handled the multiple thread accessing the same resources we allocated that one seat to first
person is how it accessing.
Synchronization keyword is used only when the particular code to be handled or synchronized.
Synchronization makes parallel execution of threads into concurrent of thread execution (like one by one)
They are two types of locking mechanisms used to achieve the synchronization
Synchronization when we want to perform, we need locking system and synchronized keyword for method or block
or class.
Mutual Exclusive:
Interthread communication
Mutual Exclusive----It prevents the multireads access same resources and it executed only one thread and that
thread access the resources while other thread are in waiting state.
Synchronized Method
Synchronized Block
Static Synchronization( class level locking)
Object Level Locking—instance level locking: These object level locking is when the multiple thread are want to
access the same object resources then object is resources having the same the lock so that lock is given to only one
thread at time and that thread is executed and after the lock is released next thread is will acquire the lock then it is
access the resources the remaining thread are goes to wating state.
Method: when the method that is declared with Synchronized keyword before the name then that method would be
synchronized and thread safe so multiple thread are try to access the same method with the help of synchronization
will handled that.
Block: Block is useful when the we want to synchronize the 5 line code in programme what situation we use the
block.
Class Level Locking—Every class is having the lock and multiple thread want to access the same resources class the
threads need the lock and class give the lock to one thread the that thread is access the resources and after the
execution of thread the lock is released and next thread is acquiring of lock.
Class level locking only work with thread is want to access the static synchronized method or static synchronized
block. Bcz no need to create the object for the resource and directly access the resources.
Static synchronized method: we put the static keyword Infront of the static method then the thread is directly access
the resources without object and resource class having the one key it is given to one thread at all time and other
threads are in waiting state.
Static Block synchronization: we create a block is synchronized keyword and with parameter is resource class
reference
Interthread Communication:
Interthread communication is used to achieve the synchronization when multiple threads are used to access the
same resource then collision will be happened and it gives the incorrect details.
With the help of interthread communication the threads are communicate and Syncronize and exchange the
information between the thread to coordinate their execution
In these the thread is paused running in its resources and another thread is allowed to enter into the same resources
to be executed. It is implemented by following methods.
Wait()
Notify()
Notify All()
Wait()
These method is used to make the current thread to release the lock and wait until either another thread invokes the
nofiy or notifyall method
Notify:
Notifyall:
Thread scheduling:
Jvm uses the Thread scheduling and Thread scheduling means it manages the thread execution order and allocate
the time for thread and allocated the memory for the thread and executed the multiple thread concurrently and
parall in the programme . Thread scheduling contains the lots of works each work is different and they are part of
thread scheduler.
Thread Priority:
Each thread is assigned a priority value, when the value is assigned, the threads get the high priority then more
chances to thread gets executed first.
Thread State:
Thread is having the various states such new, running , runnable, wating ,terminated with the help these states
thread scheduler is manages the thread executions flow.
Time Slicing:
Time slicing means Each thread gets the same time and space for the thread to execute
Demon Thread:
Deamon threads are low priority threads that run in the background to perform the task such as garbage collection
etc.
Demon thread is also used for user threads for background supporting tasks.
-----------------------------------------------------------------------------------------------------------------------------------------------------------
Hierarchy of Collection Framework:
ITERABLE:
Iterator method Returns the Object of Iterator Interface. So with the help of Iterator object, we can access the
methods of iterator Interface.
Iterable interface is used to iterate each and every element sequentially from a collection with the help of iterator
method we can return the value from the collection or remove the value from the collection.
-*+
ITERATOR METHOD:
Iterator class implements the Iterator interface so When we call Iterator method returns the object of Iterator class
Iterator method creates the creates the object automatically for the iterator class the iterator class implements
iterator interface. Iterator interface declared the hash next , next , remove method so iterator class implements the
iterator interfaces and override the methods and provide the code then so with the help of iterator object we
directly accessing the iterator interface methods to perform the operations.
Hash next()
This method is return the Boolean value and it check element in the collection if the element is found it returns true
otherwise false.
Next()
These method is used to return the element from the collection and if not element is found it throw an exception like
NOSUCHELEMENTEXCEPTION.
remove()
while (iterator.hasNext()) {
if (element.equals("b")) {
iterator.remove();
FOR LOOP
ITERABLE
COLLECTIONS:
Collection framework main use is we can able to store different type of values in a single object and we can
perform the inserting, searching, sorting, deleting the values.
Framework contains the pre-written code written in the form of class and interfaces that are used to develop the
java application.
When we will go the collection is we want to store the group of different type of values in a single entity.
The collection extends the iterable interface why it is extends is So with the help of Iterable interface we can iterate
each and every element from the collection.
collections are designed to store objects and not primitive values directly. but, when you try to store the primitive
values directly, which can be automatically convert primitive values into objects with the help of wrapper class that is
autoboxing and unboxing.
Collection interface declared some method so with the help of these we perform the operations.
Collection Methods:
1. Adding Elements:
addAll(Collection): Adds all elements from the specified collection to the current collection.
2. Removing Elements:
removeAll(Collection): Removes all elements in the specified collection from the current collection.
containsAll(Collection<?> collection): Checks if the collection contains all elements in the specified
collection.
forEach(Consumer<? super E> action): Performs the specified action on each element in the
collection.
toArray(T[] array): Returns an array containing all elements in the collection, using the specified array
if it is large enough.
6. Miscellaneous:
equals(Object object): Checks if the two collection values equal or not Returns true or false.
Object_1.equlas(object_2);
List interface is implemented by the array list, linked list, vector, stack classes.
indexOf(Object o): Returns the index of the first occurrence of the specified element in the list, or -1 if it is not
present.
lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in the list, or -1 if it is not
present.
ListIterator<E> listIterator(): Returns a list iterator over the elements in the list.
ARRAY LIST:
Array list uses the dynamic array to stores the elements Dynamic array means there is no size limit of array list and
we can add more elements then the array list size is increased automatically.
Array list stores the elements in the Contiguous manner that means elements are stored in the sequential manner.
Array list is not thread safe that means Multiple threads are accessing the same array list resources and performing
operation on the array list at same time it lead to data corruption or unexpected behaviour so we explicitly use the
synchronization to handled the multiple threads.
We array List only stores the Objects and not primitive values because they are not objects collection only designed
to Store the objects but we you try to store the primitive values automatically convert into object with the help of
wrapper class.
We use Generics to specify the type of elements that collection can stores like integer, String, float etc.
ArrayList<int> al = ArrayList<int>(); // does not work
linkedList:
Linkedlist is a class provide the implementation of the list and Deque interfaces.
Linkedlist uses the double linked list to store and manipulate the data on the list.
Linked list stores the elements in non-contiguous manner that means data is stored in different places in memory
and there are linked.
Linked list use nodes to store the data. Nodes contains the data and next node address and previous address node
address
Array list uses the dynamic array to store the elements and each element is stores in the continuous in the memory.
LinkedList uses the double linked list to store elements and each element is called as node it contains the previous
address of node and next address node.
Array list takes the less time to search the elements because array list having the index positions and with the help of
index position access easily. Time complexity is O(1)
LinkedList takes the more time to search the elements because Linked list having no index positions so we have to
Iterate each and every element node start to end then we find the element. Time complexity is O(n).
Array list is taking the more time to insert or delete the values from list because we Iterate each and every element
and perform the operation. Time complexity O(n).
Linked list is take less time to insert or delete the values because linked list having node each node is point to the
previous node and next node so we can directly add the element to list Time complexity is O(1)
Linked list take more memory to store the elements because it stores the element along with the store the address
references of the previous node and next node.
Suppose we want to create the E-commerce Shopping Cart then that cart users can add products to their cart An
ArrayList can be used to store the selected products, allowing users to add or remove items from their cart.
Linked List:
Suppose we want to create the Music Playlist that An application that manages a playlist of songs. Each song can be
represented as a node in a linked list, where each node contains information about the song and a reference to the
next song in the playlist.
Vector:
Vector is legacy class the meaning is it older class in java it is introduced in the java before the collection framework.
Vector is thread-safe that means vector automatically having the thread synchronization by the default
Array list is not thread-safe that means array list not automatically having the thread synchronization by the default
we must explicitly perform the synchronization
Vector is legacy class and means that is available from the java. Array list not a legacy class because it is introduces in
the java 1.2 version.
Vector is slow because of synchronization it holds the thread execution until the first thread execution completed.
Array list is fast because of non-synchronized.
Stack:
Stack uses the LIFO order to store Elements that means new element is added to last stack and element is removes
first from the stack.
Stack Methods:
Queue:
Queue interface uses the First-In-First-Out (FIFO) order in which elements are added at one end and removed from
the other end.
Queue interface stores the elements based on the insertion order in sequential manner.
Queue interface which is used added, remove and modified elements based on the index.
Adding:
Add()—add the specified element at the end of queue and return the exception when element is not added
Offer(()—adds the specified element to the end of queue and return NULL VALUE if element is not found
Remove:
remove()—removes the first element of the queue and queue is empty is throw an exception.
Poll()---removes the first element from the queue and queue is empty it return the null value.
Get Methods:
Peek()—returns the element from the queue and not deleted the element.
Priority Queue:
Priority Queue is deletion happens at head part and insertion is happens at tail part.
suppose we add the integer elements in the queue like 6,4,2,1 not properly ascending randomly added but internally
they check the priority of the element and it moves the element to the Head in the queue I mean first in the queue
and then remaining are randomly inserted only first highest priority element is point to head positioned it not sort
the elements from ascending to descending just randomly display the elements. Suppose we remove the highest
priority element then again it check the highest priority element it moves to the first place.
No elements are found then the queue is Null is it a default value that means no values.
Foreach: if we use these then it print the elements based insertion order not based on the priority queue.
While: we uses the ! isEmpty() method to check queue is empty or not then we uses the poll() method to retrieve
method.
Deque interface:
Methods:
Inserting:
AddFirst()---insert the element beginning of the queue and throws an exception if the insertion is fails at first
offerFirst()---insert the element beginning of the queue and return true if the insertion is succeed and return false
insertion fails.
AddLast()—insert the element ending of queue and throws an exception if the insertion is fails at last.
Offerlast()—insert the element Ending of queue return true if the insertion is succeed and return false insertion fails.
Remove:
Pollfirst()—removes the element beginning of the queue and return true or false
Polllast()—removes the element end of the queue and return true or false
Know Method:
getFirst(): Returns the element at the beginning of the deque without removing it. Throws an exception if the deque
is empty.
getLast(): Returns the element at the end of the deque and throw and exception.
PeekFirst()—Return the element first of the queue and Return null if the deque is empty
PeekLast()—return the element last of the queue and return null if the deque is empty.
Array Deque:
Array deque is implemented by circular array which mean that we able to add or remove or retrieve the elements at
both ends.
Array deque stores the elements in insertion order. And contiguous manner
Array deque takes the less time for insertion or removing or retrieving the elements at both ends Time complexity is
O(1)
Linked List:
Linked list uses the double linked list so we can able to add or remove or retrieve elements at both ends.
Array deque takes the less time for insertion or removing or retrieving the elements at both ends and Time
complexity is O(1)
Linked list uses the double linked list to store the elements.
Linked list consumes the more memory because it stores the node address.
Both having the insertion and deletion and retrieving take the same time i.e. O(1).
Linked list doesn’t have the index they have the nodes
Array deque most used for insertion and deletion and removal at both ends and not possible to add in middle.
Linked list most used for insertion and deletion and removal at both ends and also possible with middle is possible
Map Interface:
Map is an interface which is extends the Iterable interface.
Map interface stores only the unique keys and doesn’t allow the duplicate keys and but we can have the duplicate
values for different keys.
In map Interface we can retrieve the values based on the keys and it is more efficient to retrieval the data.
Map interface allows single null key and multiple null values.
Map interface
Map interface cannot be traverse the elements because we don’t have the index so we use keyset() or entry set()
methods Iterate the keys and value.
Map is useful when we have to perform the search update or delete operations elements so we use the key to find
the values very fast bcz no need to iterate the map and we cannot iterate the map .
Examples: e-commerce application, we use the map interface to store the product information, we store the product
information in the form of key and value pair, the product Id serves as the key and product information serves as
value it contains like name, price ,description, stock quantity.
Keyset():
These method is returns the set object depending upon the map data like integer ,float, string so after we need to
store the set object in set data structure. So with help of set data structure, we travers the elements.
We want to print the values of the hash map we use the Values() these method will return the collection object so
we need to store that and after we iterate collection object to known the values.
For(Integer key: s)
Entry set():
These method it returns the keys and values both it also return the set object we store object in set data structure
Set< interger, string> entry =hash_object.entryset();
Difference between the hash table, hash set, Linked Hash set, tree set
HashMap: Not thread-safe by default. Requires external synchronization for concurrent access.
LinkedHashMap: Not thread-safe by default. Requires external synchronization for concurrent access.
TreeMap: Not thread-safe by default. Requires external synchronization for concurrent access.
TreeMap: Does not allow null keys. Restrict the null values to store.
Hashtable: It Doesn’t stores the elements based on the specific order it store randomly.
HashMap: It Doesn’t stores the elements based on the specific order it store randomly.
LinkedHashMap: Store the elements based on the insertion order of the elements.
LinkedHashMap: Slightly slower performance compared to HashMap due to maintaining the insertion order.
TreeMap: Slower performance compared to HashMap and Linked HashMap due to the tree structure.
Example:
Hash table:
Suppose we create the student attendance application; we use the hash table to maintain the record of student
attendance. we create the student Id as a key and attendance status information as value. Hash table is synchronized
that means multiple students updating attendance and simultaneously.
Hash map:
Suppose we create the student grade application; we use the Hash map to store and retrieve student grades.
The student Id can serve as key and grade can be value. Hash map provides the efficient performance for adding,
updating, retrieving grades.
Suppose we create the student registration application we use the linked hash map for storing the student register
account information in the insertion order it maintain where insertion order what ever the student registered first we
added to the linked Hash map.
Tree Map:
Suppose we create the dictionary application, we use the Tree map to store the dictionary word and dictionary
definition. The key is name and value is definition and Tree map is automatically sort and stores the elements based
on the alphabetical order. Tree map is efficient for searching for words
SET Interface:
Set interface stores only unique elements and it doesn’t allow the duplicate elements to store.
When we try to add the duplicate data it doesn’t return any error it is just not add the element in the set it is just skip
the element.
Set interface stores the elements unorderly that we not don’t know which order they are going to store.
Set interface doesn’t allow the direct access to elements with the index because we don’t know which they are
going to store and we use the iterate to access the elements.
Set interface is extended by sorted set and again sorted set again extended by navigable set and navigable set
implemented by tree set class.
HashSet: Elements are stored are randomly when don’t know which order they store.
LinkedHashSet: Uses slightly more memory than HashSet due to maintaining the linked list.
TreeSet: Can use significantly more memory than HashSet and LinkedHashSet due to the tree structure.
Examples:
Hash set:
Suppose when developing application that application stores a list of unique email address in that situations we use
the Hash set because it not allows the duplicate email address. Hash set effectively handle the unique elements and
allowing you to add ,remove and search the Email address.
Suppose when you developing music playlist application every time user plays the song that song are added to
playlist in the same order they play. We can use the linked hash set to store the elements based on order of the song
played. Linked hash set effectively handle the adding , removing songs from the playlist.
Tree set:
Suppose when we develop the employee application, we need to store to the employee details in the ascending
order and with the help of tree set we stores the employees in ascending order and with the help of tree set we can
easily identify the employees’ details.
These datatypes are based on the class and object. Class represent the Structure of datatype and object creates the
memory for the values.
These Data types stores the reference or memory address of the actual data.
String
Array
Object
STRINGS:
String is class is part of Java. Lang package which is automatically imported in the programme.
String class represent group of character values. String class provides the various methods such length , charat() ,
concat(), tolowercae(), touppercase() so with the help of Methods we can perform the operations on String like
adding , deleting, updating.
String class
StringBuilder class
We need to store the String data we must create the String object bcz when object is created then only memory is
Assigned .
String Literal
String class is immutable, which means that once a String object is created, its value cannot be changed. Instead of
modifying the original String object, any operation that appears to modify the string actually creates a new String
object with the desired changes.
Why String is Immutable bcz of Security Reasons that mean no one can change the String values example like
password is String so no one can change only you can change .
String literal
New keyword
String literal:
when you create a String object using a string literal, that object is stored in the string constant pool, which is part of
the heap memory.
String Constant pool is a special area in the heap memory that stores the String objects. When we create the String
by using the String literal java check the String object in the pool if the same String object is existed it is Stored in the
same memory area in pool. If not exited in stored in the different memory area in the pool.
String a=”abhi”;
String b=”abhi”;
New Keyword:
We can create the object using the new keyword and that object is memory is created in the heap memory.
Heap memory is area in the computer memory which is used for allocates the memory the created objects. The data
is not stored permently in the memory Whatever the operation is performed that values are stored in the memory
after closing the programme entire memory is deleted.
Every time String object is created and each time memory is created regarding the String object values is same or
not.
B==c // false bcz there memory address is different values is same or not.
== operator
It used to compare the two values along with the object address. It perform the AND operation if condition failed
then it is false.
String a=”abhi”;
A==b // false bcz values is same but address id different so it returns false.
Equals Method:
Equals method is compare the values only not consider their address.
String a=”abhi”;
a.equals(b) // return true bcz it check only the value not address.
String Builder class is used to create new String object in the heap memory and It creates the mutable Strings that
means you can directly perform operations on String values then there is no object is created every time operation
is perform.
Append()
Delete(4,”abhi”)
Replace()
Reverse();
String Buffer is similar to String Builder but only difference is Thread safe String buffer by default is supports the
Synchronization that mean multiple thread can access the data at same time without data corruption.
when we write the + operator the compiler generate the String Builder class to combine the two concatenated
strings.
String s1 = "hello";
String s2 = "world";
String s3 = s1 + " " + s2;
ARRAY:
Fixed size: The size of an array is determined at the time of creation and cannot be changed dynamically. You need to
specify the size of the array when declaring it.
Homogeneous elements: All elements in an array must be of the same type. For example, an array of integers will
only store integers, an array of strings will only store strings, and so on.
Zero-based indexing: The index of the first element in an array is 0, and the index of the last element is length - 1,
where length represents the size of the array.
Contiguous memory allocation: Array elements are stored in contiguous memory locations that is sequential
manner, allowing for efficient memory access.
Multidimensional Array
This approach involves declaring an array variable and then allocating memory for the array using the new keyword.
The size of the array is specified during allocation.
This approach combines declaration, allocation, and initialization in a single statement. You provide the initial values
for the array elements.
int[] a = {1, 2, 3, 4, 5};