0% found this document useful (0 votes)
18 views70 pages

Question Bank Java BCS 403

The document is a question bank for the OOP with Java course (BCS 403) at Axis Institute of Technology and Management, authored by Alok Dwivedi. It contains a series of questions and answers covering key concepts in Java, including inner classes, access specifiers, exception handling, and the differences between processes and threads. The content serves as a study guide for students to understand essential Java programming principles and practices.

Uploaded by

dwivedialok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views70 pages

Question Bank Java BCS 403

The document is a question bank for the OOP with Java course (BCS 403) at Axis Institute of Technology and Management, authored by Alok Dwivedi. It contains a series of questions and answers covering key concepts in Java, including inner classes, access specifiers, exception handling, and the differences between processes and threads. The content serves as a study guide for students to understand essential Java programming principles and practices.

Uploaded by

dwivedialok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Axis Institute of Technology and Mgt.

Java (OOPJ)
Question Bank

BCS 403

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

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.

Q3. What's the purpose of Static methods and static variables.

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.

Q4. What is data encapsulation and what's its significance.

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.

Q5. What is a singleton class? Give a practical example of its usage.

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.

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

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.

Q7. Is Java Platform Independent if then how.


Yes, Java is a Platform Independent language. Unlike many programming languages javac
compiler compiles the program to form a bytecode or .class file. This file is independent of the
software or hardware running but needs a JVM(Java Virtual Machine) file preinstalled in the
operating system for further execution of the bytecode.
Although JVM is platform dependent, the bytecode can be created on any System and can be
executed in any other system despite hardware or software being used which makes Java
platform independent.

Q8. Difference between JVM, JRE, and JDK.


JVM: JVM also known as Java Virtual Machine is a part of JRE. JVM is a type of interpreter
responsible for converting bytecode into machine-readable code. JVM itself is platform
dependent but it interprets the bytecode which is the platform-independent reason why Java is
platform-independent.
JRE: JRE stands for Java Runtime Environment, it is an installation package that provides an
environment to run the Java program or application on any machine.
JDK: JDK stands for Java Development Kit which provides the environment to develop and
execute Java programs. JDK is a package that includes two things Development Tools to
provide an environment to develop your Java programs and, JRE to execute Java programs or
applications.

Q9. Explain public static void main(String args[]) in Java.

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

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 {

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

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;

public class File_Read {


public static void main(String[] args)
{ try {

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

readFile("test1.txt");
} catch (FileNotFoundException e)
{ System.out.println("Error: " + e.getMessage());
}
}

public static void readFile(String fileName) throws FileNotFoundException {


File file = new File(fileName);
Scanner scanner = new Scanner(file);

// Read and process the contents of the file


while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}

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

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

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.

Q14) what are exception handling techniques in java.


Ans) There are four keywords used in java exception handling.
throw: Sometimes we explicitly want to create an exception object and then throw it to halt the
normal processing of the program. The throw keyword is used to throw exceptions to the runtime
to handle it.
throws: When we are throwing any checked exception in a method and not handling it, then we
need to use the throws keyword in the method signature to let the caller program know the
exceptions that might be thrown by the method. The caller method might handle these exceptions
or propagate them to its caller method using the throws keyword. We can provide multiple
exceptions in the throws clause and it can be used with the main() method also.
try-catch: We use try-catch block for exception handling in our code. try is the start of the block
and catch is at the end of the try block to handle the exceptions. We can have multiple catch
blocks with a try and try-catch blocks can be nested also. catch block requires a parameter that
should be of type Exception.
finally: The finally block is optional and can be used only with a try-catch block. Since
exception halts the process of execution, we might have some resources open that will not get
closed, so we can use the finally block. The finally block gets executed always, whether an
exception occurs or not.

Q15) what are the important methods of java Exception class.


Ans) Exception and all of its subclasses don’t provide any specific methods and all of the
methods are defined in the base class Throwable.

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

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.

Q16) what is the difference between checked and unchecked exception.


Ans) Checked Exceptions should be handled in the code using try-catch block or else the method
should use the throws keyword to let the caller know about the checked exceptions that might be
thrown from the method. Unchecked Exceptions are not required to be handled in the program or
to mention them in the throws clause of the method.
Exception is the superclass of all checked exceptions whereas RuntimeException is the
superclass of all unchecked exceptions. Note that RuntimeException is the child class of
Exception.
Checked exceptions are error scenarios that require to be handled in the code, or else you will get
compile time error. For example, if you use FileReader to read a file, it
throws FileNotFoundException and we must catch it in the try-catch block or throw it again to
the caller method. Unchecked exceptions are mostly caused by poor programming, for example,
NullPointerException when invoking a method on an object reference without making sure that
it’s not null. For example, I can write a method to remove all the vowels from the string. It’s the
caller’s responsibility to make sure not to pass a null string.

Q17) How to write custom exception in java.

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

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;

public class MyException extends IOException {

private static final long serialVersionUID = 4664456874499611218L;

private String errorCode="Unknown_Exception";

public MyException(String message, String errorCode)


{ super(message);
this.errorCode=errorCode;
}

public String getErrorCode(){


return this.errorCode;
}

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.

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

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.

Q19) Differentiate between process and thread.

Ans) A Program in the execution is called the process whereas; A thread is a subset of the
process

• Processes are independent whereas threads are the subset of process.


• Process have different address space in memory, while threads contain a shared address
space.
• Context switching is faster between the threads as compared to processes.
• Inter-process communication is slower and expensive than inter-thread communication.

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

• Any change in Parent process doesn't affect the child process whereas changes in parent
thread can affect the child thread.

Q20) what are the states in the lifecycle of a 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.

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

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 {

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

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);

// Subtraction using lambda expression

Calculator subtraction = (a, b) -> a - b;

int difference = subtraction.calculate(10, 5); // Output: 5

System.out.println("Difference: " + difference);

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

Q23) what is Lambda expression, what is purpose of this in java.

A lambda expression in Java is a concise way to represent an anonymous function—a function


without a name that can be passed around as a parameter to other methods or stored in variables.

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.

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.

Flexibility: Lambda expressions provide a flexible way to pass behavior as an argument to


methods or store it in variables. This enables the use of higher-order functions, which can accept
other functions as parameters or return functions as results.

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.

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

Functional Programming Paradigm: Lambda expressions play a crucial role in promoting


functional programming paradigms within Java. They facilitate the adoption of functional
programming concepts such as higher-order functions, immutability, and function composition.

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.

Q24) Explain Lambda expression with suitable example.


import java.util.ArrayList;
import java.util.List;

public class Main {


public static void main(String[] args) {
// List of strings
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");

// Sorting the list alphabetically using lambda expression


names.sort((String s1, String s2) -> s1.compareTo(s2));

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

// Printing the sorted list


System.out.println("Sorted Names:");
for (String name : names) {
System.out.println(name);
}
}
}

Q25) Explain the concept of Base64 encoding and decoding in detail, covering its purpose,
principles, and applications in computer science and beyond.

Introduction to Base64 Encoding and Decoding:

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.

Principles of Base64 Encoding:

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.

Purpose of Base64 Encoding and Decoding:

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 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.

Advantages of Base64 Encoding:


Compatibility: Base64 encoding allows binary data to be transmitted over channels that only
support text data, ensuring compatibility with various protocols and systems.
Data Integrity: Base64 encoding preserves the integrity of binary data during transmission, as it
can accurately represent all possible byte values without loss.
Text Representation: Encoded Base64 data consists of printable ASCII characters, making it
human-readable and suitable for inclusion in textual documents or messages.

Applications of Base64 Encoding and Decoding:

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.

Authentication Tokens: Base64 encoding is utilized in authentication mechanisms, such as Basic


Authentication, where credentials are encoded as Base64 strings in HTTP headers.

Cryptography: Base64 encoding is employed in cryptographic algorithms and protocols to


represent binary data, such as cryptographic keys or digital signatures, in a human-readable
format.

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

Q26) what is for-each method in java. Explain with suitable example.


The forEach method in Java is a convenient way to iterate over elements in a collection (like
lists, sets, or maps) and perform an operation on each element.
Syntax:
void forEach(Consumer<? super T> action)
Here, action represents the operation to be performed on each element, and Consumer is a
functional interface with a single abstract method, accept, that takes one argument and returns no
result.

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;

public class Main {


public static void main(String[] args) {
// Create a list of strings
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");

// Using forEach to print each element of the list


names.forEach(name -> System.out.println(name));

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

}
}

Q27) Explain try-with-resource with suitable example.


The try-with-resources statement in Java is used to automatically close resources that are opened
within its scope. This ensures that the resources are closed properly, regardless of whether an
exception occurs during their use.
Syntax:
try (resource initialization) {
// code that uses the resource
} catch (ExceptionType e) {
// exception handling
}

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;

public class Main {


public static void main(String[] args) {
// Specify the file path
String filePath = "example.txt";

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

// Using try-with-resources to open and read the file


try (BufferedReader reader = new BufferedReader(new FileReader(filePath)))
{ String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Q28) Explain switch expression in java with suitable example.


Switch expressions in Java provide a more concise and expressive way to write switch
statements, especially when dealing with complex conditions or multiple cases. Introduced as a
preview feature in Java 12 and made a standard feature in Java 14, switch expressions allow you
to use switch as an expression rather than just a statement
Syntax:
result = switch (expression)
{ case value1 ->
expression1; case value2 -
> expression2;
// more cases
default -> defaultExpression;

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

};
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);
}
}

Q29) What is local variable type inference in java.


Local variable type inference, introduced in Java 10, allows you to declare local variables
without explicitly specifying their type. Instead, the compiler infers the type of the variable
based on the initializer expression used to initialize it. This feature is also known as "var" type.
Syntax:
var variableName = initializerExpression;

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

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.

Q30) Explain inner anonymous class in Java with suitable example.


An inner anonymous class in Java is a class that is declared and instantiated at the same time,
typically within the body of another class or method. Anonymous inner classes are useful when
you need to implement a simple interface or extend a class and don't want to create a separate
named class for it.
Syntax:
Anonymous inner classes are declared and instantiated using the following syntax:
For implementing an interface:

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

InterfaceName obj = new InterfaceName() {


// Method implementations
};
For extending a class:
ClassName obj = new ClassName() {
// Method implementations
};
Example : Implementing an Interface with Anonymous Inner Class:
Suppose we have a Runnable interface and want to create a thread using an anonymous inner
class.
public class Main {
public static void main(String[] args) {
// Using anonymous inner class to implement Runnable interface
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Hello from anonymous inner class!");
}
};
// Creating and starting a thread with the anonymous inner class
Thread thread = new Thread(runnable);
thread.start();
}
}

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

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

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

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

JDK. Reusability and Interoperability

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.

Benefits of the Java Collection Framework

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.

2. Reduces Programming Effort:


o Reusable Data Structures: The framework provides standard implementations
for common data structures (e.g., ArrayList, LinkedList, HashSet, TreeSet,
HashMap, TreeMap), so developers don’t need to implement these themselves.
o Pre-built Algorithms: The framework includes utility classes like Collections and
Arrays that provide methods for sorting, searching, and manipulating collections.

3. Increases Program Speed and Quality:


o Optimized Implementations: The collection classes are highly optimized,
providing better performance than custom implementations.
o Exception Handling: The framework provides runtime exception handling, which helps
in identifying programming errors quickly.

4 Reduces Effort to Learn New APIs:


o Standard Interfaces: Once you learn the interfaces, you can use any of the
collection classes that implement these interfaces without learning new APIs.

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

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

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.

Key Components of the Java Collection Framework

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()).

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

Example Usage

import java.util.*;

public class CollectionFrameworkExample

{ public static void main(String[] args) {

// List Example

List<String> list = new ArrayList<>();

list.add("Apple");

list.add("Banana");

list.add("Cherry");

Collections.sort(list);

System.out.println("Sorted List: " + list);

// Set Example

Set<String> set = new HashSet<>();

set.add("Apple");

set.add("Banana");

set.add("Apple"); // Duplicate element

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

System.out.println("Set: " + set);

// Map Example

Map<String, Integer> map = new HashMap<>();

map.put("Apple", 1);

map.put("Banana", 2);

System.out.println("Map: " + map);

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.

Q32) what is difference between ArrayList and LinkedList in collection framework.


Explain.

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

• ArrayList is backed by a dynamically resizable array.

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

Performance Characteristics

• Access Time: O(1) - Direct access using index.


• Insertion/Deletion: O(n) - Adding or removing elements in the middle of the list requires
shifting elements.
• Memory Consumption: Less overhead compared to LinkedList as it only stores data
elements and not node pointers.

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

List<String> arrayList = new ArrayList<>();

arrayList.add("Apple");

arrayList.add("Banana");

arrayList.add("Cherry");

System.out.println(arrayList.get(1)); // Access element at index 1

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.

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

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

List<String> linkedList = new LinkedList<>();

linkedList.add("Apple");

linkedList.add("Banana");

linkedList.add("Cherry");

System.out.println(linkedList.get(1)); // Access element at index 1

Summary of Differences

Feature ArrayList LinkedList

Data Structure Dynamic array Doubly linked list

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)

Memory Usage Less overhead More overhead (due to pointers)

Best for read-heavy scenarios Best for write-heavy scenarios with


Use Case with infrequent
insertions/deletions frequent insertions/deletions

Choosing Between ArrayList and LinkedList

• Use ArrayList when you need fast random access and your application does not require
frequent insertion/deletion operations.

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

• 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

• HashMap is an implementation of the Map interface.


• It stores key-value pairs where each key is unique, and each key maps to exactly one value.

Key Features

• No Order: Does not guarantee any order of the keys or values.


• Null Values: Allows one null key and multiple null values.
• Efficiency: Provides O(1) average time complexity for insertion, deletion, and
retrieval operations.

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

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

Description

• HashSet is an implementation of the Set interface.


• It stores unique elements and does not allow duplicate values.

Key Features

• No Order: Does not guarantee any order of the elements.


• Null Values: Allows a single null value.
• Efficiency: Provides O(1) average time complexity for basic operations like add, remove,
and contains.

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]

List (ArrayList and LinkedList)


Description

• List is an interface that provides an ordered collection of elements.


• Common implementations are ArrayList and LinkedList.

Key Features

• Ordered: Maintains the order of elements based on insertion order.


• Duplicates: Allows duplicate elements.
• Access by Index: Elements can be accessed by their index.

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

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)

Interface Map Set List


Data Unique
Structure Key-value pairs
elements Ordered collection of elements

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)

Order No order No order Maintains insertion

order Access by Index No No Yes

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

Choosing the Right Data Structure

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

• 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.

Q34) Differentiate Comparator and Comparable

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;

public MyClass(int value)


{ this.value = value;
}

@Override
public int compareTo(MyClass other) {
return Integer.compare(this.value, other.value);
}

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

}
Example
java
Copy code
List<MyClass> list = new ArrayList<>();
list.add(new MyClass(3));
list.add(new MyClass(1));
list.add(new MyClass(2));

Collections.sort(list); // Uses compareTo method

Comparator
Description

• 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;

public MyClass(int value)


{ this.value = value;
}

// Getters and setters


}

public class MyClassComparator implements Comparator<MyClass> {


@Override
public int compare(MyClass o1, MyClass o2) {
return Integer.compare(o1.getValue(), o2.getValue());
}

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

}
Example
java
Copy code
List<MyClass> list = new ArrayList<>();
list.add(new MyClass(3));
list.add(new MyClass(1));
list.add(new MyClass(2));

Collections.sort(list, new MyClassComparator()); // Uses compare method

Summary of Differences

Feature Comparable Comparator

Interface Comparable<T> Comparator<T>

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

Automatically used by Collections.sort() Explicitly passed to


Usage and Arrays.sort() when no Comparator Collections.sort()
is provided and Arrays.sort()

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

When to Use Which

• Use Comparable:
o When you want to define a natural ordering for objects of a class.

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

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.

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;

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

public class EmployeeRecords {

public static void main(String[] args) {

// Create a Hashtable to store employee records

Hashtable<Integer, String> employees = new

Hashtable<>();

// Add employee records to the Hashtable

employees.put(101, "John Doe");

employees.put(102, "Jane Smith");

employees.put(103, "Michael Johnson");

employees.put(104, "Emily Davis");

// Retrieve and print employee records

System.out.println("Employee ID: 101, Name: " +

employees.get(101)); System.out.println("Employee ID: 102, Name: "

+ employees.get(102)); System.out.println("Employee ID: 103, Name:

" + employees.get(103)); System.out.println("Employee ID: 104,

Name: " + employees.get(104));

// Display all employee records

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

System.out.println("\nAll Employee Records:");

for (Integer id : employees.keySet()) {

System.out.println("Employee ID: " + id + ", Name: " + employees.get(id));

// Check if a particular employee ID exists

int searchID = 102;

if (employees.containsKey(searchID)) {

System.out.println("\nEmployee ID " + searchID + " exists with name: " +


employees.get(searchID));

} else {

System.out.println("\nEmployee ID " + searchID + " does not exist.");

// Remove an employee record

int removeID = 103;

employees.remove(removeID);

System.out.println("\nEmployee ID " + removeID + " removed.");

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

// Display all employee records after removal

System.out.println("\nAll Employee Records After Removal:");

for (Integer id : employees.keySet()) {

System.out.println("Employee ID: " + id + ", Name: " + employees.get(id));

Q36) Explain the process of accessing collection through iterator.

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.

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

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;

public class IteratorExample {


public static void main(String[] args) {
// Create an ArrayList and add some elements
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

// Get an iterator for the list


Iterator<String> iterator = list.iterator();

// Traverse the list using the iterator


while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);

// Remove an element conditionally if


(element.equals("Banana")) {
iterator.remove();
}
}

// Print the list after iteration System.out.println("List


after iteration: " + list);
}
}

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.

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

3. Traverse the Collection:


o The while (iterator.hasNext()) loop is used to iterate through the collection.
o Inside the loop, iterator.next() is called to get the next element in the collection.
o The element is printed, and if the element is "Banana", it is removed from the
collection using iterator.remove().

4. Print the Updated Collection:


o After the iteration, the updated ArrayList is printed to show the removal of "Banana".

Advantages of Using Iterators

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.

Example: Using an Iterator with a HashSet

Here’s an example of how to use an Iterator to traverse a HashSet:

java
Copy code
import java.util.HashSet;
import java.util.Iterator;

public class HashSetIteratorExample {


public static void main(String[] args) {
// Create a HashSet and add some elements
HashSet<String> set = new HashSet<>();
set.add("Dog");
set.add("Cat");
set.add("Bird");

// Get an iterator for the set

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

Iterator<String> iterator = set.iterator();

// Traverse the set using the iterator


while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
}
}

Example: Using an Iterator with a HashMap

Here’s an example of how to use an Iterator to traverse a HashMap:

java
Copy code
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapIteratorExample {


public static void main(String[] args) {
// Create a HashMap and add some key-value pairs
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Get a set of the entries


Set<Map.Entry<Integer, String>> entrySet = map.entrySet();

// Get an iterator for the entry set


Iterator<Map.Entry<Integer, String>> iterator = entrySet.iterator();

// Traverse the map using the iterator


while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " +
entry.getValue());
}
}
}

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

In these examples, the Iterator is used to traverse different types of collections


(HashSet, HashMap). The process remains consistent across different collection types,
highlighting the flexibility and utility of the Iterator interface in Java.

Q37) what is cursor? Explain different cursor in java.

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:

• hasNext(): Returns true if the iteration has more elements.


• next(): Returns the next element in the iteration.
• remove(): Removes the last element returned by the iterator.

Usage:

• Suitable for any collection that implements the Iterable interface, including
ArrayList, HashSet, and HashMap.

Example:

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

java
Copy code
import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {


public static void main(String[] args)
{ ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

Iterator<String> iterator = list.iterator();

while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);

if (element.equals("Banana")) {
iterator.remove();
}
}

System.out.println("List after iteration: " + list);


}
}
2. ListIterator

Description:

• 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.

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

Usage:

• Only for lists, such as ArrayList and LinkedList.

Example:

java
Copy code
import java.util.ArrayList; import
java.util.ListIterator;

public class ListIteratorExample {


public static void main(String[] args)
{ ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

ListIterator<String> listIterator = list.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:

• hasMoreElements(): Returns true if there are more elements to be enumerated.


• nextElement(): Returns the next element in the enumeration.

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

Usage:

• Mainly used with legacy classes like Vector and Stack.

Example:

java
Copy code
import java.util.Vector; import
java.util.Enumeration;

public class EnumerationExample {


public static void main(String[] args)
{ Vector<String> vector = new
Vector<>(); vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");

Enumeration<String> enumeration = vector.elements();

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

Legacy collections (e.g., Vector,


Enumeration Forward No No Stack)

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

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.

Q38) What is map in java. How is it different from collection. Explain.

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.

Key Characteristics of Map

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.

2. No Direct Inheritance from Collection:


o Unlike other collection interfaces (List, Set), Map does not inherit from the
Collection interface.

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.

Key Methods of Map

1. put(K key, V value):


o Associates the specified value with the specified key in the map.

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.

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

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;

public class MapExample {


public static void main(String[] args) {
// Create a HashMap
Map<Integer, String> map = new HashMap<>();

// Add key-value pairs to the map


map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

// Retrieve a value by key


System.out.println("Value for key 2: " + map.get(2));

// Check if a key exists if


(map.containsKey(3)) {
System.out.println("Key 3 exists in the map.");
}

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

// Check if a value exists


if (map.containsValue("One"))
{ System.out.println("Value 'One' exists in the
map.");
}

// Remove a key-value pair


map.remove(2);
System.out.println("Map after removing key 2: " + map);

// Iterate over the map


for (Map.Entry<Integer, String> entry : map.entrySet())
{ System.out.println("Key: " + entry.getKey() + ", Value: " +
entry.getValue());
}
}
}

Differences Between Map and Collection

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.

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

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.

Q39) Explain Properties class in java with example.

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:

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

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.

Key Methods of Properties

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.

3. store(OutputStream out, String comments):


o Writes the properties list to the output stream.

4. store(Writer writer, String comments):


o Writes the properties list to the writer.

5. getProperty(String key):
o Searches for the property with the specified key in this property list.

6. setProperty(String key, String value):


o Calls the put method of Hashtable.

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.

9. getProperty(String key, String defaultValue):


o Searches for the property with the specified key. If the key is not found, returns
the default value.

Example: Using the Properties Class

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

Here’s an example of how to use the Properties class to read from and write to a properties
file.

Example Properties File (config.properties)


makefile
Copy code
username=admin
password=secret
url=http://example.com
Java Program to Read and Write Properties
java
Copy code
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class PropertiesExample {


public static void main(String[] args)
{ Properties properties = new
Properties();

// Load properties from a file


try (InputStream input = new FileInputStream("config.properties")) {
properties.load(input);
System.out.println("Properties loaded:");
properties.list(System.out);
} catch (IOException e) {
e.printStackTrace();
}

// Accessing properties
String username = properties.getProperty("username");
String password = properties.getProperty("password");
String url = properties.getProperty("url");

System.out.println("\nUsername: " + username);


System.out.println("Password: " + password);
System.out.println("URL: " + url);

// Modifying properties
properties.setProperty("username", "newAdmin");
properties.setProperty("password", "newSecret");

// Save properties to a file

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

try (OutputStream output = new FileOutputStream("config.properties"))


{
properties.store(output, "Updated properties");
System.out.println("\nProperties updated and saved to file.");
} catch (IOException e) {
e.printStackTrace();
}

// Load and print updated properties


try (InputStream input = new FileInputStream("config.properties")) {
properties.load(input);
System.out.println("\nUpdated properties loaded:");
properties.list(System.out);
} catch (IOException e) {
e.printStackTrace();
}
}
}

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.

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

• 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.

Q40) Explain Set and Queue interface 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.

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

Example Usage of Set


java
Copy code
import java.util.HashSet;
import java.util.Set;

public class SetExample {


public static void main(String[] args)
{ Set<String> set = new HashSet<>();

// Adding elements to the set


set.add("Apple");
set.add("Banana");
set.add("Apple"); // This duplicate will be ignored

System.out.println("Set elements: " + set);

// Removing an element from the set


set.remove("Banana");

System.out.println("Set elements after removal: " + set);

// Checking if an element exists in the set if


(set.contains("Apple")) {
System.out.println("Set contains 'Apple'");
}

// Iterating over the set (order may vary)


for (String element : set) {
System.out.println("Element: " + element);
}
}
}

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:

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

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

• add(E e): Adds the specified element to the queue.


• remove(): Removes and returns the head of the queue.
• peek(): Retrieves, but does not remove, the head of the queue.
• poll(): Retrieves and removes the head of the queue.
• offer(E e): Adds the specified element to the queue if possible.

Example Usage of Queue


java
Copy code
import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {


public static void main(String[] args)
{ Queue<String> queue = new
LinkedList<>();

// Adding elements to the queue


queue.add("Apple");
queue.add("Banana");
queue.add("Cherry");

System.out.println("Queue elements: " + queue);

// Removing an element from the queue


String removedElement = queue.remove();
System.out.println("Removed element: " + removedElement);
System.out.println("Queue elements after removal: " + queue);

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

// Checking the head of the queue


String headElement = queue.peek();
System.out.println("Head element: " + headElement);

// Iterating over the queue (FIFO order)


while (!queue.isEmpty()) {
System.out.println("Processing element: " + queue.poll());
}
}
}

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.

Q41) Define String framework with its advantages.

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.

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 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

There are many advantages of Spring Framework. They are as follows:


1) Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no
need to write too much code. It hides the basic steps of these technologies.
Let's take the example of JdbcTemplate, you don't need to write the code for exception handling,
creating connection, creating statement, committing transaction, closing connection etc. You
need to write the code of executing query only. Thus, it save a lot of JDBC code.
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.

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

Q42) Describe the Dependency Injection and its types.

Dependency Injection in Spring


Dependency Injection (DI) is a design pattern that removes the dependency from the
programming code so that it can be easy to manage and test the application. Dependency
Injection makes our programming code loosely coupled. To understand the DI better, Let's
understand the Dependency Lookup (DL) first:
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.

Q43) Describe the types of IOC container in spring.

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:

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

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?

No. Constructor Injection Setter Injection

1) No Partial Injection Partial 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

4) Better for too many properties Better for few properties.

Q45) what is autowiring in spring. Define the autowiring modes.

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" />

The autowiring modes are given below:

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

No. Mode Description

1) No this is the default mode, it means autowiring is not enabled.

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.

4) Constructor It injects the bean using constructor

Q46) Describe Bean Definition with Bean Scopes.


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. These beans are created with the configuration metadata that
you supply to the container. For example, in the form of XML <bean/> definitions.

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).

2
Prototype
This scopes a single bean definition to have any number of object instances.

3 Request

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

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.

The advantages of Spring Boot are as follows:


• It is very simple to create Spring-based apps in Java or Groovy.
• It cuts down on development time and also increases the output.
• It eliminates the requirement to write repetitive code, annotations, and XML
configuration.

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

• 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

Key dependencies of Spring Boot

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

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

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.

Q50) Explain the basic Spring Boot Annotations.


@SpringBootApplication: This is the main annotation used to bootstrap a Spring Boot
application. It combines three annotations: @Configuration, @EnableAutoConfiguration,
and @ComponentScan. It is typically placed on the main class of the application.
@Configuration: This annotation is used to indicate that a class contains configuration
methods for the application context. It is typically used in combination with @Bean
annotations to define beans and their dependencies.
@Component: This annotation is the most generic annotation for any Spring-managed component.
It is used to mark a class as a Spring bean that will be managed by the Spring container.

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

@RestController: This annotation is used to define a RESTful web service controller. It is a


specialized version of the @Controller annotation that includes the @ResponseBody
annotation by default.
@RequestMapping: This annotation is used to map HTTP requests to a specific method in a
controller. It can be applied at the class level to define a base URL for all methods in the class,
or at the method level to specify a specific URL mapping.

Alok Dwivedi Asst. Prof AITM CS ([email protected])

You might also like