OOPS With Java All 5 Units Notes
OOPS With Java All 5 Units Notes
AKTU
with Java
Subject Introduction
B.Tech 2nd Year 4th Sem
New Syllabus
Object Oriented Programming with Java
Unit :- 1
AKTU BCS-403
Introduction
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
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.
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.
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.
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.
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.
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.
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.
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.
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) 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,
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.
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.
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.
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.
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.
@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