QuestionBank JAVA BCS403
QuestionBank JAVA BCS403
IT DEPARTMENT
SUB: OOPS WITH JAVA SUB CODE: BCS 403
QUESTION BANK
Q1. What is the difference between an Inner Class and a Sub-Class.
Ans: An Inner class is a class which is nested within another class. An Inner class has access
rights for the class which is nesting it and it can access all variables and methods defined in the
outer class .A sub-class is a class which inherits from another class called super class. Sub-class
can access all public and protected methods and fields of its super class.
Q2. What are the various access specifiers for Java classes.
Ans: In Java, access specifiers are the keywords used before a class name which defines the
access scope. The types of access specifiers for classes are:
1.Public: Class,Method,Field is accessible from anywhere.
2.Protected: Method, Field can be accessed from the same class to which they belong or from the
sub-classes ,and from the class of same package, but not from outside.
3.Default: Method, Field, class can be accessed only from the same package and not
from outside of its native package.
4. Private: Method, Field can be accessed from the same class to which they belong.
Ans: When there is a requirement to share a method or a variable between multiple objects of a
class instead of creating separate copies for each object, we use static keyword to make a method
or variable shared for all objects.
Ans: Encapsulation is a concept in Object Oriented Programming for combining properties and
methods in a single unit .Encapsulation helps programmers to follow a modular approach for
software development as each object has its own set of methods and variables and serves its
functions independent of other objects. Encapsulation also serves data hiding purpose.
A singleton class in java can have only one instance and hence all its methods and variables
belong to just one instance. Singleton class concept is useful for the situations when there is a
need to limit the number of objects for a class.
Q6. What’s the difference between an Abstract Class and Interface in Java.
Ans: The primary difference between an abstract class and interface is that an interface can only
possess declaration of public static methods with no concrete implementation while an abstract
class can have members with any access specifiers (public, private etc) with or without concrete
implementation. Another key difference in the use of abstract classes and interfaces is that a class
which implements an interface must implement all the methods of the interface while a class
which inherits from an abstract class doesn’t require implementation of all the methods of
Its super class.
Q10. What will happen if we declare don’t declare the main as static.
We can declare the main method without using static and without getting any errors. But, the
main method will not be treated as the entry point to the application or the program.
Q11) Write a Java program that throws an exception and catch it using a try-catch block.
Ans) public class Exception_Example {
public static void main(String[] args) {
try {
int result = divideNumbers(5, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static int divideNumbers(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Cannot divide the given number by zero!");
}
return dividend / divisor;
}
}
Q12) Write a Java program to create a method that reads a file and throws an exception if
the file is not found.
Ans) import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
scanner.close();
}
}
Q13) what is Exception handling.
Ans) An exception is an error event that can happen during the execution of a program and
disrupts its normal flow. The exception can arise from different kinds of situations such as wrong
data entered by the user, hardware failure, network connection failure, etc. Whenever any error
occurs while executing a java statement, an exception object is created, and then JRE tries to find
an exception handler to handle the exception. If a suitable exception handler is found then the
exception object is passed to the handler code to process the exception, known as catching the
exception. If no handler is found then the application throws the exception to the runtime
environment and JRE terminates the program. Java Exception handling framework is used to
handle runtime errors only, compile-time errors are not handled by exception handling
framework.
import java.io.IOException;
Q18) what is the concept of Byte stream and Character Stream in Java. How reading and
writing files will be done.
Ans) A stream is a way of sequentially accessing a file. A byte stream access the file byte by
byte. A byte stream is suitable for any kind of file, however not quite appropriate for text files.
For example, if the file is using a unicode encoding and a character is represented with two
bytes, the byte stream will treat these separately and you will need to do the conversion yourself.
A character stream will read a file character by character. A character stream needs to be given
the file's encoding in order to work properly.
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are
descended from InputStream and OutputStream.
The java.io package is used for file handling in Java. It provides various classes for handling
files, such as File, FileReader, FileWriter, FileInputStream, and FileOutputStream.
Ans) A Program in the execution is called the process whereas; A thread is a subset of the
process
A thread can have one of the following states during its lifetime:
1. New: In this state, a Thread class object is created using a new operator, but the thread is
not alive. Thread doesn't start until we call the start() method.
2. Runnable: In this state, the thread is ready to run after calling the start() method.
However, the thread is not yet selected by the thread scheduler.
3. Running: In this state, the thread scheduler picks the thread from the ready state, and the
thread is running.
4. Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for
the other thread to finish.
5. Dead/Terminated: A thread is in terminated or dead state when the run() method exits.
Q21) What are Java functional interfaces, and how do they contribute to the paradigm
shift towards functional programming within the Java ecosystem.
In Java, a functional interface is an interface that contains only one abstract method. These
interfaces facilitate the implementation of lambda expressions, which are concise representations
of anonymous functions. Java's functional interfaces are annotated with the
@FunctionalInterface annotation, which ensures that they abide by the single abstract method
constraint.
@FunctionalInterface Annotation: While not strictly required, it's a good practice to annotate
functional interfaces with @Functional Interface. This annotation ensures that the interface has
only one abstract method. If you accidentally add another abstract method to an interface
annotated with @FunctionalInterface, the compiler will raise an error.
Purpose: Functional interfaces serve as the cornerstone for leveraging functional programming
concepts within Java. By enabling the use of lambda expressions, they allow developers to write
more expressive, concise, and readable code.
Contributions to Functional Programming: Java's adoption of functional interfaces marks a
significant step towards embracing functional programming paradigms. Functional programming
emphasizes the use of pure functions, immutability, and higher-order functions. While Java
remains primarily an object-oriented language, the incorporation of functional interfaces enables
developers to apply functional programming principles where appropriate, promoting cleaner
and more modular code.
Lambda Expressions and Stream API: Functional interfaces are closely intertwined with
lambda expressions, which provide a concise syntax for defining anonymous functions. Lambda
expressions, in conjunction with functional interfaces, form the backbone of Java's Stream API.
Streams enable developers to process collections of data in a functional style, facilitating
operations such as mapping, filtering, and reducing with ease and efficiency.
Parallelism and Concurrency: The functional programming paradigm encourages stateless
operations and immutability, which inherently support parallelism and concurrency. Java's
functional interfaces, when combined with parallel streams, empower developers to exploit
multicore processors effectively, thereby enhancing the performance of their applications.
Enhanced Expressiveness and Readability: By leveraging functional interfaces and lambda
expressions, developers can express their intent more clearly and concisely. This leads to code
that is easier to understand, maintain, and reason about. Functional programming constructs
encourage declarative rather than imperative programming styles, resulting in code that focuses
on what needs to be done rather than how it should be done.
Q22) what is functional interface. Explain with suitable example.
A functional interface in Java is an interface that contains exactly one abstract method. It may
contain any number of default methods or static methods, but it must have only one abstract
method.
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
@FunctionalInterface annotation ensures that Calculator is indeed a functional interface. While
this annotation is not mandatory, it's good practice to use it for clarity and to prevent accidental
addition of more abstract methods.
Calculator interface has a single abstract method calculate that takes two integer parameters a
and b and returns an integer result.
We can provide different implementations of the calculate method using lambda expressions.
Here's how we can use the Calculator functional interface with lambda expressions:
public class Main {
public static void main(String[] args) {
// Addition using lambda expression
Calculator addition = (a, b) -> a + b;
int sum = addition.calculate(5, 3); // Output: 8
System.out.println("Sum: " + sum);
Conciseness: Lambda expressions allow you to express behavior more concisely compared to
traditional anonymous inner classes. They help reduce boilerplate code, making the code base
more readable and maintainable.
Expressiveness: Lambda expressions enhance code expressiveness by enabling developers to
focus on the what (the behavior) rather than the how (the implementation details). This leads to
more declarative and understandable code.
Readability: Lambda expressions often result in more readable code, especially when used in
conjunction with functional interfaces. They can make the code more self-explanatory by clearly
indicating the intention behind certain operations.
Stream API: Lambda expressions are extensively used in Java's Stream API, which provides a
powerful way to process collections of data in a functional style. Streams enable operations such
as mapping, filtering, and reducing, and lambda expressions are used to specify the behaviour for
these operations succinctly.
Q25) Explain the concept of Base64 encoding and decoding in detail, covering its purpose,
principles, and applications in computer science and beyond.
Email Attachments: Base64 encoding is commonly used to encode email attachments, such as
images or documents, for transmission over SMTP servers.
Data URI Scheme: In web development, Base64 encoding is employed to embed binary data,
such as images or fonts, directly into HTML or CSS files using the data URI scheme.
Suppose we have a list of strings, and we want to print each element of the list using the forEach
method:
import java.util.ArrayList;
import java.util.List;
Suppose we have a file that we want to read using BufferedReader. With try-with-resources, we
can ensure that the file is closed properly after reading, even if an exception occurs.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Here, var is a reserved keyword indicating that the type of the variable will be inferred by the
compiler. variableName is the name of the variable, and initializerExpression is the expression
used to initialize the variable.
Consider the following example:
var message = "Hello, world!";
In this example, the type of the variable message is inferred to be String based on the initializer
expression "Hello, world!".
Benefits of Local Variable Type Inference:
Conciseness: Local variable type inference reduces boilerplate code by allowing you to omit
explicit type declarations, making the code more concise and readable.
Flexibility: It allows you to focus on the intent of the code rather than the specific types,
enhancing code readability and maintainability.
Compatibility: It is backward-compatible with existing code, as it does not introduce any
changes to the underlying type system or bytecode representation.
Encapsulation: It encourages encapsulation by reducing the visibility of implementation details,
as the type of the variable is inferred locally and does not need to be exposed.
Q31) what is java Collection framework? List out some benefits of collection framework
and Explain it.
1. The Java Collections
Framework is a set of classes
and interfaces that provide a
2. unified way to store and
manipulate collections of
objects in Java. The
Collections
3. Framework includes classes
for representing different
types of collections, such as
4. lists, sets, and maps. It also
includes classes for
performing operations on
5. collections, such as sorting,
searching, and iterating.
Collections are used in every programming language and initial java release contained few
classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger scope and
usage, Java 1.2 came up with Collections Framework that group all the collections interfaces,
implementations and algorithms. Java Collections have come through a long way with the usage
of Generics and Concurrent Collection classes for thread-safe operations. It also includes
blocking interfaces and their implementations in java concurrent package. Some of the benefits
of collections framework are;
Reduced development effort by using core collection classes rather than implementing our own
collection classes.
Code quality is enhanced with the use of well tested collections framework classes.
Reduced effort for code maintenance by using collection classes shipped with JDK.
Reusability and Interoperability
Example Usage
import java.util.*;
list.add("Apple");
list.add("Banana");
list.add("Cherry");
Collections.sort(list);
// Set Example
set.add("Apple");
set.add("Banana");
// Map Example
map.put("Apple", 1);
map.put("Banana", 2);
}
In this example, a List is used to store and sort elements, a Set is used to store unique elements, and a
Map is used to store key-value pairs. The Java Collection Framework makes it easy to perform these
common operations with minimal effort.
Ans: In Java, both ArrayList and LinkedList implement the List interface, but they have
different underlying data structures and performance characteristics.
ArrayList
Underlying Data Structure
Performance Characteristics
Use Case
● Best suited for applications where frequent access to elements via index is required.
● Ideal for read-heavy operations where the list size is relatively stable.
Example
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
LinkedList
Underlying Data Structure
● LinkedList is implemented as a doubly linked list where each element is a node containing data
and pointers to the previous and next nodes.
Performance Characteristics
● Access Time: O(n) - Requires traversal from the beginning or end of the list to access elements.
● Insertion/Deletion: O(1) - Adding or removing elements from the beginning or end of the list is
efficient; in the middle, it requires traversal but no shifting.
● Memory Consumption: More overhead due to storing pointers to next and previous nodes.
Use Case
● Best suited for applications where frequent insertion and deletion of elements occur, especially
at the beginning or end of the list.
● Ideal for write-heavy operations where the list size changes frequently.
Example
linkedList.add("Apple");
linkedList.add("Banana");
linkedList.add("Cherry");
Summary of Differences
Feature ArrayList LinkedList
Access Time O(1) for random access O(n) for random access
Insertion/Deletion O(n) for middle operations (requires O(1) for middle operations (no shifting,
Time shifting) just pointer updates)
Best for read-heavy scenarios with Best for write-heavy scenarios with
Use Case
infrequent insertions/deletions frequent insertions/deletions
● Use ArrayList when you need fast random access and your application does not require frequent
insertion/deletion operations.
● Use LinkedList when you need efficient insertion and deletion operations, especially at the
beginning or end of the list, and random access is less critical.
Q33) Discuss differences between HashList and HashMap, Set and List.
Ans: In Java, HashMap, HashSet, and List are commonly used data structures with distinct
characteristics and use cases. Here's a detailed comparison:
HashMap
Description
Key Features
Use Case
● Best suited for scenarios where you need to associate unique keys with specific values and
require fast lookup based on the key.
Example
java
Copy code
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Apple", 1);
hashMap.put("Banana", 2);
System.out.println(hashMap.get("Apple")); // Output: 1
HashSet
Description
Key Features
● Best suited for scenarios where you need a collection of unique elements and require fast
operations for checking the presence of elements.
Example
java
Copy code
Set<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Apple"); // Duplicate element
System.out.println(hashSet); // Output: [Apple, Banana]
List (ArrayList and LinkedList)
Description
Key Features
Use Case
● Best suited for scenarios where you need an ordered collection of elements, may have
duplicates, and require access to elements by their index.
Example
java
Copy code
List<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Apple"); // Duplicate element
System.out.println(arrayList); // Output: [Apple, Banana, Apple]
Summary of Differences
Feature HashMap HashSet List (ArrayList/LinkedList)
Unique
Data Structure Key-value pairs Ordered collection of elements
elements
Feature HashMap HashSet List (ArrayList/LinkedList)
No duplicate keys,
Duplicates No duplicates Allows duplicates
values can repeat
Allows one null key, Allows one null Allows multiple null values (depending on
Null Values
multiple null values value implementation)
Average Time O(1) for basic O(1) for basic O(1) for ArrayList (random access), O(n) for
Complexity operations operations LinkedList (random access)
Unique
Use Case Key-value association Ordered collection with duplicates allowed
collection
● HashMap: Use when you need to map unique keys to specific values and require fast lookups,
insertions, and deletions.
● HashSet: Use when you need a collection of unique elements with no particular order.
● List: Use when you need an ordered collection that allows duplicates and requires access to
elements by their index. Choose ArrayList for fast random access and LinkedList for
frequent insertions and deletions.
Ans : In Java, both Comparator and Comparable interfaces are used to sort collections or arrays
of objects. However, they serve different purposes and are used in different contexts. Here’s a
detailed comparison of Comparator and Comparable:
Comparable
Description
● The Comparable interface is used to define the natural ordering of objects of a class. It is
implemented by the class whose objects need to be sorted.
Key Features
● Single Sort Sequence: A class can implement Comparable to provide a single way of sorting its
instances.
● Method to Implement: The compareTo() method must be overridden.
● Used In: Arrays.sort() and Collections.sort() when no Comparator is provided.
Syntax
java
Copy code
public class MyClass implements Comparable<MyClass> {
private int value;
@Override
public int compareTo(MyClass other) {
return Integer.compare(this.value, other.value);
}
}
Example
java
Copy code
List<MyClass> list = new ArrayList<>();
list.add(new MyClass(3));
list.add(new MyClass(1));
list.add(new MyClass(2));
● The Comparator interface is used to define multiple ways of sorting objects. It is typically
implemented in a separate class and can be passed to sorting methods.
Key Features
● Multiple Sort Sequences: A class can have multiple Comparator implementations to sort
objects in different ways.
● Method to Implement: The compare() method must be overridden.
● Used In: Arrays.sort() and Collections.sort() when a Comparator is provided.
Syntax
java
Copy code
public class MyClass {
private int value;
Method to
compareTo(T o) compare(T o1, T o2)
Implement
Sorting Logic
Defined within the class itself Defined in a separate class
Location
Number of
Single natural ordering Multiple custom orderings
Sorting Sequences
Modification Requires modifying the class Does not require modifying the class
Q34) Explain Hashtable class in java. Write a program to illustrate the use of Hashtable
class for storing and retrieving employee record.
Ans: The Hashtable class in Java is part of the java.util package and provides a means to
store key-value pairs in a hash table data structure. It is similar to the HashMap class, but with
some key differences, primarily regarding synchronization and how it handles nulls.
Key Characteristics of Hashtable
1. Synchronized:
o Hashtable is synchronized, meaning it is thread-safe. Multiple threads can access a
Hashtable without causing concurrency issues. This makes it suitable for use in
multi-threaded environments.
2. Null Keys and Values:
o Hashtable does not allow null keys or values. Attempting to insert a null key or value
will result in a NullPointerException.
3. Legacy Class:
o Hashtable is a legacy class that was part of the original version of Java. It has been
retrofitted to implement the Map interface but still retains some of its original design
characteristics.
4. Performance:
o Due to its synchronized nature, Hashtable can be slower than HashMap when only one
thread is accessing it. For non-thread-safe environments, HashMap is typically preferred
due to its better performance.
import java.util.Hashtable;
if (employees.containsKey(searchID)) {
} else {
}
// Remove an employee record
employees.remove(removeID);
Ans: Accessing a collection through an iterator in Java allows you to traverse the collection and
access its elements sequentially without exposing the underlying structure. The Iterator
interface provides methods to iterate over any collection that implements the Iterable interface,
such as ArrayList, HashSet, HashMap, etc.
Key Methods of the Iterator Interface
1. hasNext():
o Returns true if the iteration has more elements.
o Returns false when all elements have been accessed.
2. next():
o Returns the next element in the iteration.
o Throws NoSuchElementException if there are no more elements.
3. remove():
o Removes the last element returned by the iterator.
o Can be called only once per call to next().
o Throws UnsupportedOperationException if the remove operation is not supported
by the iterator.
Example: Using an Iterator with an ArrayList
Here’s an example of how to use an Iterator to traverse an ArrayList:
java
Copy code
import java.util.ArrayList;
import java.util.Iterator;
Ans: In Java, a "cursor" is a concept that allows traversal or iteration over the elements of a
collection. Cursors are interfaces provided by the Java Collections Framework that enable
navigating through the elements of collections like lists, sets, and maps. The primary cursor
interfaces in Java are Iterator, ListIterator, and Enumeration.
Types of Cursors in Java
1. Iterator
2. ListIterator
3. Enumeration
1. Iterator
Description:
● The Iterator interface provides a way to traverse elements of a collection sequentially without
exposing its underlying representation.
Key Methods:
Usage:
● Suitable for any collection that implements the Iterable interface, including ArrayList,
HashSet, and HashMap.
Example:
java
Copy code
import java.util.ArrayList;
import java.util.Iterator;
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
if (element.equals("Banana")) {
iterator.remove();
}
}
● The ListIterator interface extends Iterator and provides additional methods to traverse
the list in both forward and backward directions.
Key Methods:
● hasNext(): Returns true if the list iterator has more elements when traversing forward.
● next(): Returns the next element in the list.
● hasPrevious(): Returns true if the list iterator has more elements when traversing backward.
● previous(): Returns the previous element in the list.
● add(E e): Inserts the specified element into the list.
● set(E e): Replaces the last element returned by next() or previous() with the specified
element.
Usage:
System.out.println("Forward traversal:");
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
System.out.println("Backward traversal:");
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}
3. Enumeration
Description:
● The Enumeration interface provides methods to enumerate (obtain one at a time) through a
collection of elements.
Key Methods:
Usage:
Example:
java
Copy code
import java.util.Vector;
import java.util.Enumeration;
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
}
}
Summary
Modify Supports
Cursor Traversal Direction Suitable For
Collection List
Each cursor type has its use case depending on the collection and the type of traversal required.
Iterator is versatile and can be used with any collection, while ListIterator provides
additional functionality for lists, and Enumeration is mainly for legacy classes.
Ans: In Java, the Map interface is part of the Java Collections Framework and represents a
collection of key-value pairs. Each key in a Map is unique, and each key maps to exactly one
value. The Map interface is implemented by various classes such as HashMap, TreeMap,
LinkedHashMap, and Hashtable.
Example Usage
java
Copy code
import java.util.HashMap;
import java.util.Map;
Summary
● Map:
o Designed for key-value pairs.
o Keys are unique.
o Provides methods to access keys, values, and key-value pairs.
o Not a subtype of Collection.
● Collection:
o Designed for storing individual elements.
o Includes subtypes like List, Set, and Queue.
o Provides methods to add, remove, and access elements.
o Allows different rules for duplicates and ordering depending on the specific
implementation (e.g., ArrayList, HashSet).
The choice between using a Map or a Collection depends on the specific requirements of the
data structure you need, such as whether you need to associate keys with values or store
individual elements.
Ans: The Properties class in Java is part of the java.util package and extends the Hashtable
class. It is used to maintain lists of key-value pairs where both keys and values are String
objects. The Properties class is commonly used for configuration settings and for managing
application properties.
Key Characteristics of Properties
1. Key-Value Pairs:
o Stores data as key-value pairs, both of which are String objects.
2. Default Properties:
o Can have a set of default properties that provide default values.
3. Persistence:
o Provides methods to read from and write to properties files, which are plain text files
with key-value pairs.
4. Usage:
o Commonly used for configuration files, environment settings, and internationalization
(i18n) support.
// Accessing properties
String username = properties.getProperty("username");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
// Modifying properties
properties.setProperty("username", "newAdmin");
properties.setProperty("password", "newSecret");
Summary
● The Properties class is a powerful tool for handling configuration and application settings in
Java.
● It supports easy reading and writing of properties files.
● It ensures that key-value pairs are always strings, simplifying data handling.
● It can be used in various contexts such as setting application parameters, managing
internationalization (i18n) resources, and more.
Key Methods
● add(E e): Adds the specified element to the set if it is not already present.
● remove(Object o): Removes the specified element from the set if it is present.
● contains(Object o): Returns true if the set contains the specified element.
● size(): Returns the number of elements in the set.
● isEmpty(): Returns true if the set contains no elements.
Key Methods
Both Set and Queue interfaces provide specialized behaviors for handling collections of elements
with specific requirements regarding uniqueness and order of processing, respectively. They are
integral parts of the Java Collections Framework and offer various implementations tailored to
different use cases.
Spring Framework:
● 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.
Dependency Lookup
The Dependency Lookup is an approach where we get the resource after demand. There can be
various ways to get the resource for example:
A obj = new AImpl();
In such way, we get the resource(instance of A class) directly by new keyword. Another way is
factory method:
A obj = A.getA();
This way, we get the resource (instance of A class) by calling the static factory method getA().
Problems of Dependency Lookup
There are mainly two problems of dependency lookup.
o tight coupling The dependency lookup approach makes the code tightly coupled. If resource
is changed, we need to perform a lot of modification in the code.
o Not easy for testing This approach creates a lot of problems while testing the application
especially in black box testing.
There three types of dependency Injections.
● Constructor injection: This is the most common type of DI in Spring Boot. In constructor
injection, the dependency object is injected into the dependent object’s constructor.
● Setter injection: In setter injection, the dependency object is injected into the dependent
object’s setter method.
● Field injection: In field injection, the dependency object is injected into the dependent
object’s field.
The IoC container is responsible to instantiate, configure and assemble the objects. The IoC
container gets information from the XML file and works accordingly. The main tasks performed
by IoC container are:
o to instantiate the application class
o to configure the object
o to assemble the dependencies between the objects
There are two types of IoC containers. They are:
1. BeanFactory
2. ApplicationContext
BeanFactory is the basic container whereas ApplicationContext is the advanced container.
ApplicationContext extends the BeanFactory interface. ApplicationContext provides more
facilities than BeanFactory such as integration with spring AOP, message resource handling for
i18n etc.
Q44) what is the difference between constructor injection and setter injection?
3) Creates new instance if any Doesn't create new instance if you change the
modification occurs property value
Autowiring enables the programmer to inject the bean automatically. We don't need to write
explicit injection logic.
Let's see the code to inject bean using dependency injection.
<bean id="emp" class="com.javatpoint.Employee" autowire="byName" />
2) Byname injects the bean based on the property name. It uses setter method.
3) byType injects the bean based on the property type. It uses setter method.
Bean Scopes
When defining a <bean> you have the option of declaring a scope for that bean. For example, to
force Spring to produce a new bean instance each time one is needed, you should declare the
bean's scope attribute to be prototype. Similarly, if you want Spring to return the same bean
instance each time one is needed, you should declare the bean's scope attribute to be singleton.
The Spring Framework supports the following five scopes, three of which are available only if
you use a web-aware ApplicationContext.
Sr.No
Scope & Description
.
Singleton
1 This scopes the bean definition to a single instance per Spring IoC container
(default).
Prototype
2
This scopes a single bean definition to have any number of object instances.
Request
3 This scopes a bean definition to an HTTP request. Only valid in the context of
a web-aware Spring ApplicationContext.
Session
4 This scopes a bean definition to an HTTP session. Only valid in the context of
a web-aware Spring ApplicationContext.
global-session
5 This scopes a bean definition to a global HTTP session. Only valid in the
context of a web-aware Spring ApplicationContext.
Q47) what is Spring Boot and what are its Benefits.
● A Java-based, open-source framework to create web applications, Spring Boot has been
dominating the web development landscape ever since the official release of Spring Boot
1.0.0 in April 2014.
● Because of its ability to simplify the process of developing complex applications, the
enterprise-grade Spring Boot framework is today among the most widely used Java-based
technologies to build scalable and robust web applications.
● Spring Boot represents a fusion of the lightweight Spring application framework,
configuration annotations, and embedded HTTP server.
● Made available with an auto-configuration feature, and support for Spring Initializer,
Groovy, and Java, Spring Boot reduces Integration Test, Development, and Unit Test
time.
● It aids the development of fast, responsive, and secure web applications, providing users
with a complete configuration and programming model for Java enterprise applications.
● Spring Boot, utilizing the core features of the Spring application framework, offers a
faster development technique for RESTful or REST architecture-based web services.
Q48) Why Spring Boot is preferred over any other framework? Describe the key
dependencies of Spring Boot.
The Spring cloud that comes with Spring Boot, includes vast libraries, which is one of the major
reasons why most developers prefer the Java-based Spring Boot. In addition, Spring Boot offers
superior compatibility with Spring frameworks, and it also provides excellent support for docker
containerization, heightening performance, and usability. Some of the most compelling reasons
for using Spring Boot include:
● Provides the best means to configure Java beans
● Offers robust batch processing
● Helps users effectively manage Representational State Transfer (REST) endpoints
● Integrates an auto-configuration tool, eliminating the need for manual configuration
● Enables annotation-based configurations
● Ease of dependency management
● Includes embedded servlet containers
Mentioned below are important Spring Boot dependencies that need to be added to a
Gradle-based or Maven-based application, to ensure application compatibility with Spring Boot
features.
● spring-boot-starter-parent
● spring-boot-maven-plugin
● spring-boot-starter-test
● spring-boot-starter-security
● spring-boot-starter-actuator
● Spring-boot-starter-web
Q49)Describe the flow of HTTPS requests through the Spring Boot application.
The flow of HTTPS requests through a Spring Boot application is as follows:
● First client makes an HTTP request (GET, POST, PUT, DELETE) to the browser.
● After that the request will go to the controller, where all the requests will be mapped and
handled.
● After this in Service layer, all the business logic will be performed. It performs the business
logic on the data that is mapped to JPA (Java Persistence API) using model classes.
● In repository layer, all the CRUD operations are being done for the REST APIs.
● A JSP page is returned to the end users if no errors are there.