0% found this document useful (0 votes)
8 views

OOPS With Java All 5 Units Notes

Uploaded by

2k22.csds.32825
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

OOPS With Java All 5 Units Notes

Uploaded by

2k22.csds.32825
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 259

Object Oriented Programming

AKTU
with Java
Subject Introduction
B.Tech 2nd Year 4th Sem
New Syllabus
Object Oriented Programming with Java
Unit :- 1
AKTU BCS-403
Introduction

Java is a High level , Class based ,


Object Oriented Programming (OOP)
Language developed by James
Gosling in 1991.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the
Java language project in June 1991. The small team of sun engineers
called Green Team at Sun Microsystem.
2) Initially it was designed for small, embedded systems in electronic
appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file
extension was .gt. After that, it was called Oak and was developed as a
part of the Green project.
4) Why Oak? Oak is a symbol of strength and chosen as a national tree of
many countries like the U.S.A., France, Germany, Romania, etc.
5) In 1995, Oak was renamed as "Java" because it was already a trademark
by Oak Technologies.
6) Java is an island in Indonesia where the first coffee was produced
(called Java coffee). Java name was chosen by James Gosling while
having a cup of coffee nearby his office.
7) Initially developed by James Gosling at Sun Microsystems (which is
now a subsidiary of Oracle Corporation) and released in 1995.
8) JDK 1.0 was released on January 23, 1996.

After the first release of Java, there have been many additional features
added to the language. Now Java is being used in Windows applications,
Web applications, enterprise applications, mobile applications, cards, etc.
Each new version adds new features in Java.
The Java Runtime Environment, is a software layer that runs on top of a
computer’s operating system software and provides the class libraries and
other resources that a specific Java program requires to run.
Compilation and Fundamentals
Programming Structures in Java
The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.
Static Members and Final Members
Object Oriented Programming

A Class is a template or blueprint for creating


Objects; an Object is an Instance of a Class.
An entity that has state and behavior is known as an object e.g., chair,
bike, pen, table, car, etc. It can be physical or logical (tangible and
intangible). The example of an intangible object is the banking system
Java, Inheritance is an important pillar of OOP. It is the mechanism in Java by
which one class is allowed to inherit the features(fields and methods) of
another class. In Java, Inheritance means creating new classes based on
existing ones. A class that inherits from another class can reuse the methods
and fields of that class. In addition, you can add new fields and methods to
your current class as well.
Example :

In the below example of inheritance,


class Employee is a base class,
class Engineer is a derived class
that extends the Employee class
and class Test is a driver class to
run the program.
The word polymorphism means having many forms. In simple words, we
can define Java Polymorphism as the ability of a message to be
displayed in more than one form.
Packages
In Java, static import concept is introduced in 1.5 version. With the help
of static import, we can access the static members of a class directly
without class name or any object.
For Ex: we always use sqrt() method of Math class by using Math class
i.e. Math.sqrt(), but by using static import we can access sqrt() method
directly. According to SUN microSystem, it will improve the code
readability and enhance coding. But according to the programming
experts, it will lead to confusion and not good for programming. If there
is no specific requirement then we should not go for static import.
Object Oriented Programming with Java
Unit :- 2
Exception Handling

An exception is something that is left out or not done on


purpose. An exception to a rule does not follow that rule.

In Java “an event that occurs during the execution of a


program that disrupts the normal flow of instructions” is called an
exception. This is generally an unexpected or unwanted event which
can occur either at compile-time or run-time in application code.
In Short errors and exceptions represent different types of problems that
can occur during program execution. Errors are usually caused by serious
problems that cannot be recovered from, while exceptions are used to
handle recoverable errors within a program.
Control Flow in Exceptions
JVM Reaction to Exceptions
The JVM starts the search from the method where the exception
occurred and then goes up the call stack, checking each method in
turn for a catch block that can handle the exception. If a catch block
is found, the JVM transfers control to that block and the exception is
considered to be handled.
In Exception handling , we should have
an alternate source through which we
can handle the Exception.
Input / Output Basics
Reading and Writing File in Java
1. In Java, the FilelnputSream class is used for reading binary data
Reading from a file: from a file.
2. It is an input stream that reads bytes from a file in a file system.

3.To read data from a file using FileInputStream, these steps you
need to follow :-
Step 1: Create an instance of the FileInputStream class and pass the path of the file that you
want to read as an argument to its constructor.

Step 2: Create a byte array of a fixed size to read a chunk of data from the file.

Step 3: Use the read() method of the FileInputStream class to read data from the file into the
byte array. This method returns the number of bytes read , or -1 if the end of the file
has been reached.

Step 4: Continue reading data from the file until the read() method returns -1.

Step 5: Close the FileInputStream object using to release the close() method to release any
system resources associated with it.
Following example demonstrates how to use Fileinputstream
to read data from a file :
import java.io.*
In the example above, we create a
public class ReadFileExample {
FilelnputStream object to read data
public static void main(String[] args) {
from a file called "file.txt".
try {
FileInputStream fileinput = new
We then create a byte array of size 1024
FileInputStream ("file.txt");
to read a chunk of data from the file.
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileInput.read(buffer))!=-1){
System.out.println/new String buffer, 0, bytesread));
} We use the read() method to read data
fileInput.close(); into the buffer untill the end of the file is
} catch (IOException e) { reached, and then we close the
e.printStackTrace(); FilelnputStream object.
}
} Finally, we print the data that we read
} from the file to the console
Writing in a file: 1. In Java, FileOutputStream class in used for writing binary data to a file.

2. It is an output stream that writes bytes to a file in a file system.

3. To write data to a file using FileOutputStream, you need to follow


these steps:
Step 1: Create an instance of the FileOutputStream class and pass the path of the file that
you want to write as an argument to its constructor. If the file dosen't exist, it will
be created automatically.

Step 2: Create a byte array that contains the date that you want to write to the file.

Step 3: Use the write() method of the FileOutputStream class to write the data to the File
This method writes the entire array to the the file.

Step 4: Close the FileOutputStream object using the close() method to release any system
resources associated with it.

Following example demonstrates how to use FileOutputstream


to write data to a file :
import java.io.*;
public class Write File Example {
public static void main(String[] args) {
try {
FileOutputStream fileOutput = new
FileOutputStream("file.txt");
String data ="This is some data that will be written to a file";
byte[] bytes = data.getBytes();
fileOutput.write(bytes);
In the example above, we create a FileOutputStream
fileOutput.close();
object write data to a file called "file.txt".
} catch (IOException e) {
e.printStackTrace();
We then create a string that contains some data that we
}
wants write to the file.
}
}
We convert this string to a byte array using the getbytes()
method and then we use the write() method to write the
data to the file.

Finally, we close the FileOutputStream object.


Multithreading
Object Oriented Programming with Java
AKTU Unit :- 3 BCS-403
Java New Features
Stream API is a newly added feature to the Collections API in Java 8. A
stream represents a sequence of elements & supports different operations
(Filter, Sort, Map, and Collect) from a collection.
Static method is a static member to the Interface, cant be overridden
(as with the class), default method is the default implementation of a
method which might be overridden.
Difference between Static Interface Method and Default Interface Method
ForEach Method
This is how JDK now looks
like. On the bottom, we
have “java.base” module
that every other module
implicitly or explicitly depends
on. As you can see, this
dependency graph is
a DAG which means no
circular dependency allowed.

It is a name of module and should follow the reverse-domain-pattern.


Like we name packages, e.g. com.itechworld.
Diamond Syntax with Inner Anonymous Class

, It is an inner class without a name and for which


only a single object is created. An anonymous inner class can be useful
when making an instance of an object with certain “extras” such as
overriding methods of a class or interface, without having to actually
subclass a class.
Diamond syntax, sometimes known as the
diamond operator, It was added to Java 7 as just
a new feature. The diamond operator makes it
easier to employ generics while building an
object.
The Java releases up to and including 13 are rather manageable in terms
of their innovations. This is true even for Java 11 as an LTS version.
Fortunately, Java 14 brings a good slew of useful enhancements:
On the one hand, there are the convenient syntax changes in switch.

Let me conclude: The new syntax of switch seems to be just a small


change, but it has an enormous effect on readability and ease of use.
Object Oriented Programming with Java
AKTU
Unit :- 4 BCS-403
Java Collections Framework

The Collection in Java is a framework that provides an architecture to


store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
In Java, "Collections" refers to a framework provided in the Java API to
manage and manipulate groups of objects. These objects are commonly
referred to as elements or items.
The Collections framework provides a unified architecture for working with
collections of objects. It allows developers to easily store, retrieve,
manipulate, and iterate over these collections.
Key features of Collections:
The Java Collections framework is a set of classes and interfaces that provide
implementations of commonly reusable collection data structures in Java.

The data structures can be lists, sets, maps, queues, etc.

It provides a unified architecture for manipulating and storing groups of objects.


Advantages of Java Collection Framework :-
1. The Utility Package (java.util)
contains all the classes &
interfaces that are required by
the collection framework.

2. The collection framework


contains an interface named an
iterable interface which
provides the iterator to iterate
through all the collections.
This interface is extended by
the main collection interface
which acts as a root for the
collection framework.

3. All the collections extend this


collection interface thereby
extending the properties of the
iterator and the methods of this
interface.
The Collection interface is the root interface in the Java Collections
framework hierarchy. It represents a group of objects, known as elements,
and provides a unified way to work with collections of objects in Java.

The Collection interface defines a set of operations that can be performed


on collections, regardless of their specific implementation. The Collection
interface does not specify any particular ordering of elements.

The Collection interface allows duplicate elements.

Overall, the Collection interface serves as a fundamental building block for


working with collections of objects in Java. It provides a common set of
operations and behaviours that can be used across different types of
collections.
Collection is called interface in java whereas Collections is called a
utility class in java and both of them can be found in java. util.
package. Collection is used to represent a single unit with a group of
individual objects whereas collections is used to operate on collection
with several utility methods.
This is a child interface of the collection interface.
This interface is dedicated to the data of the list type in which we can
store all the ordered collections of the objects.
This also allows duplicate data to be present in it. This list interface is
implemented by various classes like ArrayList, Vector, Stack, etc.
Since all the subclasses implement the list, we can instantiate a list
object with any of these classes.

1. Ordered Collections 4. Iterable

2. Indexed Access 5. Search Operations

3. Dynamic Size
The LinkedList stores its items in "containers." The list has a link to the first container
and each container has a link to the next container in the list. To add an element to the
list, the element is placed into a new container and that container is linked to one of the
other containers in the list.
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are not part of Collection framework.
It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of
Vector class and also provides its methods like boolean push(), boolean peek(), boolean
push(object o), which defines its properties.
Being an interface the queue needs a concrete
class for the declaration and the most common
classes are the PriorityQueue and LinkedList in
Java. Note that neither of these implementations
is thread-safe. PriorityBlockingQueue is one
alternative implementation if the thread-safe
implementation is needed
Queue interface maintains the first-in-first-out order.
It can be defined as an ordered list that is used to hold the elements which
are about to be processed.
There are various classes like PriorityQueue, Deque, and ArrayDeque
which implements the Queue interface.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();

2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface,


some of them are given below.
The Deque (double-ended queue) interface in Java is a subinterface of the
Queue interface and extends it to provide a double-ended queue, which is a
queue that allows elements to be added and removed from both ends. The
Deque interface is part of the Java Collections Framework and is used to
provide a generic and flexible data structure that can be used to implement a
variety of algorithms and data structures.

Deque interface extends the Queue interface. In Deque, we can remove and add
the elements from both the side. Deque stands for a double-ended queue which
enables us to perform the operations at both the ends.

Deque can be instantiated as:


Deque d = new ArrayDeque();
The ArrayDeque class in Java is an implementation of the Deque interface that uses a resizable array to store its
elements. This class provides a more efficient alternative to the traditional Stack class, which was previously
used for double-ended operations. The ArrayDeque class provides constant-time performance for inserting and
removing elements from both ends of the queue, making it a good choice for scenarios where you need to
perform many add and remove operations.
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can
add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
The set interface is present in java.util package and extends the Collection interface. It is an unordered
collection of objects in which duplicate values cannot be stored. It is an interface that implements the
mathematical set. This interface contains the methods inherited from the Collection interface and adds
a feature that restricts the insertion of the duplicate elements. There are two
interfaces that extend the set implementation namely SortedSet and NavigableSet.
In the above image, the navigable set extends the sorted set interface. Since a
set doesn’t retain the insertion order, the navigable set interface provides the
implementation to navigate through the Set. The class which implements the
navigable set is a TreeSet which is an implementation of a self-balancing tree.
Therefore, this interface provides us with a way to navigate through this tree.
Set Interface in Java is present in java.util package. It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store the
duplicate items. We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet. Set can be instantiated as:
Java HashSet class implements the Set interface, backed by a hash table which is actually
a HashMap instance. No guarantee is made as to the iteration order of the hash sets which means
that the class does not guarantee the constant order of elements over time. This class permits the
null element. The class also offers constant time performance for the basic operations like add,
remove, contains, and size assuming the hash function disperses the elements properly among the
buckets, which we shall see further.

where E is the type of elements stored in a HashSet


The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all
elements. When the iteration order is needed to be maintained this class is used. When iterating
through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the
elements in the order in which they were inserted. When cycling through LinkedHashSet using an
iterator, the elements will be returned in the order in which they were inserted.
LinkedHashSet class represents the LinkedList implementation of Set
Interface. It extends the HashSet class and implements Set interface.
Like HashSet, It also contains unique elements. It maintains the insertion
order and permits null elements.
The SortedSet interface present in java.util package extends the Set interface present in
the collection framework. It is an interface that implements the mathematical set. This interface
contains the methods inherited from the Set interface and adds a feature that stores all the
elements in this interface to be stored in a sorted manner.
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses
a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering
whether or not an explicit comparator is provided. This must be consistent with equals if it is to
correctly implement the Set interface.

Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also
contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in
TreeSet stored in ascending order.

1. Sorted order 4. Iterating in sorted order

2. Unique elements 5. Use of Red-Black tree

3. Efficient operations
Map stores Elements as
key-value pairs, where
each key is associated with a correspending value.
2. Uniqueness of Keys :- Each Key in a map is unique.
The LinkedHashMap Class is just like HashMap with an additional feature of maintaining an order of
elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it
never maintained the track and order of insertion, which the LinkedHashMap provides where the elements
can be accessed in their insertion order.
Important Features of a LinkedHashMap are listed as
follows:

Here, K is the key Object type and V is the value Object type
K – The type of the keys in the map.
V – The type of values mapped in the map.
It implements Map<K, V> interface, and extends HashMap<K, V> class.
Though the Hierarchy of LinkedHashMap is as depicted as follows:
A LinkedHashMap is an extension of the HashMap class and it implements
the Map interface.Therefore, the class is declared as:
In this class, the data is stored in the form of nodes. The implementation
of the LinkedHashMap is very similar to a doubly-linked list. Therefore,
each node of the LinkedHashMap is represented as:
The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a
key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must
implement the hashCode method and the equals method.

The java.util.Hashtable class is a class in Java that provides a key-value data structure, similar to the Map
interface. It was part of the original Java Collections framework and was introduced in Java 1.0.

However, the Hashtable class has since been considered obsolete and its use is generally discouraged. This is
because it was designed prior to the introduction of the Collections framework and does not implement the
Map interface, which makes it difficult to use in conjunction with other parts of the framework. In addition, the
Hashtable class is synchronized, which can result in slower performance compared to other implementations
of the Map interface.

In general, it’s recommended to use the Map interface or one of its implementations (such as HashMap or
ConcurrentHashMap) instead of the Hashtable class.
It is similar to HashMap, but is synchronized.
Hashtable stores key/value pair in hash table.
In Hashtable we specify an object that is used as a key, and the value
we want to associate to that key.The key is then hashed, and the
resulting hash code is used as the index at which the value is
stored within the table.
HashMap doesn’t provide any Enumeration, while Hashtable provides not
fail-fast Enumeration.
Whenever we do hear sorting algorithms come into play such as selection sort,
bubble sort, insertion sort, radix sort, bucket sort, etc but if we look closer here we
are not asked to use any kind of algorithms.

It is as simple sorting with the help of linear and non-linear


data structures present within java.
So there is sorting done with the help of brute force in java with the help of loops

Ways of sorting in Java

1. Using loops
2. Using sort() method of Arrays class
3. Using sort method of Collections class
4. Sorting on a subarray
Java Comparable interface is used to order the objects of the user-defined class.
This interface is found in java.lang package and contains only one method named
compareTo(Object). It provides a single sorting sequence only, i.e., you can sort
the elements on the basis of single data member only. For example, it may be
rollno, name, age or anything else.
Collections class provides static methods for sorting the elements of collections.
If collection elements are of Set or Map, we can use TreeSet or TreeMap.
However, we cannot sort the elements of List. Collections class provides methods
for sorting the elements of List type elements.

public void sort(List list): It is used to sort the elements of List.


List elements must be of the Comparable type.

Note: String class and Wrapper classes implement the Comparable


interface by default. So if you store the objects of string or wrapper
classes in a list, set or map, it will be Comparable by default.
A comparator interface is used to order the objects of user-defined classes. A comparator object is
capable of comparing two objects of the same class. Following function compare obj1 with obj2.
Syntax:
public int compare(Object obj1, Object obj2):
Suppose we have an Array/ArrayList of our own class type, containing fields like roll no, name,
address, DOB, etc, and we need to sort the array based on Roll no or name?

Method 1: One obvious approach is to write our own sort() function using one of the standard
algorithms. This solution requires rewriting the whole sorting code for different criteria like Roll No.
and Name.

Method 2: Using comparator interface- Comparator interface is used to order the objects of a
user-defined class. This interface is present in java.util package and contains 2 methods
compare(Object obj1, Object obj2) and equals(Object element).
Using a comparator, we can sort the elements based on data members. For instance, it may be on
roll no, name, age, or anything else.
Method of Collections class for sorting List elements is used to sort the
elements of List by the given comparator.

public void sort(List list, ComparatorClass c)

To sort a given List, ComparatorClass must implement a Comparator


interface.
How do the sort() method of Collections class work?
Internally the Sort method does call Compare method of the classes it is
sorting. To compare two elements, it asks “Which is greater?”

Compare method returns -1, 0, or 1 to say if it is less than, equal, or


greater to the other. It uses this result to then determine if they should be
swapped for their sort.
Advantage of a Properties file

In the event that any data is changed from the properties record, you don’t have to recompile the
java class. It is utilized to store data that is to be changed habitually.

Note: The Properties class does not inherit the concept of a load factor from its superclass,

Hashtable Declaration
public class Properties extends Hashtable<Object,Object>

Constructors of Properties

1. Properties(): This creates a Properties object that has no default values.


Properties p = new Properties();

2. Properties(Properties propDefault): The second creates an object that uses propDefault


for its default value.
Properties p = new Properties(Properties propDefault);
Object Oriented Programming with Java
Unit :- 5
Spring Framework and Spring Boot

A Java framework is the body of predefined codes used by


programmers to develop applications on the web. These frameworks
in Java development are classes and functions that control hardware,
process input, and communicate with system applications.
SPRING FRAMEWORK
Spring framework makes the easy development of JavaEE application.

It is helpful for beginners and experienced persons.

Spring is a lightweight framework. It can be thought of as a framework of


frameworks because it provides support to various frameworks such

as Struts, Hibernate, Tapestry, EJB, JSF, etc.


The framework, in broader sense, can be defined as a structure where we find
solution of the various technical problems. The Spring framework comprises several
modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc.
There are many advantages of Spring Framework. They are as follows:

1) Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no
need to write too much code. It hides the basic steps of these technologies.
2) Loose Coupling
The Spring applications are loosely coupled because of dependency injection.
3) Easy to test
The Dependency Injection makes easier to test the application. The EJB or Struts application
require server to run the application but Spring framework doesn't require server.
4) Lightweight
Spring framework is lightweight because of its POJO implementation. The Spring Framework
doesn't force the programmer to inherit any class or implement any interface. That is why it is
said non-invasive.
5) Fast Development
The Dependency Injection feature of Spring Framework and it support to various frameworks
makes the easy development of JavaEE application.
6) Powerful abstraction
It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.
7) Declarative support
It provides declarative support for caching, validation, transactions and formatting.
There are two types of Spring Dependency Injection.

You can mix both, Constructor-based and Setter-based DI but it is a good rule of
thumb to use constructor arguments for mandatory dependencies and setters for
optional dependencies.
The code is cleaner with the DI principle and decoupling is more effective when
objects are provided with their dependencies. The object does not look up its
dependencies and does not know the location or class of the dependencies,
rather everything is taken care by the Spring Framework.
Inversion of Control is a principle in software engineering which transfers the
control of objects or portions of a program to a container or framework. We most
often use it in the context of object-oriented programming.

Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects,
configures and assembles their dependencies, manages their entire life cycle. The Container uses
Dependency Injection(DI) to manage the components that make up the application. It gets the
information about the objects from a configuration file(XML) or Java Code or Java Annotations and
Java POJO class. These objects are called Beans. Since the Controlling of Java objects and their
lifecycle is not done by the developers, hence the name Inversion Of Control. The followings are
some of the main features of Spring IoC,

· Creating Object for us,


· Managing our objects,
· Helping our application to
be configurable,
· Managing dependencies
AOP
Aspect oriented programming(AOP) as the name suggests uses aspects in programming.
It can be defined as the breaking of code into different modules, also known as modularisation, where
the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns
such as- transaction, logging not central to business logic without cluttering the code core to its
functionality. It does so by adding additional behaviour that is the advice to the existing code.
For example- Security is a crosscutting concern, in many methods in an application security rules can
be applied, therefore repeating the code at every method, define the functionality in a common class
and control were to apply that functionality in the whole application.

Dominant Frameworks in AOP:

AOP includes programming methods and frameworks on


which modularisation of code is supported and
implemented.

Let’s have a look the three dominant frameworks in AOP


· AspectJ: It is an extension for Java programming created at PARC research centre. It uses
Java like syntax and included IDE integrations for displaying crosscutting structure. It
has its own compiler and weaver, on using it enables the use of full AspectJ language.
· JBoss: It is an open source Java application server developed by JBoss, used for Java
development.
· Spring: It uses XML based configuration for implementing AOP, also it uses annotations which
are interpreted by using a library supplied by AspectJ for parsing and matching.
Currently, AspectJ libraries with Spring framework are dominant in the market, therefore let’s
have an understanding of how Aspect-oriented programming works with Spring.

How Aspect-Oriented Programming works with Spring:


One may think that invoking a method will automatically implement cross-cutting concerns but
that is not the case. Just invocation of the method does not invoke the advice(the job which is
meant to be done).
Spring uses proxy based mechanism i.e. it creates a proxy Object which will wrap around the
original object and will take up the advice which is relevant to the method call. Proxy objects can
be created either manually through proxy factory bean or through auto proxy configuration in the
XML file and get destroyed when the execution completes.
Proxy objects are used to enrich the Original behaviour of the real object.
A cross-cutting concern is a concern that can affect the whole application
and should be centralized in one location in code as possible, such as
transaction management, authentication, logging, security etc.

Common terminologies in AOP:

1. Aspect: The class which implements the JEE application cross-cutting concerns(transaction, logger
etc) is known as the aspect. It can be normal class configured through XML configuration
or through regular classes annotated with @Aspect.

2. Weaving: The process of linking Aspects with an Advised Object. It can be done at load
time, compile time or at runtime time. Spring AOP does weaving at runtime.
BEAN SCOPE
Bean Definition: In Spring, the objects that form the backbone
of your application and that are managed by the Spring IoC
container are called beans. A bean is an object that is
instantiated, assembled, and otherwise managed by a Spring IoC
container

Bean Scopes refers to the lifecycle of Bean that means when the object of Bean will be
instantiated, how long does that object live, and how many objects will be created for that bean
throughout. Basically, it controls the instance creation of the bean and it is managed by the spring
container.
The following are the different scopes provided for a bean:
1. Singleton: Only one instance will be created for a single bean definition per Spring IoC container and the same object will be
shared for each request made for that bean.
2. Prototype: A new instance will be created for a single bean definition every time a request is made for that bean.
3. Request: A new instance will be created for a single bean definition every time an HTTP request is made for that bean.
But Only valid in the context of a web-aware Spring ApplicationContext.
4. Session: Scopes a single bean definition to the lifecycle of an HTTP Session. But Only valid in the context of a web-aware
Spring ApplicationContext.
5. Global-Session: Scopes a single bean definition to the lifecycle of a global HTTP Session. It is also only valid in the context
of a web-aware Spring ApplicationContext.
Autowiring in Spring
Autowiring in the Spring framework can inject dependencies automatically. The Spring container
detects those dependencies specified in the configuration file and the relationship between the beans.
This is referred to as Autowiring in Spring. To enable Autowiring in the Spring application we should
use @Autowired annotation. Autowiring in Spring internally uses constructor injection. An autowired
application requires fewer lines of code comparatively but at the same time, it provides very little
flexibility to the programmer.

No control of programmer.
Annotations
Annotations are a form of metadata that provides data about a program. Annotations are used to
provide supplemental information about a program. It does not have a direct effect on the operation of
the code they annotate. It does not change the action of the compiled program. So, we are going to
discuss what are the main types of annotation that are available in the spring framework .
Use of java annotations
Java annotations are mainly used for the following:
· Compiler instructions
· Build-time instructions
· Runtime instructions

Compiler instructions: Java provides the 3 in built annotations which are used to give certain instructions to the
compiler. Java in built annotation are @Deprecated, @Override & @SuppressWarnings.
Build-time instructions: Java annotations can be used for build time or compile time instructions. These
instructions can be used by the build tools for generating source code, compiling the
source, generating XML files, packaging the compiled code and files into a JAR file etc.
Runtime instructions: Normally, Java annotations are not present in your Java code after compilation. However, we
can define our own annotations that can be available at runtime. These annotations can be
accessed using Java Reflection.
The following image shows the process flow of the bean life cycle.

Bean Life Cycle Process Flow


Note: We can choose a custom method name instead
of init() and destroy(). Here, we will use init() method to execute all its
code as the spring container starts up and the bean is instantiated, and
destroy() method to execute all its code on closing the container.

1.Spring bean life cycle involves initialization and destruction callbacks and Spring bean
aware classes.
2. Initialization callback methods execute after dependency injection is completed. Their
purposes are to check the values that have been set in bean properties, perform any
custom initialization or provide a wrapper on original bean etc. Once the initialization
callbacks are completed, bean is ready to be used.
3. When IoC container is about to remove bean, destruction callback methods execute.
Their purposes are to release the resources held by bean or to perform any other
finalization tasks.
4. When more than one initialization and destructions callback methods have been
implemented by bean, then those methods execute in certain order.
BEAN CONFIGURATION STYLE
Spring Framework provides three ways to configure beans to be used in the application.

1. Annotation Based Configuration - By using @Service or @Component annotations.


Scope details can be provided with @Scope annotation.

2. XML Based Configuration - By creating Spring Configuration XML file to configure


the beans. If you are using Spring MVC framework, the xml based configuration can be
loaded automatically by writing some boiler plate code in web.xml file.

3. Java Based Configuration - Starting from Spring 3.0, we can configure Spring beans
using java programs. Some important annotations used for java based configuration
are @Configuration, @ComponentScan and @Bean.
Spring Boot is most commonly used and contains all Spring Framework features.
Nowadays Spring Boot is becoming the best choice for Java developers to build rapid
Spring applications. When Java Developers use Spring Boot for developing applications
then they will focus on the logic instead of struggling with the configuration setup
environment of the application.

In Spring Boot, choosing a build system is an important task. We recommend


Maven or Gradle as they provide a good support for dependency management.
Spring does not support well other build systems.
SPRING BOOT CODE STRUCTURE

Note: It is recommended to use Java’s package


naming conventions with a reverse domain name.
Rest Controller
When building robust APIs, understanding and appropriately utilizing the HTTP methods GET, POST, PUT, and
DELETE is essential. Each method serves a specific purpose and has its own limitations. We will explore these
HTTP methods, their characteristics, and discuss their limitations in the context of building robust APIs. Additionally,
we will provide Java code examples to demonstrate their usage.

HTTP methods, also known as HTTP verbs, are a set of standardized actions that can be performed on a resource
using the Hypertext Transfer Protocol (HTTP). These methods define the intended operation to be performed on the
resource and provide a uniform way of interacting with web servers. The most commonly used HTTP methods are
GET, POST, PUT, and DELETE, but there are other methods as well, such as PATCH, HEAD, and OPTIONS.

HTTP methods are important for several reasons:

By understanding and utilizing the appropriate HTTP methods, developers can build robust and well-designed
APIs that adhere to the principles of HTTP and REST. This ensures consistency, interoperability, and efficiency
in the communication between clients and servers.
Below we will elaborate more on the most commonly used HTTP methods.
Here are some key points to consider when working with the GET method in API development:
The POST method is one of the HTTP methods used for submitting data to be processed by the server.
Unlike the GET method, which is used for retrieving data, the POST method is intended for data
submission and can cause modifications on the server. Here are some important points to consider when
working with the POST method:
The PUT method is an HTTP method used for updating or replacing a resource on the server. It is
idempotent, meaning that multiple identical PUT requests should have the same outcome. Here are
some important points to consider when working with the PUT method:

In the provided Java code example, a PUT request is sent to https://api.example.com/resource with a request body containing the updated
data. The data is written to the request output stream, and the response code is checked to handle the response accordingly.
When using the PUT method, it is important to handle concurrency and data consistency issues appropriately. For example, you may use optimistic
locking mechanisms or versioning to ensure that updates do not conflict with other concurrent modifications to the resource.
Remember to use the appropriate HTTP method based on the intended operation. While the GET method is used for retrieving data and the POST
method is used for submitting data, the PUT method is suitable for updating existing resources on the server.
The DELETE method is an HTTP method used for deleting a specified resource on the server. It is
used to remove a resource permanently from the server. Here are some important points to consider
when working with the DELETE method:

In the provided Java code example, a DELETE request is sent to https://api.example.com/resource/123, where “123” represents the identifier of the
resource to be deleted. The response code is checked to handle the success or failure of the deletion operation.
When using the DELETE method, it is important to implement proper authorization and authentication mechanisms to prevent unauthorized deletions.
Additionally, consider providing proper error handling and feedback to the client in case of failures or errors during the deletion process.
Remember to use the appropriate HTTP method based on the intended operation. While the GET method is used for retrieving data, the POST method is
used for submitting data, the PUT method is used for updating data, the DELETE method is specifically designed for resource deletion.
One of the most important annotations in spring is the @RequestMapping Annotation which
is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC
applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP
requests to handler methods of controllers. When configuring Spring MVC, you need to specify the
mappings between the requests and handler methods.
What is Request Body?
Data sent over the request body can be of any format like json, XML, PDF, Http Forms, and many more. The Content-
Type header indicates the server's understanding type of request.
Spring provides @RequestBody annotation to deserialize the incoming payload into java object or map.
The request body goes along with content-type header for handler method to understand and deserialize the payload.

How to Get the Body of Request in Spring Boot?


Java language is one of the most popular languages among all programming languages. There are several
advantages of using the Java programming language, whether for security purposes or building large
distribution projects. One of the advantages of using Java is that Java tries to connect every concept in the
language to the real world with the help of the concepts of classes, inheritance, polymorphism, etc.
There are several other concepts present in Java that increase the user-friendly interaction between the Java
code and the programmer such as generic, Access specifiers, Annotations, etc. These features add an extra
property to the class as well as the method of the Java program. In this article, we will discuss how to get the
body of the incoming request in the spring boot.

@RequestBody: Annotation is used to get the request body in the incoming request.
Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot
project. It also provides various features for the projects expressed in a metadata model. This model allows us
to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an
application using a spring initializer and then use an IDE to create a sample GET route. Therefore, to do this,
the following steps are followed sequentially as follows:
Path variable in spring boot
The @PathVariable annotation is used to retrieve data from the URL path. By defining
placeholders in the request mapping URL, you can bind those placeholders to method
parameters annotated with @PathVariable. This allows you to access dynamic values from the
URL and use them in your code.
The @PathVariable annotation is used to retrieve data from the URL path. By defining placeholders in
the request mapping URL, you can bind those placeholders to method parameters annotated with
@PathVariable. This allows you to access dynamic values from the URL and use them in your code.
The @PathVariable annotation is used to extract data from the URL path.
It allows you to define placeholders in your request mapping URL and bind
those placeholders to method parameters.
Build Web Applications
Java is one of the most used programming languages for developing dynamic web applications. A web application
is computer software that utilizes the web browser and technologies to perform tasks over the internet. A web
application is deployed on a web server.
Java provides some technologies like Servlet and JSP that allow us to develop and deploy a web application on a
server easily. It also provides some frameworks such as Spring, Spring Boot that simplify the work and provide an
efficient way to develop a web application. They reduce the effort of the developer.
We can create a website using static HTML pages and style them using CSS, but we need server-side technology
when we want to create a dynamic website

A web application is computer software that can be accessed using any web browser. Usually, the frontend of
a web application is created using the scripting languages such as HTML, CSS, and JavaScript, supported
by almost all web browsers. In contrast, the backend is created by any of the programming languages such
as Java, Python, Php, etc., and databases. Unlike the mobile application, there is no specific tool for
developing web applications; we can use any of the supported IDE for developing the web application.
We use the concept of MVC, i.e., Model-View-Controller.
MVC is an architecture that separates various
components of an application like the Input Logic,
Business Logic, and UI Logic.
The views and the models don’t interact with each other.
The controller receives the request from the view and
gets the required details from the model and transfers it

AT THE END YOUR TASK :-


Build a Web Application
using Java , Spring etc.

For E.g:- To do List ,


Calculator etc.

You might also like