0% found this document useful (0 votes)
2 views32 pages

OOPs With Java Questions

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including JVM, bytecode, object creation, and the differences between JDK, JRE, and JVM. It covers key features such as constructors, garbage collection, instance variables, checked exceptions, and the distinction between classes and objects. Additionally, it discusses advanced topics like local variable type inference, records, sealed classes, and the diamond syntax for generics.

Uploaded by

tanyafds
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)
2 views32 pages

OOPs With Java Questions

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including JVM, bytecode, object creation, and the differences between JDK, JRE, and JVM. It covers key features such as constructors, garbage collection, instance variables, checked exceptions, and the distinction between classes and objects. Additionally, it discusses advanced topics like local variable type inference, records, sealed classes, and the diamond syntax for generics.

Uploaded by

tanyafds
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

OBJECT ORIENTED PROGRAMMING WITH JAVA

1. Describe JVM and byte code in Java Architecture.

The Java Virtual Machine (JVM) is a virtual runtime environment that enables Java programs
to run on any device or operating system, providing platform independence (Write Once, Run
Anywhere).
Key Responsibilities of JVM:
 Loads Java .class files (bytecode)
 Verifies the bytecode for security and correctness
 Interprets or compiles bytecode to machine code using JIT (Just-In-Time) compiler
 Manages memory through garbage collection
 Provides runtime environment for execution

📦 2. What is Bytecode in Java?


Bytecode is the intermediate code generated by the Java compiler (javac). It is not machine-
specific, but JVM-specific.
Key Characteristics:
 Stored in .class files
 Executed by JVM, not the CPU directly
 Enables Java's platform independence
 Compact and optimized format

2. How is object created in Java?


In Java, objects are created from classes using the new keyword. This process involves three key
steps:
 Declaration: A variable is declared with a specific object type, associating a variable name
with that type.
 Instantiation: The new keyword allocates memory for the object, effectively creating an
instance of the class.
 Initialization: Following the new keyword, a constructor is called to initialize the object's
state. Constructors are special methods that set initial values for the object's fields.
Here's an example:
class Car {
String brand;
String model;

Car(String brand, String model) {


[Link] = brand;
[Link] = model;
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Camry"); // Object creation
}
}
3. Compare between JDK, JRE, and JVM.
JVM (Java Virtual JRE (Java Runtime
Feature JDK (Java Development Kit)
Machine) Environment)
Java Runtime
Full Form Java Virtual Machine Java Development Kit
Environment
Runs Java bytecode Provides environment to Provides tools to develop and
Purpose
(compiled code) run Java programs run Java programs
JVM + core Java libraries + JRE + development tools
Contains JVM only
supporting files (compiler, debugger, etc.)
End-user systems to run End-users and developers Developers to write, compile,
Used By
Java apps to run apps and run Java programs
Key Class Loader, Bytecode JRE + javac (compiler), jar,
JVM + Java class libraries
Components Verifier, Execution Engine javadoc, etc.
Yes (if bytecode is already
Can Run Code? Yes Yes
compiled)
Can Compile
❌ No ❌ No ✅ Yes (contains javac)
Code?

4. What are JAR and Manifest files?


JAR File (Java ARchive): A JAR file is a package file format that bundles multiple Java class files,
images, libraries, and metadata into one compressed file.
 It’s based on the ZIP format.
🔸 Purpose: To distribute Java applications or libraries in a compact form.
 To simplify deployment and sharing.
🔸 Creating a JAR: jar cf [Link] [Link]
(c = create, f = specify file name)
Running a JAR: java -jar [Link]

2. Manifest File ([Link])


 A Manifest file is a special file in a JAR located in the META-INF/ directory.
 It contains metadata about the JAR file, like:
o Main class to execute
o Classpath
o Version info
🔸 Example contents of [Link]: Manifest-Version: 1.0
Main-Class: MyClass
Feature JAR File Manifest File
Type Compressed archive Metadata text file
Location Anywhere on system Inside JAR → META-INF/[Link]
Purpose Package Java app or library Provide info about JAR contents
Common Use Deploy Java apps/libraries Specify main class, classpath, etc.

5. Define constructor.
In Java, a constructor is a special method used to initialize objects of a
class. It has the same name as the class and does not have a return
type, not even void. Constructors are automatically called when an
object of the class is created using the new keyword.
Key Features:
 Name: Must have the same name as the class.
 Return Type: Does not have a return type, not even void.
 Invocation: Automatically invoked when an object is created.
 Purpose: Initializes the object's state, setting initial values for its attributes.
Types of Constructors:
 Default Constructor:
If no constructor is explicitly defined in a class, Java provides a default
constructor with no parameters.
 Parameterized Constructor:
A constructor that accepts parameters, used to initialize object attributes with
specific values.
 Copy Constructor:
A constructor that creates a new object as a copy of an existing object of the
same class.
Rules for Constructors:
 Must have the same name as the class.
 Cannot have a return type.
 Cannot be static, abstract, final, or synchronized.
Example: public class Car {
String modelName;
int modelYear;

// Parameterized constructor
public Car(String name, int year) {
modelName = name;
modelYear = year;
}

public static void main(String[] args) {


Car myCar = new Car("Mustang", 1969);
[Link]([Link] + " " + [Link]);
}
}
Usage:
Constructors are essential for:
 Creating instances of classes.
 Allocating memory for objects on the heap.
 Setting default values for instance variables.
 Enforcing dependency management in frameworks like Spring.
 Ensuring objects are initialized properly before use.

6. Define Path in JDK. How is path different from ClassPath?

PATH is an environment variable that tells the operating system where to find the Java tools (like
javac, java, jar, etc.).
 It allows you to run Java commands from any directory in the command prompt or terminal.
✅ Example:
If your JDK is installed in:
C:\Program Files\Java\jdk21\bin
You add this path to the system's PATH variable.
bash
set PATH=C:\Program Files\Java\jdk21\bin;%PATH%
What is CLASSPATH?
 CLASSPATH is an environment variable used by the Java compiler and JVM to locate user-
defined classes, packages, and JAR files during compilation and execution.
✅ Example:
If your .class or .jar file is in C:\myapp\lib, then:
set CLASSPATH=C:\myapp\lib\[Link]
Difference Between PATH and CLASSPATH:
Feature PATH CLASSPATH
Purpose Tells OS where to find Java tools Tells JVM where to find Java classes/libraries
Affects javac, java, etc. commands Java programs and compiler locating .class files
Points To /bin directory of JDK /lib, .class, or .jar files
Example C:\Java\jdk21\bin C:\myProject\classes or [Link]
Default Value Must be manually set If not set, current directory . is used by default

🧠 In Simple Words:
 PATH = "Where is Java installed?"
 CLASSPATH = "Where are my Java classes and libraries?"

7. Describe garbage collection and demonstrate how it functions.


Garbage Collection (GC) in Java is the process of automatically identifying and destroying objects
that are no longer used by a program, to free up memory. It is handled by the Java Virtual
Machine (JVM).
Key Concepts
 Automatic Memory Management: JVM automatically reclaims memory used by
unreferenced objects.
 Heap Memory: Objects are stored in the heap. GC monitors this area.
 Unreachable Object: When there are no live references to an object, it becomes eligible for
garbage collection.
 [Link]() Method: A way to request garbage collection, though it's not guaranteed.
How It Functions
1. Object Allocation: An object is created using new, and stored in heap memory.
2. Reference Tracking: JVM keeps track of all references to each object.
3. Eligibility Check: If no reference points to an object, it becomes unreachable.
4. Garbage Collection Runs: JVM garbage collector deletes the unreachable object to free
memory.
5. Finalization (Optional): Before destroying an object, the GC may call its finalize() method
(deprecated in recent Java versions).

public class GarbageCollectionDemo {


public void finalize() {
[Link]("Garbage collector called to delete object");
}

public static void main(String[] args) {


GarbageCollectionDemo obj1 = new GarbageCollectionDemo();
GarbageCollectionDemo obj2 = new GarbageCollectionDemo();

// Nullifying references
obj1 = null;
obj2 = null;

// Requesting JVM to run Garbage Collector


[Link]();
}
}
8. What is an Instance Variable?
An instance variable is a non-static variable defined inside a class but outside any method,
constructor, or block. It is associated with an object (instance) of the class, meaning each
object has its own copy of the instance variable.

Key Characteristics of Instance Variables:


 Declared inside a class, but outside methods.
 Not marked as static.
 Memory is allocated when an object is created.
 Each object has its own separate copy.
 Can have default values (e.g., 0 for int, null for objects).

Example:
public class Student {
// Instance variable
String name;
int age;

void display() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}

public static void main(String[] args) {


Student s1 = new Student();
[Link] = "Alice";
[Link] = 20;

Student s2 = new Student();


[Link] = "Bob";
[Link] = 22;

[Link]();
[Link]();
}
}
9. What do you mean by Checked Exceptions?
Checked Exceptions are exceptions that are checked at compile-time by the Java compiler. This
means you must either handle them using a try-catch block or declare them using the throws
keyword, or the code will not compile.

📌 Key Points:
 Occur due to external factors beyond programmer control (e.g., file not found, database
error).
 Subclasses of the class Exception (but not RuntimeException).
 Compiler checks whether they are handled properly.
 If not handled, it causes a compilation error.

✅ Examples of Checked Exceptions:


Exception Class Description
IOException Input/output errors
SQLException Database access errors
FileNotFoundException File not found during file operations
ParseException Parsing errors (e.g., date format)
ClassNotFoundException Class not found when loading dynamically

🔍 Example Program:
import [Link].*;

public class CheckedExceptionExample {


public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
[Link]();
[Link]();
} catch (IOException e) {
[Link]("File operation error: " + [Link]());
}
}
}
10. Define the concept of classes and object in Java with a suitable example.
Class:
A class in Java is a blueprint or template for creating objects. It defines:
 Fields (variables) — to store data
 Methods (functions) — to perform actions
A class does not occupy memory until an object is created from it.

✅ Object:
An object is a real instance of a class. It:
 Has state (data stored in variables)
 Has behavior (actions through methods)
An object is created using the new keyword.

🔸 Syntax of Class:
class ClassName {
// Fields (variables)
// Methods (functions)
}
// Class definition
Example: Class and Object in Java
class Car {
// Instance variables (fields)
String color;
int speed;

// Method
void drive() {
[Link]("Driving " + color + " car at " + speed + " km/h");
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Creating object of Car
Car myCar = new Car();
// Setting field values
[Link] = "Red";
[Link] = 80;

// Calling method
[Link]();
}
}

11. Compare Object-Oriented Programming and Object-Based Programming with examples.


Difference between OOP and POP:
OOP POP

Object oriented. Structure oriented.

Program is divided into objects. Program is divided into functions.

Bottom-up approach. Top-down approach.

Inheritance property is used. Inheritance is not allowed.

It uses access specifier. It doesn't use access specifier.

Encapsulation is used to hide the data. No data hiding.

Concept of virtual function. No virtual function.

Object functions are linked through Parts of program are linked through
message passing. parameter passing.

Expanding new data and functions is not


Adding new data and functions is easy
easy.

The existing code can be reused. No code reusability.

use for solving big problems. Not suitable for solving big problems.

C++, Java. C, Pascal.

12. What is Diamond Syntax? How does it work with anonymous inner classes?
Diamond Syntax (<>) was introduced in Java 7 to simplify instantiating generic classes by
allowing the compiler to infer the type arguments from the context. This avoids redundancy
in code.
Example Without Diamond Syntax (before Java 7):
List<String> list = new ArrayList<String>();
Example With Diamond Syntax (Java 7 and above)
List<String> list = new ArrayList<>();
Here, the compiler infers that ArrayList is of type String by looking at the variable
declaration.
How Does It Work with Anonymous Inner Classes?
Diamond syntax does not work with anonymous inner classes (pre-Java 9). You must specify the
generic type explicitly when creating an anonymous inner class.
List<String> list = new ArrayList<String>() {
// You can override methods here
};
Java 9+ Update
From Java 9 onward, the compiler supports diamond syntax with anonymous inner classes
as long as the inferred type is unambiguous.
✅ Example (Java 9+):
Comparator<String> comp = new Comparator<>() {
public int compare(String a, String b) {
return [Link](b);
}
};
13. Explain the concept of Local Variable Type Inference using var. What are its limitations?
Introduced in Java 10, local variable type inference allows you to declare local variables
without explicitly specifying their type. The var keyword lets the compiler infer the type based
on the initializer.
Syntax:
var name = "Tanya"; // Compiler infers String
var number = 42; // Compiler infers int
var list = new ArrayList<String>(); // Compiler infers ArrayList<String>
var is not a keyword — it's a reserved type name.
🔸 You must initialize the variable when declaring with var
Use var?
 Inside methods (local variables)
 Enhanced for loops
 try-with-resources blocks
public void example() {
var message = "Hello"; // Inferred as String
var numbers = [Link](1, 2, 3); // Inferred as List<Integer>

for (var n : numbers) {


[Link](n);
}

try (var stream = new FileInputStream("[Link]")) {


// use stream
} catch (IOException e) {
[Link]();
}
}
Limitations of var in Java
Limitation Explanation
You must assign a value immediately.
❌ Can't be used without initialization
var x; // ❌ Error
Can't be used for class fields, parameters, or
❌ Only for local variables
return types.
❌ Can't be used with lambda expressions (unless
var x = () -> {}; // ❌ Error
explicitly typed)
Makes code harder to read when the type isn't
❌ Reduces readability if overused
obvious.
var value = null; // ❌ Error
❌ Can't be null without casting
Must write: var value = (String) null;

14. What are Records and Sealed Classes in Java?

Records are a special kind of class introduced in Java 14 (preview) and standardized in
Java 16, used for immutable data-carrying classes.

They automatically generate:

 constructor
 getters
 equals()
 hashCode()
 toString()

✅ Syntax:

public record Person(String name, int age) {}


public final class Person {
private final String name;
private final int age;

public Person(String name, int age) { ... }


public String name() { return name; }
public int age() { return age; }
public boolean equals(Object o) { ... }
public int hashCode() { ... }
public String toString() { ... }
}
Sealed Classes (introduced in Java 15 preview, finalized in Java 17) allow you to control which
classes are allowed to extend or implement a class/interface.
Steps to Create a Sealed Class
 Define the class that you want to make a seal.
 Add the "sealed" keyword to the class and specify which
classes are permitted to inherit it by using the "permits"
keyword.

Example
sealed class Human permits Manish, Vartika, Anjali
{
public void printName()
{
[Link]("Default");
}
}
non-sealed class Manish extends Human
{
public void printName()
{
[Link]("Manish Sharma");
}
}
sealed class Vartika extends Human
{
public void printName()
{
[Link]("Vartika Dadheech");
}
}
final class Anjali extends Human
{
public void printName()
{
[Link]("Anjali Sharma");
}
}

15. Describe Collections framework in Java with hierarchy diagram.


Hierarchy of the Collection Framework in Java
The utility package, ([Link]) contains all the classes and
interfaces that are required by the collection framework. The
collection framework contains an interface named an iterable
interface which provides the iterator to iterate through all the
collections. This interface is extended by the main collection
interface which acts as a root for the collection framework. All
the collections extend this collection interface thereby extending
the properties of the iterator and the methods of this interface.
The following figure illustrates the hierarchy of the collection
framework.
16. What is the Java Collections Framework? How does it differ from Arrays?

The Java Collections Framework is a unified architecture for storing, managing, and
manipulating groups of objects. It includes:

 Interfaces: List, Set, Queue, Deque, Map


 Implementations: ArrayList, HashSet, LinkedList, HashMap, etc.
 Algorithms: Sorting, searching, shuffling (via Collections class)
 Utilities: Like Collections and Arrays classes

🔷 Features of Java Collections Framework

 Dynamic memory management


 Built-in methods for sorting, searching, iteration, etc.
 Type-safe using generics
 Supports data structures like lists, sets, queues, maps

Example:

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


[Link]("Alice");
[Link]("Bob");
[Link](names); // Sorts list

Collections vs Arrays in Java


Feature Collections Arrays
Size Dynamic (can grow/shrink) Fixed once declared
Type Object types only Can store primitives and objects
Feature Collections Arrays
Flexibility More flexible; many structures (List, Set, Map) Less flexible
Utility methods Many (add, remove, sort, search, etc.) Limited (via Arrays class only)
Performance Slight overhead due to dynamic nature Faster for fixed-size, primitive data
Type Safety Supports generics (type safety) No type safety for primitives
Null Handling Can store null (except some sets/maps) Can store null in object arrays
Iterator support Built-in Iterators, for-each loops For-each supported (since Java 5)
Example List<String> list = new ArrayList<>(); String[] arr = new String[10];

17. Differentiate between Collection and Collections in Java.

Comparison Table
Feature Collection Collections
Type Interface Utility class (final)
Part of Hierarchy? Yes, root interface No, helper class only
Contains Methods Abstract instance methods Static utility methods
Inheritance Extended by interfaces like List, Set Cannot be extended
Object
Not directly instantiated Cannot be instantiated
Instantiation
Collection<String> c = new
Example ArrayList<>();
[Link](list);

Code Example Showing Both:


import [Link].*;

public class Demo {


public static void main(String[] args) {
Collection<String> names = new ArrayList<>();
[Link]("Tanya");
[Link]("Anya");

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


[Link](list); // Using Collections utility class

[Link](list); // [Anya, Tanya]


}
}
18. Explain the hierarchy of the Java Collections Framework with a diagram.
19. What is the Iterator interface? How does it differ from ListIterator?
Iterators are used in Collection framework in Java to retrieve elements one by one. It can be
applied to any Collection object. By using Iterator, we can perform both read and remove
operations. Iterator must be used whenever we want to enumerate elements in all Collection
framework implemented interfaces like Set, List, Queue, Deque and also in all implemented
classes of Map interface. Iterator is the only cursor available for entire collection framework.
Iterator object can be created by calling iterator() method present in Collection interface.
ListIterator It is only applicable for List collection implemented classes
like arraylist, linkedlist etc. It provides bi-directional iteration. ListIterator must be used when we
want to enumerate elements of List. This cursor has more functionality(methods) than iterator.
ListIterator object can be created by calling listIterator() method present in List interface.
Both Iterator and ListIterator are part of the Java Collections Framework, used to traverse
elements in a collection — but they differ in capabilities and use cases
Key Differences:
Feature Iterator ListIterator
Direction of Traversal Forward only Both forward and backward
Applicable To All collections (List, Set, etc.) Only List (like ArrayList, LinkedList)
Modify Elements Only remove() Can add(), remove(), and set()
Get Index While Traversing ❌ Not supported ✅ nextIndex(), previousIndex()
Can start at any index (e.g.,
Starts At Beginning of the collection
listIterator(2))
Very simple, read-only
Simplicity More powerful but complex
iteration

20. Describe the Collection interface and its main methods.

The Collection interface is the root interface of the Java Collections Framework. It is part
of the [Link] package and represents a group of objects, known as elements.

It is the superinterface for most commonly used collections like List, Set, and Queue.

Key Characteristics:

 Can store object elements (not primitives)


 Does not allow direct instantiation (it’s an interface)
 Provides common methods for all collection types

✅ Common Methods in Collection Interface


Method Description
boolean add(E e) Adds an element to the collection
boolean addAll(Collection<? extends E> c) Adds all elements from another collection
void clear() Removes all elements
boolean contains(Object o) Checks if an element exists
boolean containsAll(Collection<?> c) Checks if all elements in the collection exist
boolean isEmpty() Returns true if the collection is empty
Iterator<E> iterator() Returns an iterator to traverse elements
boolean remove(Object o) Removes the specified element
boolean removeAll(Collection<?> c) Removes all matching elements
boolean retainAll(Collection<?> c) Keeps only common elements between
Method Description
collections
int size() Returns the number of elements
Object[] toArray() Returns an array containing all elements
<T> T[] toArray(T[] a) Returns an array of a specified type

✅ Example Code Using Collection


import [Link].*;

public class CollectionDemo {


public static void main(String[] args) {
Collection<String> names = new ArrayList<>();

[Link]("Tanya");
[Link]("Amit");
[Link]("Ravi");

[Link]("Size: " + [Link]()); // 3


[Link]("Contains 'Amit'? " + [Link]("Amit")); // true

[Link]("Ravi");
[Link]("After removal: " + names); // [Tanya, Amit]

[Link]();
[Link]("Is Empty? " + [Link]()); // true
}
}

21. Compare the List, Set, and Queue interfaces.


22. Interface Description
List An ordered collection that allows duplicates
Set An unordered collection that does not allow duplicates
Queue A collection used to hold elements prior to processing, typically FIFO

🔄 Comparison Table
Feature List Set Queue
Order Maintained ✅ Yes (insertion order) ❌ Not guaranteed ✅ Yes (usually FIFO)
Duplicates ✅ Yes (depending on
✅ Yes ❌ No
Allowed implementation)
Indexed Access ✅ Yes (get(int index)) ❌ No ❌ No
Access elements by
Primary Purpose Ensure uniqueness Process elements in order
position
Forward (also backward
Traversal Only forward Forward only (usually)
using ListIterator)
HashSet,
Key ArrayList, LinkedList, PriorityQueue,
LinkedHashSet,
Implementations Vector ArrayDeque, LinkedList
TreeSet
Null Elements ✅ Allowed ✅ Allowed (except ✅ Allowed (some limit
Feature List Set Queue
TreeSet) null)
Depends on FIFO, priority-based, or
Ordering Type Insertion order
implementation deque-style

✅ When to Use
Use Case Recommended Interface
You need to maintain insertion order and allow duplicates List
You need to prevent duplicates (like IDs or usernames) Set
You need to process elements in a queue (e.g., tasks) Queue

🔍 Code Example of Each


List<String> list = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("A"); // duplicates allowed
[Link](list); // [A, B, A]
🔸 Set
Set<String> set = new HashSet<>();
[Link]("A");
[Link]("B");
[Link]("A"); // duplicate ignored
[Link](set); // [A, B] (unordered)
🔸 Queue
Queue<String> queue = new LinkedList<>();
[Link]("Task1");
[Link]("Task2");
[Link]([Link]()); // Task1

23. How is ArrayList different from LinkedList? Give suitable use cases.
Feature ArrayList LinkedList
Underlying Data Structure Dynamic Array Doubly Linked List
Access Time (get/set) ✅ Fast — O(1) ❌ Slow — O(n)
Insertion/Deletion at End ✅ Fast — O(1) amortized ✅ Fast — O(1)
Insertion/Deletion at Middle or
❌ Slow — O(n) ✅ Fast — O(1) (if position is known)
Start
Less memory (stores only More memory (stores data + 2
Memory Usage
data) pointers)
Very fast (due to cache
Performance on Iteration Slower
locality)
Implements List List, Deque, Queue
Random Access ✅ Supported ❌ Not supported
Thread Safety ❌ Not synchronized ❌ Not synchronized

✅ When to Use Which


🔹 Use ArrayList When:
 You want fast random access using indexes (get(i))
 Most operations involve adding/removing at the end
 You don’t insert/delete much from the middle or beginning
Example Use Cases:
 Storing list of student names
 Lookup-heavy applications
 Caching items

🔹 Use LinkedList When:


 You frequently insert/delete elements from the middle/start
 You need a Deque (double-ended queue)
 Memory is not a constraint
Example Use Cases:
 Implementing queues or stacks
 Applications with lots of insertions/deletions

✅ Example Code Comparison


List<String> arrayList = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]([Link](1)); // Fast: B

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


[Link]("A");
[Link]("B");
[Link]("C");
[Link](1); // Fast if position known
24. What are the differences between ArrayList and Vector?
ArrayList vs Vector in Java
Feature ArrayList Vector
Package [Link] [Link]
Java 1.2 (part of
Introduced In Java 1.0 (Legacy class)
Collections Framework)
❌ Not synchronized (not
Synchronization ✅ Synchronized (thread-safe)
thread-safe)
✅ Faster (no overhead of
Performance ❌ Slower (due to synchronization)
sync)
Grows by 50% of original
Growth Rate Grows by 100% (doubles in size)
size
❌ Must manually
Thread Safety ✅ Built-in thread safety
synchronize if needed
Use in Not suitable without
Suitable for multithreading (but outdated)
Multithreading manual sync
Part of Collections
✅ Fully integrated ✅ But considered legacy
API
Iterator Type Iterator (fail-fast) Iterator (fail-fast) + Enumeration (not fail-fast)
Preferred In Modern ❌ No (use ArrayList +
✅ Yes
Code [Link]()

25. Describe the Stack class. How does it implement LIFO behavior?
The Stack class in Java is a part of the [Link] package and is a subclass of Vector. It represents
a Last-In, First-Out (LIFO) data structure.
Hierarchy

↳ [Link]
[Link]

↳ [Link]
↳ [Link]<E>
LIFO Behavior
LIFO stands for Last-In, First-Out — the last element added to the stack is the first one removed.
Think of it like a stack of plates: you put new plates on top, and you remove plates from the top.

🔹 Key Methods in Stack Class


Method Description
push(E item) Adds an item to the top of the stack
pop() Removes and returns the item from the top
peek() Returns (but does not remove) the top item
empty() Checks if the stack is empty
search(Object o) Returns position of the element (1-based) or -1

✅ Example: Using Stack


import [Link];

public class StackExample {


public static void main(String[] args) {
Stack<String> stack = new Stack<>();

[Link]("A");
[Link]("B");
[Link]("C");

[Link]("Top element: " + [Link]()); // C


[Link]("Removed: " + [Link]()); // C
[Link]("Now top: " + [Link]()); // B
[Link]("Is empty? " + [Link]()); // false
}
} Output
Top element: C
Removed: C
Now top: B
Is empty? false

26. What is the Queue interface? Explain with example using LinkedList.
The Queue interface in Java, part of the Collections Framework, represents a First-In-First-Out
(FIFO) data structure — elements are added at the rear and removed from the front.
Common Implementations of Queue:
 LinkedList ✅
 PriorityQueue
 ArrayDeque
Among these, LinkedList is often used because it implements both List and Queue interfaces.
Important Methods in Queue Interface
Method Description
add(E e) Inserts the element; throws exception if fails
Method Description
offer(E e) Inserts the element; returns false if fails
remove() Removes head element; throws exception if empty
poll() Removes head; returns null if empty
element() Retrieves head; throws exception if empty
peek() Retrieves head; returns null if empty

✅ Example: Using Queue with LinkedList


import [Link].*;

public class QueueExample {


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

// Adding elements
[Link]("A");
[Link]("B");
[Link]("C");

[Link]("Queue: " + queue); // [A, B, C]

// Accessing head
[Link]("Head: " + [Link]()); // A

// Removing elements
[Link]("Removed: " + [Link]()); // A
[Link]("Queue after poll: " + queue); // [B, C]

// Check if queue is empty


[Link]("Is Empty? " + [Link]()); // false
}
}Output:
Queue: [A, B, C]
Head: A
Removed: A
Queue after poll: [B, C]
Is Empty? false
27. Explain HashSet and how it ensures uniqueness.
The HashSet class in Java is part of the Collections Framework, and it implements the Set interface.
It represents a collection of unique elements backed by a HashMap internally.

🔹 Key Features of HashSet


Feature Description
Implements Set interface
Duplicates Allowed ❌ No
Order Maintained ❌ No — it's unordered
Null Elements ✅ Allowed (only one null)
Underlying Structure Internally uses a HashMap

✅ How HashSet Ensures Uniqueness


1. When you add an element to a HashSet, it:
o Computes the hash code of the object using hashCode().
o Uses the hash to find a bucket (index) in the internal table.
o Compares with other elements in that bucket using equals() to check for duplicates.
2. If equals() returns true, the element is not added.
🔸 Therefore, both hashCode() and equals() methods play a critical role in ensuring uniqueness.

✅ Example: HashSet in Action


import [Link].*;

public class HashSetExample {


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

[Link]("Apple");
[Link]("Banana");
[Link]("Apple"); // Duplicate — will not be added

[Link](set); // Output: [Banana, Apple] (unordered)


}
}
28. Differentiate between HashSet and LinkedHashSet.
HashSet vs LinkedHashSet
Feature HashSet LinkedHashSet
Implements Set Set (extends HashSet)
Underlying Structure Backed by a HashMap Backed by a HashMap with a linked list
Order Maintained ❌ No — elements are unordered ✅ Yes — maintains insertion order
Duplicates Allowed ❌ No ❌ No
Slightly faster (no ordering
Performance Slightly slower (due to order maintenance)
overhead)
Iteration Order Unpredictable Predictable — same as insertion
Null Elements ✅ Allows one null ✅ Allows one null
When you need to preserve insertion
Use Case When order doesn't matter
order

✅ Example Code
🔹 HashSet

import [Link].*;

public class HashSetExample {


public static void main(String[] args) {
Set<String> hs = new HashSet<>();
[Link]("C");
[Link]("A");
[Link]("B");
[Link]("HashSet: " + hs); // Output may vary
}
}
🔹 LinkedHashSet
java
Copy code
import [Link].*;

public class LinkedHashSetExample {


public static void main(String[] args) {
Set<String> lhs = new LinkedHashSet<>();
[Link]("C");
[Link]("A");
[Link]("B");
[Link]("LinkedHashSet: " + lhs); // Output: [C, A, B]
}
}
29. What is SortedSet? How is TreeSet used to implement it?
The SortedSet is an interface in Java that extends the Set interface and represents a set of unique
elements sorted in ascending order.
It provides additional methods to deal with sorted data, such as getting subsets and boundaries.

🔹 Key Features of SortedSet


 No duplicate elements
 Sorted in natural order (e.g., numbers in ascending, strings alphabetically) or by a custom
comparator
 Null values are not allowed in SortedSet (via TreeSet) if the set contains non-null elements

✅ Common Implementation: TreeSet


 The most common implementation of SortedSet is TreeSet
 Internally uses a Red-Black Tree (a self-balancing binary search tree)
 Automatically keeps elements sorted
 Has O(log n) time complexity for add, remove, and lookup operations

✅ TreeSet Example
import [Link].*;

public class TreeSetExample {


public static void main(String[] args) {
SortedSet<Integer> numbers = new TreeSet<>();

[Link](50);
[Link](10);
[Link](30);

[Link]("SortedSet: " + numbers); // Output: [10, 30, 50]

[Link]("First: " + [Link]()); // 10


[Link]("Last: " + [Link]()); // 50
[Link]("HeadSet: " + [Link](30)); // [10]
}
}
Important Methods in SortedSet
Method Description
first() Returns the lowest element
last() Returns the highest element
headSet(E toElement) Returns elements less than toElement
tailSet(E fromElement) Returns elements ≥ fromElement
subSet(E from, E to) Returns elements in range [from, to)
comparator() Returns the comparator used, or null if natural order
30. What is the difference between Map and Collection interfaces in Java?
In Java, Map and Collection are both core parts of the Java Collections Framework, but
they serve different purposes and are not related by inheritance.
The Collection and Map interfaces are fundamental parts of the Java Collections Framework, but
they serve different purposes and have distinct characteristics.
Collection Interface:
 Represents a group of individual objects, known as its elements.
 Designed for storing and managing a sequence of items.
 Provides methods for adding, removing, and iterating through elements.
 Includes sub-interfaces like List, Set, and Queue, each with specific behaviors.
 Examples include ArrayList, HashSet, and LinkedList.
Map Interface:
 Represents a collection of key-value pairs, where each key is unique.
 Designed for associating keys with values, enabling efficient lookup of values based on their
keys.
 Does not extend the Collection interface, as it represents a different type of data structure.
 Provides methods for putting, getting, and removing key-value pairs.
 Examples include HashMap, TreeMap, and LinkedHashMap.
Key Differences:
 Structure: Collection stores individual elements, while Map stores key-value pairs.
 Purpose: Collection is for managing sequences of objects, while Map is for associating keys
with values.
 Hierarchy: Map does not extend Collection, indicating a different conceptual model.
 Iteration: Collection can be iterated directly, while Map requires accessing its key set, value
collection, or entry set for iteration.
 Uniqueness: Collection may or may not allow duplicate elements, while Map requires
unique keys.
In essence, Collection is for storing and managing groups of individual objects, while Map is for
storing and managing relationships between keys and values.

31. How does HashMap store key-value pairs internally?

The HashMap class in Java uses a combination of hashing and linked list / tree data structures to
store key-value pairs efficiently.

🔹 Internal Structure of HashMap


A HashMap is internally backed by an array of buckets. Each bucket is a linked list or a red-black
tree (in case of many hash collisions).
vbnet
Copy code
HashMap<Key, Value>
└──> Array of Node<K, V>[] table
├── Each Node holds:
│ ├─ hash (int)
│ ├─ key (K)
│ ├─ value (V)
│ └─ next (reference to next Node)

How Key-Value Pair Is Stored


Step-by-step process when you call [Link](key, value):
1. Hashing
The key’s hashCode() is computed, and then processed by an internal hash function to
determine the bucket index:
java
Copy code
int hash = hash([Link]());
int index = (n - 1) & hash; // n = table length
2. Bucket Selection
The computed index points to a bucket in the array (Node[]).
3. Collision Handling
o If the bucket is empty → new node is created and placed there.
o If not:
 Compare existing node(s) using equals():
 If equal key → replace value.
 If different key with same hash → chain the new node in a linked
list.
 If too many nodes (≥ 8) → the list is converted into a red-black tree
for faster access.
4. Rehashing (Resize)
If the size of the map exceeds the load factor (default 0.75 * capacity), the table is resized
(typically doubled), and all entries are rehashed.

✅ Example Illustration
java
Copy code
HashMap<String, Integer> map = new HashMap<>();
[Link]("Apple", 100);
[Link]("Banana", 200);
[Link]("Orange", 300);
Internally:
 "Apple" → hashCode() → index → bucket → store Node(key="Apple", value=100)
 "Banana" → hash → same or different index → bucket → new node or add to linked list

🔹 Node Structure
java
Copy code
static class Node<K,V> implements [Link]<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
32. What are the differences between HashMap and LinkedHashMap?
HashMap vs LinkedHashMap
Feature HashMap LinkedHashMap
❌ No ordering — elements are
Ordering ✅ Maintains insertion order of keys
unordered
Performance Slightly faster (no order overhead) Slightly slower (due to maintaining order)
Null Keys and ✅ Allows one null key and multiple
✅ Same as HashMap
Values null values
Uses a hash table (array + linked Hash table + doubly linked list for insertion
Internal Structure
list/tree) order
Iteration Order Unpredictable Predictable — as per insertion
When you want predictable iteration (like
Use Case When order doesn't matter
a cache or log)
Slightly higher (extra linked list pointers)
Memory Usage Lower (no ordering links)

Code Example
🔸 HashMap
java
Copy code
import [Link].*;

public class HashMapDemo {


public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
[Link]("Banana", 1);
[Link]("Apple", 2);
[Link]("Cherry", 3);
[Link]("HashMap: " + map); // Unordered
}
}
🔸 LinkedHashMap
java
Copy code
import [Link].*;

public class LinkedHashMapDemo {


public static void main(String[] args) {
Map<String, Integer> map = new LinkedHashMap<>();
[Link]("Banana", 1);
[Link]("Apple", 2);
[Link]("Cherry", 3);
[Link]("LinkedHashMap: " + map); // Ordered as inserted
}
}
33. Explain how TreeMap maintains the natural order of keys.
How TreeMap Maintains the Natural Order of Keys in Java
The TreeMap class in Java is part of the [Link] package and implements the Map interface. It
maintains its entries sorted according to the natural ordering of its keys (or by a custom
comparator, if provided).

🔹 Underlying Data Structure


TreeMap is internally backed by a Red-Black Tree, which is a self-balancing binary search tree (BST).
This tree structure ensures that the map remains sorted and allows logarithmic time complexity
for operations like put(), get(), remove(), etc.

🔹 What is Natural Ordering?


 Natural order is the order defined by the Comparable interface.
 For example:
o String – lexicographical (alphabetical) order
o Integer – ascending numerical order
 Custom objects must implement the Comparable interface to define their natural order.

🔹 How TreeMap Maintains the Order (Step-by-Step)


1. Key Insertion
o When a key-value pair is inserted into the TreeMap, the key’s natural ordering (via
compareTo() method) or custom comparator (compare()) determines its position in
the red-black tree.
2. Balancing
o After insertion or deletion, the red-black tree rebalances itself to maintain the order
and performance guarantees.
3. Iteration
o Iterating over a TreeMap (e.g., via entrySet(), keySet()) returns keys in sorted
(ascending) order.

🔹 Example: TreeMap with Natural Order


import [Link].*;

public class TreeMapExample {


public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();

[Link](50, "Apple");
[Link](20, "Banana");
[Link](40, "Cherry");

[Link]("Sorted Map: " + map);


// Output: {20=Banana, 40=Cherry, 50=Apple}
}
}
Example with Strings (Lexical Order)
TreeMap<String, Integer> nameMap = new TreeMap<>();
[Link]("Zebra", 1);
[Link]("Apple", 2);
[Link]("Mango", 3);

[Link](nameMap);
// Output: {Apple=2, Mango=3, Zebra=1}

34. What are the key features of Hashtable? How does it differ from HashMap?
Hashtable is a legacy class in Java that implements a key-value pair data structure, similar to
HashMap, but with some distinct characteristics.
Key Features of Hashtable
Feature Description
Thread-safe ✅ Yes — all methods are synchronized
No null keys/values ❌ Does not allow null as key or value
Legacy class ✅ Part of original Java 1.0 API
Implements Map, Cloneable, and Serializable
Hashing mechanism Uses hash codes of keys to determine storage
Performance Slower than HashMap in single-threaded applications due to synchronization
Enumeration support Supports legacy Enumeration interface for traversal

🔹 How Hashtable Differs from HashMap


Feature Hashtable HashMap
Thread-safety ✅ Synchronized (thread-safe) ❌ Not synchronized by default
✅ Faster, especially in non-threaded
Performance ⚠️Slower in single-threaded use
scenarios
❌ Not allowed (throws ✅ Allows one null key and multiple null
Null Keys/Values
NullPointerException) values
Introduced in Java 1.0 (legacy) Java 1.2 (part of Collections Framework)
Traversal Uses Enumeration Uses Iterator
Extensibility ❌ Less flexible (final methods) ✅ More flexible, widely used
Use in new
❌ No (discouraged) ✅ Yes (recommended)
projects?
Example of Hashtable
import [Link];

public class HashtableExample {


public static void main(String[] args) {
Hashtable<String, Integer> table = new Hashtable<>();

[Link]("A", 1);
[Link]("B", 2);
[Link]("C", 3);

[Link]("Hashtable: " + table);


}
}

35. What is the purpose of the Comparable interface? Give an example.


What is the Purpose of the Comparable Interface in Java?
The Comparable interface is used to define the natural ordering of objects. It allows a class to
specify how its instances should be compared, which is especially useful when sorting
collections like List, TreeSet, or TreeMap.
🔹 Purpose of Comparable
 To define the default (natural) order for the objects of a class.
 Used by sorting methods like [Link]() or [Link]().

🔹 Interface Declaration
public interface Comparable<T> {
int compareTo(T o);
}
 Returns:
o A negative number if this < o
o Zero if this == o
o A positive number if this > o

✅ Example: Student Class Sorted by Name


import [Link].*;

class Student implements Comparable<Student> {


String name;
int marks;

Student(String name, int marks) {


[Link] = name;
[Link] = marks;
}

// Define natural order: sort by name


public int compareTo(Student other) {
return [Link]([Link]); // lexicographical order
}

public String toString() {


return name + " - " + marks;
}
}

public class ComparableExample {


public static void main(String[] args) {
List<Student> list = new ArrayList<>();
[Link](new Student("Amit", 85));
[Link](new Student("Rahul", 90));
[Link](new Student("Neha", 80));

[Link](list); // Sorts using compareTo()

for (Student s : list) {


[Link](s);
}
}
} Output:
nginx
Copy code
Amit - 85
Neha - 80
Rahul - 90

36. How does the Comparator interface work? When would you use it over Comparable?
The Comparator interface in Java provides a way to define custom sorting logic for objects, while
the Comparable interface defines a natural ordering for objects of a class. Comparator is used
when you need multiple sorting criteria or when the objects you want to sort don't
implement Comparable.
Here's a breakdown of how they work and when to use them:
Comparable Interface:
 Purpose: Defines the natural ordering of a class.
 Method: compareTo(Object other): This method compares the current object with another
object and returns a negative, zero, or positive integer based on whether the current object
is less than, equal to, or greater than the other object.
 Usage: A class implements Comparable to define its own natural sorting
order. The [Link]() or [Link]() methods can then use this natural ordering.
Comparator Interface:
 Purpose:
Allows you to define custom sorting logic that can be applied to objects of any class, regardless of
whether they implement Comparable or not.
 Method:
compare(Object o1, Object o2): This method takes two objects as input and returns an integer
indicating their relative order. Like compareTo, it returns a negative, zero, or positive integer.
 Usage:
You create a Comparator class or lambda expression that implements
the compare method. This Comparator can then be passed
to [Link]() or [Link]() to sort the objects according to the custom logic you define.
When to use Comparator over Comparable:
 Multiple Sorting Criteria:
If you need to sort objects based on different criteria, you'll need a Comparator for each sorting
method. Comparable only allows for one natural ordering.
 Objects That Don't Implement Comparable:
You can use a Comparator to sort objects of classes that don't implement Comparable.
 Custom Sorting Logic:
You can define complex sorting logic using a Comparator that may not be suitable for the natural
ordering of a class.
 Non-Invasive Sorting:
Comparator allows you to sort objects without modifying the class they belong to.
 Flexibility:
Comparator offers more flexibility and control over the sorting process

37. What is the Properties class in Java? Mention a scenario where it's useful.
The Properties class in Java is a specialized subclass of Hashtable used to manage
configuration data — typically in the form of key-value pairs of Strings.
🔹 Key Features of Properties:

Feature Description
✅ Inherits from Hashtable Stores keys and values as String-String pairs
✅ Can read from .properties files Supports file I/O via load() and store() methods
✅ Used for config files Common for settings like DB configs, language resources
✅ Lightweight and easy to use Ideal for key-value config storage

// Java program to demonstrate Properties class to get all


// the system properties

import [Link].*;
import [Link].*;

public class GFG {


public static void main(String[] args) throws Exception
{
// get all the system properties
Properties p = [Link]();

// stores set of properties information


Set set = [Link]();

// iterate over the set


Iterator itr = [Link]();
while ([Link]()) {

// print each property


[Link] entry = ([Link])[Link]();
[Link]([Link]() + " = "
+ [Link]());
}
}
}

38. Describe Linked List in Java collection framework with five methods.
LinkedList is a doubly-linked list implementation of the List, Deque, and Queue interfaces in the
Java Collection Framework. It allows sequential access, dynamic memory allocation, and fast
insertions/removals (especially in the middle of the list).

🔹 Key Characteristics
 Allows duplicate elements
 Maintains insertion order
 Implements: List, Deque, Queue
 Can be used as Stack, Queue, or Deque
 Slower in random access than ArrayList (no index-based jump)

🔹 Commonly Used Methods


Here are five frequently used methods in LinkedList:
Method Description
add(E e) Adds an element to the end of the list
addFirst(E e) / addLast(E e) Adds element at the beginning / end
get(int index) Retrieves the element at a specific position
remove(int index) Removes the element at the given index
size() Returns the number of elements in the list
Example: Using LinkedList Methods
java
Copy code
import [Link];

public class LinkedListExample {


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

// 1. add()
[Link]("Java");
[Link]("Python");
[Link]("C++");

// 2. addFirst()
[Link]("HTML");

// 3. get()
[Link]("Element at index 2: " + [Link](2)); // Python

// 4. remove()
[Link](1); // Removes "Java"

// 5. size()
[Link]("List size: " + [Link]());

[Link]("Final List: " + list);


}
}

39. Describe HashMap in Java collection framework with five methods.

HashMap is a part of the Java Collections Framework and provides the implementation of a
hash table. It stores key-value pairs and allows fast access to data via hashing.

🔹 Key Characteristics of HashMap


Feature Description
Implements Map<K, V> interface
Feature Description
Key-Value Mapping Stores data in pairs (key → value)
Null allowed? ✅ One null key, multiple null values
Order maintained? ❌ No (use LinkedHashMap if needed)
Thread-safe? ❌ No (use ConcurrentHashMap for thread safety)
Performance Fast retrieval (O(1) average time)
🔹 Five Commonly Used Methods in HashMap
Method Description
put(K key, V value) Inserts a key-value pair into the map
get(Object key) Retrieves the value for a given key
remove(Object key) Removes the key (and its value) from the map
containsKey(Object key) Checks if a key exists
keySet() / entrySet() / values() Returns a view of keys, entries, or values
✅ Example: Using HashMap Methods

40. Explain the difference between Dependency Injection (DI) and Inversion of Control (IoC)
in Spring.
In Spring, Inversion of Control (IoC) is a design principle where control of object creation and
dependency management is transferred from the application code to a container or
framework (like the Spring IoC container). Dependency Injection (DI) is a specific
implementation of IoC where an object receives its dependencies from the container,
rather than creating them itself.
Here's a more detailed breakdown:
 Inversion of Control (IoC):
 IoC is a broader concept that shifts the responsibility of managing objects and
their dependencies from the application code to a container or framework.
 In Spring, the IoC container manages the lifecycle of objects (beans) and their
dependencies.
 This allows developers to focus on business logic, while the framework
handles the details of object creation and dependency resolution.
 Dependency Injection (DI):
 DI is a specific technique within the IoC framework for providing an object
with its dependencies.
 In Spring, the IoC container injects the necessary dependencies into a bean.
 DI can be achieved through constructor injection, setter injection, or field
injection.
 DI promotes loose coupling, making code more modular, testable, and
maintainable.
Key Differences:
Feature Inversion of Control (IoC) Dependency Injection (DI)

Concept A design principle that A specific technique to


transfers control of implement IoC by
object creation. providing dependencies.

Scope Broader, encompassing Narrower, focusing on


object creation, lifecycle providing dependencies
management. to objects.

Implementation Requires an IoC container Implemented within the IoC


(like Spring's). container, providing
dependencies to beans.

Focus Decoupling components, Ensuring objects receive their


promoting dependencies.
maintainability.

41. Describe:
 Spring container
 Spring bean life cycle
 Spring boot framework and its benefits
 RESTFUL API with Spring boot
70. Differentiate between:
 Character streams and Byte Streams
 wait() and notify()
71. Compare and contrast switch-case statement with switch-expression in Java.
72. What are Exceptions and how are they handled in Java? Explain try, catch, throw, throws, and
finally.
73. What are Packages in Java? How is a user-defined package created?
74. How to create a JAR file in Java?
75. What is a functional interface in Java? Give an example using @FunctionalInterface.
76. Explain Lambda Expressions. How do they help reduce boilerplate code?
77. Differentiate between Lambda Expressions and Method References with examples.

You might also like