Question Bank Java BCS 403
Question Bank Java BCS 403
Java (OOPJ)
Question Bank
BCS 403
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.
Unlike any other programming language like C, C++, etc. In Java, we declared the main
function as a public static void main (String args[]). The meanings of the terms are mentioned
below:
1. public: the public is the access modifier responsible for mentioning who can access
the element or the method and what is the limit. It is responsible for making the
main function globally available. It is made public so that JVM can invoke it from
outside the class as it is not present in the current class.
2. static: static is a keyword used so that we can use the element without initiating the
class so to avoid the unnecessary allocation of the memory.
3. void: void is a keyword and is used to specify that a method doesn’t return
anything. As the main function doesn’t return anything we use void.
4. main: main represents that the function declared is the main function. It helps JVM
to identify that the declared function is the main function.
5. String args[]: It stores Java command-line arguments and is an array of type
java.lang.String 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 {
readFile("test1.txt");
} catch (FileNotFoundException e)
{ System.out.println("Error: " + e.getMessage());
}
}
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.
String getMessage() - This method returns the message String of Throwable and the message can
be provided while creating the exception through its constructor.
String getLocalizedMessage() - This method is provided so that subclasses can override it to
provide the locale-specific messages to the calling program. Throwable class implementation of
this method simply use getMessage() method to return the exception message.
synchronized Throwable getCause() - This method returns the cause of the exception or null if
the cause is unknown.
String toString() - This method returns the information about Throwable in String format, the
returned String contains the name of Throwable class and localized message.
void printStackTrace() - This method prints the stack trace information to the standard error
stream, this method is overloaded and we can pass PrintStream or PrintWriter as an argument to
write the stack trace information to the file or stream.
Ans) We can extend Exception class or any of its subclasses to create our custom exception
class. The custom exception class can have its own variables and methods that we can use to
pass error codes or other exception-related information to the exception handler.
package com.journaldev.exceptions;
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
• Any change in Parent process doesn't affect the child process whereas changes in parent
thread can affect the child thread.
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.
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.
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 {
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:
Purpose:
The primary purpose of lambda expressions in Java is to enable the implementation of functional
interfaces, which serve as the foundation for functional programming constructs within the
language.
Key Benefits and Purposes of Lambda Expressions:
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.
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.
Base64 encoding is a method used to encode binary data into ASCII characters, making it
suitable for transmission over protocols that require text data. Conversely, Base64 decoding is
the process of converting encoded Base64 data back to its original binary form. This encoding
scheme is widely used in various applications, including email systems, web technologies,
cryptography, and data storage.
Base64 encoding works by dividing binary data into groups of 6 bits, which are then represented
using a set of 64 ASCII characters. Each group of 6 bits corresponds to one of the 64 characters,
resulting in a compact representation of binary data as text. The padding character '=' is often
added to ensure that the length of the encoded data is a multiple of 4, facilitating proper
decoding.
The primary purpose of Base64 encoding and decoding is to enable the transmission of binary
data over text-based channels, such as email, XML, or HTTP headers, where only ASCII
characters are allowed. By converting binary data to a text format, Base64 ensures that it can be
safely transmitted without loss of information or corruption.
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;
};
Example: We want to assign a message based on the day of the week using a switch
expression:
public class Main {
public static void main(String[] args)
{ int day = 3;
String message = switch (day)
{ case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
case 4 -> "Thursday";
case 5 -> "Friday";
default -> throw new IllegalArgumentException("Invalid day: " + day);
};
System.out.println("Message: " + message);
}
}
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
Alok Dwivedi Asst. Prof AITM CS ([email protected])
Axis Institute of Technology and Mgt.
DEPARTMENT: CSE
QUESTION BANK
SUB: OOPS WITH JAVA SUB CODE:
BCS 403
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
Alok Dwivedi Asst. Prof AITM CS ([email protected])
Axis Institute of Technology and Mgt.
DEPARTMENT: CSE
QUESTION BANK
SUB: OOPS WITH JAVA SUB CODE:
BCS 403
The Java Collections Framework is a set of classes and interfaces that provide a unified
way to store and manipulate collections of objects in Java. The Collections Framework
includes classes for representing different types of collections,such as lists, sets, and
maps. It also includes classes for performing operations on collections, such as sorting,
searching, and iterating.
The Java Collection Framework is a set of classes and interfaces that implement commonly
reusable collection data structures. It provides the architecture to store and manipulate a group of
objects in a standard way. The framework includes implementations for various types of
collections such as lists, sets, and maps, and provides algorithms for sorting, searching, and
manipulating collections.
1. Unified Architecture:
o Consistent API: All collections in the framework implement standard interfaces,
which provides a uniform way to work with different types of collections.
o Interoperability: Since collections implement common interfaces, they can be
used interchangeably, making the code more flexible and reusable.
5 Encapsulation:
i. Data Abstraction: The framework allows for the abstraction of data structures
and algorithms, making it easier to change the underlying implementation
without affecting the code that uses the collections.
1. Interfaces:
o Collection: The root interface for all collections.
o List: Ordered collection (e.g., ArrayList, LinkedList).
o Set: Unordered collection that does not allow duplicates (e.g., HashSet, TreeSet).
o Queue: Collection used to hold multiple elements prior to processing
(e.g., PriorityQueue, LinkedList).
o Map: Object that maps keys to values (e.g., HashMap, TreeMap).
2. Classes:
o ArrayList: Resizable array implementation of the List interface.
o LinkedList: Doubly-linked list implementation of the List and Deque interfaces.
o HashSet: Hash table-based implementation of the Set interface.
o TreeSet: Sorted tree-based implementation of the Set interface.
o HashMap: Hash table-based implementation of the Map interface.
o TreeMap: Red-Black tree-based implementation of the Map interface.
3. Algorithms:
o Sorting: Methods to sort collections (e.g., Collections.sort(), Arrays.sort()).
o Searching: Methods to search elements within collections (e.g.,
Collections.binarySearch()).
o Shuffling and Randomizing: Methods to shuffle or randomize elements (e.g.,
Collections.shuffle()).
Example Usage
import java.util.*;
// List Example
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
Access Time O(1) for random access O(n) for random access
Insertion/Deletion O(n) for middle operations O(1) for middle operations (no shifting,
Time (requires shifting) just pointer updates)
• 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
Use Case
• 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]
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
No duplicate keys,
Duplicates values can repeat No duplicates Allows duplicates
Allows one null Allows one Allows multiple null values (depending on
Null Values
key,
multiple null values null value implementation)
Average Time O(1) for O(1) for O(1) for ArrayList (random access), O(n)
Complexity basic basic for LinkedList (random access)
operations operations
Use Unique
Case Key-value association
collection Ordered collection with duplicates allowed
• 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));
Comparator
Description
Key Features
Syntax
java
Copy code
public class MyClass
{ private int 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));
Summary of Differences
Method to
compareTo(T o) compare(T o1, T o2)
Implement
Sorting Logic
Location Defined within the class itself Defined in a separate class
Number
of Sorting Single natural ordering Multiple custom orderings
Sequences
Modification Requires modifying the class Does not require modifying the class
Multiple orderings, especially
Typical Use Case Natural ordering of objects for
third-party classes
• Use Comparable:
o When you want to define a natural ordering for objects of a class.
o When there is a single, commonly accepted way of ordering instances of the class.
• Use Comparator:
o When you need multiple ways of ordering objects.
o When you cannot modify the class whose objects need to be sorted.
o When you need to sort objects based on different criteria at different times.
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.
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.
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;
Hashtable<>();
if (employees.containsKey(searchID)) {
} else {
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.
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.
java
Copy code
import java.util.ArrayList; import
java.util.Iterator;
Explanation
1. Create a Collection:
o An ArrayList is created, and elements ("Apple", "Banana", "Cherry") are added to it.
2. Get an Iterator:
o The iterator() method of the ArrayList is called to obtain an Iterator object.
1. Encapsulation:
o Iterators provide a way to access elements of a collection without exposing
the underlying implementation details.
2. Uniform Interface:
o The Iterator interface provides a standard way to traverse collections, making
code more consistent and easier to maintain.
3. Safe Removal:
o The remove method of the Iterator allows for safe removal of elements
during iteration without causing ConcurrentModificationException.
java
Copy code
import java.util.HashSet;
import java.util.Iterator;
java
Copy code
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
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.
1. Iterator
2. ListIterator
3. Enumeration
1. Iterator
Description:
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();
}
}
Description:
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:
Example:
java
Copy code
import java.util.ArrayList; import
java.util.ListIterator;
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
Cursor Modify
Traversal Direction Supports
Collection Suitable For
List
Iterator Forward Yes No All collections
ListIterator Forward Lists (e.g., ArrayList,
and Yes Yes
LinkedList)
Backward
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.
1. Key-Value Pairs:
o A Map stores elements as key-value pairs (Map.Entry<K, V>).
o Keys are unique; a key maps to only one value.
3. Common Implementations:
o HashMap: Hash table-based implementation, allows null values and null
keys, unsynchronized.
o TreeMap: Red-Black tree-based implementation, ordered by the natural ordering of
its keys or by a comparator provided at map creation time.
o LinkedHashMap: Hash table and linked list implementation, maintains a doubly-
linked list running through all entries, provides predictable iteration order.
o Hashtable: Synchronized version of HashMap, does not allow null keys or values.
2. get(Object key):
o Returns the value to which the specified key is mapped, or null if the map contains
no mapping for the key.
3. remove(Object key):
o Removes the mapping for a key from the map if it is present.
4. containsKey(Object key):
o Returns true if the map contains a mapping for the specified key.
5. containsValue(Object value):
o Returns true if the map contains one or more mappings for the specified value.
6. keySet():
o Returns a Set view of the keys contained in the map.
7. values():
o Returns a Collection view of the values contained in the map.
8. entrySet():
o Returns a Set view of the key-value mappings contained in the map.
Example Usage
java
Copy code
import java.util.HashMap;
import java.util.Map;
1. Storage Mechanism:
o Map: Stores data as key-value pairs.
o Collection: Stores individual elements.
2. Interfaces:
o Map: Does not extend the Collection interface.
o Collection: List, Set, and Queue extend the Collection interface.
3. Data Access:
o Map: Access elements using keys.
o Collection: Access elements using iterators or index (in case of List).
4. Uniqueness:
o Map: Keys are unique.
o Collection: Depends on the type of collection (Set ensures uniqueness, List
allows duplicates).
5. Methods:
o Map: Methods like put, get, remove, keySet, values, entrySet.
o Collection: Methods like add, remove, iterator, size, contains.
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.
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.
1. load(InputStream inStream):
o Reads a property list (key-value pairs) from an input stream.
2. load(Reader reader):
o Reads a property list (key-value pairs) from a reader.
5. getProperty(String key):
o Searches for the property with the specified key in this property list.
7. list(PrintStream out):
o Prints this property list out to the specified output stream.
8. list(PrintWriter out):
o Prints this property list out to the specified writer.
Here’s an example of how to use the Properties class to read from and write to a properties
file.
// 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");
Explanation
1. Loading Properties:
o The properties file (config.properties) is loaded using the load method of the
Properties class.
2. Accessing Properties:
o The properties are accessed using the getProperty method.
3. Modifying Properties:
o Properties are modified using the setProperty method.
4. Saving Properties:
o The modified properties are saved back to the file using the store method.
5. Listing Properties:
o The list method prints all key-value pairs to the standard output.
Summary
• The Properties class is a powerful tool for handling configuration and application settings
in Java.
Ans: In Java, Set and Queue are interfaces that are part of the Java Collections Framework. They
define behaviors for collections that have specific characteristics and are implemented by
various classes to provide different implementations of these behaviors.
Set Interface
The Set interface represents a collection that cannot contain duplicate elements. It models the
mathematical set abstraction and is used when you want to ensure that no duplicates are stored.
Here are some key characteristics and methods of the Set interface:
Key Characteristics
1. No Duplicates:
o A Set does not allow duplicate elements. Adding duplicate elements has no effect.
2. Unordered:
o There is no guarantee on the order of elements in a Set. The specific
implementation decides the order, which can vary between iterations.
3. Implementations:
o Common implementations include HashSet, TreeSet, and LinkedHashSet.
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.
Queue Interface
The Queue interface represents a collection designed for holding elements prior to processing. It
follows the FIFO (First-In-First-Out) principle, where elements are added at the end (tail) and
removed from the beginning (head) of the queue. Here are some key characteristics and methods
of the Queue interface:
Key Characteristics
1. FIFO Ordering:
o Elements are inserted at the end of the queue and removed from the
beginning, maintaining the order in which elements were added.
2. Implementations:
o Common implementations include LinkedList (provides more efficient queue
operations than ArrayList) and PriorityQueue (orders elements according to
their natural ordering or by a specified comparator).
3. Special Methods:
o Besides the basic Collection methods (add, remove, peek, poll), Queue
interface also includes methods like offer, element, remove, which throw
exceptions if the operation fails.
Key Methods
Summary
• Set Interface:
o Stores unique elements.
o No defined ordering of elements.
o Common implementations include HashSet, TreeSet, and LinkedHashSet.
• Queue Interface:
o Follows FIFO ordering.
o Common implementations include LinkedList and PriorityQueue.
o Useful for tasks such as processing elements in the order they were added.
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.
Advantages of Spring Framework
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:
Q44) what is the difference between constructor injection and setter injection?
2) Desn't override the setter property Overrides the constructor property if both are
defined.
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.
Singleton
1 This scopes the bean definition to a single instance per Spring IoC container
(default).
2
Prototype
This scopes a single bean definition to have any number of object instances.
3 Request
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.
• It is very simple to combine Spring Boot Application with its Spring Ecosystem, which
includes Spring JDBC, Spring ORM, Spring Data, and Spring Security, among other
things.
• To minimize developer effort, it employs the "Opinionated Defaults Configuration"
approach.
• It provides Embedded HTTP servers such as Tomcat, Jetty, and others to help us build and
test our web applications quickly.
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.