0% found this document useful (0 votes)
5 views16 pages

Java Interview Guide: Key Concepts Explained

The document is an interview guide that outlines important differences in Java concepts such as List vs Set, Array vs ArrayList, and Interface vs Abstract Class. It covers various programming topics including method overloading vs overriding, static vs non-static methods, and the use of final vs finally in exception handling. Each section provides definitions, key features, and examples to clarify the distinctions between these Java elements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Java Interview Guide: Key Concepts Explained

The document is an interview guide that outlines important differences in Java concepts such as List vs Set, Array vs ArrayList, and Interface vs Abstract Class. It covers various programming topics including method overloading vs overriding, static vs non-static methods, and the use of final vs finally in exception handling. Each section provides definitions, key features, and examples to clarify the distinctions between these Java elements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Fun Doo

TT EES TSE RT E R S

Interview Guide

Java
Cheatsheet
vol.4
Important Differences in Java

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

1. List VS Set
Feature List Set

An ordered collection that allows An unordered collection that doesn’t allow duplicate
Definition
duplicate elements. elements.

Key Interfaces [Link] (e.g., ArrayList, LinkedList) [Link] (e.g., HashSet, TreeSet, LinkedHashSet)

Allows Duplicates Yes No

No (Order depends on implementation: e.g., HashSet


Maintains Order Yes (Insertion order is maintained) doesn’t maintain order, TreeSet sorts elements,
LinkedHashSet maintains insertion order)

Access Elements By index using get(int index) By iterator or enhanced for loop

Allows multiple null values (in some Allows only one null value (in implementations like
Null Elements
implementations like ArrayList). HashSet).

Performance Typically slower as it requires traversal (unless using


Faster for indexed access (e.g., ArrayList)
(Search) HashSet for constant-time search).

Common Use Use when duplicates are allowed or Use when duplicates need to be avoided or for fast
Cases when ordering is important. membership checks.

Examples ArrayList, LinkedList, Vector HashSet, TreeSet, LinkedHashSet

[Link] VS ArrayList
Feature Array ArrayList
A fixed-size, contiguous memory data
Definition A resizable, dynamic array implementation in Java.
structure.
Size Fixed at the time of declaration. Dynamic and can grow or shrink as needed.
Can only store objects (autoboxing handles
Type Can store primitives and objects.
primitives).

Faster due to no overhead of resizing or Slightly slower due to resizing and boxing/unboxing
Performance
boxing/unboxing. of primitives.

Uses less memory since no extra features Consumes more memory due to dynamic resizing
Memory Usage
are provided. and internal operations.

Does not require size initialization; grows


Initialization Must be initialized with a fixed size.
dynamically.
Access elements using index Access elements using methods like get(index) and
Access Syntax
(array[index]). set(index, value).
Iterating Use loops (for, for-each). Use loops or Iterator for enhanced iteration.
Cannot add or remove elements after
Adding Elements Use add() to insert elements dynamically.
creation.
Removing Not supported; must manually shift
Use remove() to delete elements.
Elements elements.
Supports No generics support; type must be
Supports generics to enforce type safety.
Generics defined explicitly.

Length/Size Use [Link] to get the size. Use [Link]() to get the size.
Allowed; no restrictions on the count of
Null Elements Allowed; can store multiple null values.
nulls.
Multi- Supports multi-dimensional arrays (e.g., Does not directly support multi-dimensional
Dimensional int[][]). structures.
Best for fixed-size collections or
Usage Ideal for dynamic collections where size can change.
performance-critical operations.
[Link] package as part of the Java Collections
Belongs To
@fundootesters
@fundootesters
java package as a core feature.
150K+ Community
150K+ Community
Framework.
Fun Doo
TT EES TSE RT E R S

3. Interface VS Abstract Class


Feature Interface Abstract Class

A contract specifying what a class must A class that provides partial implementation with
Definition
implement. abstract methods.

Keyword Declared using the interface keyword. Declared using the abstract keyword.

Methods are abstract by default (since Java


Methods Can include both abstract and concrete methods.
8, can include default and static methods).

Variables are public, static, and final by


Variables Can have instance variables (non-static, non-final).
default.

Can have constructors (but cannot instantiate


Constructor Cannot have constructors.
directly).

A class can implement multiple interfaces A class can extend only one abstract class (single
Inheritance
(multiple inheritance supported). inheritance).

Access Modifiers Methods are public by default. Methods can have any access modifier.

Multiple Supports multiple inheritance through


Does not support multiple inheritance directly.
Inheritance multiple interfaces.

Used to define a contract or behavior that Used to define a base class with shared
Usage
multiple classes can implement. functionality for related classes.

Default Only default and static methods can have Can provide concrete methods with complete
Implementation bodies (Java 8+). implementation.

Slightly slower as methods are abstract by Faster as some methods may already be
Performance
nature. implemented.

abstract class Animal { abstract void makeSound();


Examples interface Animal { void makeSound(); }
void sleep() { } }

4. Super() Vs this()
Feature super() this()

Refers to the parent class (superclass)


Definition Refers to the current class (this class) constructor.
constructor or methods.

Used to call the constructor or methods of


Usage Used to call the constructor of the current class.
the parent class.

Constructor Call Calls the parent class constructor. Calls another constructor of the same class.

Accessing Parent Can be used to invoke parent class Cannot be used to call parent class methods
Methods methods or fields. directly; it’s used within the same class.

Constructor Can be used with the parent class Can be used with overloaded constructors in the
Overloading constructor when overloading is involved. same class to avoid code duplication.

First Statement in Must be the first statement in the Must be the first statement in the constructor, if
Constructor constructor. used.

Refers to the immediate superclass (one


Scope Refers to the current object of the class.
level up).

super(); (calls the parent class default this(10); (calls another constructor in the same
Example
constructor). class with argument 10).

Used to create a chain between parent Used to create a constructor chain within the
Constructor Chain
and child class constructors. current class.

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

5. String vs StringBuilder vs StringBuffer


Feature String StringBuilder StringBuffer

Immutable (cannot be Mutable (can be modified after Mutable (can be modified after
Immutability
modified after creation). creation). creation).

Thread-safe (synchronized
Thread Safety Not thread-safe. Not thread-safe.
methods).

Slow for concatenation Faster than String for


Slower than StringBuilder due
Performance (creates a new object on concatenation (modifies the
to synchronization.
each modification). same object).

N/A (not applicable as it is


Default Capacity 16 characters. 16 characters.
immutable).

Uses more memory since a


More memory efficient Uses more memory due to
Memory Usage new object is created on
(modifies the same object). synchronization.
modification.

Synchronized methods provide


Thread Safety Not applicable, as String is No synchronization, making it
thread safety but result in
Mechanism immutable. faster but not thread-safe.
overhead.

Suitable for single-threaded Suitable for multi-threaded


Suitable for constants and
Usage applications or when string applications where string
values that don't change.
modification is needed. modification is needed.

StringBuilder sb = new StringBuffer sb = new


Example String s = "Hello"; StringBuilder("Hello"); StringBuffer("Hello");
[Link](" World"); [Link](" World");

More efficient for frequent


Not efficient for frequent Less efficient than StringBuilder
Efficiency modifications (better for
modification operations. due to synchronization.
performance).

6. Method Overloading Vs Method Overriding


Feature Method Overloading Method Overriding

Redefines a method from the parent class in


Allows a class to have multiple methods with
Definition a subclass to provide specific
the same name but different parameters.
implementation.

Achieves compile-time polymorphism (method Achieves runtime polymorphism (subclass-


Purpose
behavior varies based on parameters). specific behavior at runtime).

Happens between a parent class and a


Class Involvement Happens within a single class.
subclass.

Methods must have different parameter lists Method must have the same parameter list
Parameters
(type, number, or order). as in the parent class.

Can have different return types as long as Must have the same return type (or a
Return Type
method signatures differ. covariant return type).

Cannot reduce the visibility of the


Access Modifiers No restrictions; can have any valid modifier.
overridden method.

Only instance methods can be overridden


Static/Instance Methods Can overload both static and instance methods.
(static methods are hidden, not overridden).

Determined at runtime using dynamic


Binding Time Determined at compile time.
method dispatch.

Typically marked with the @Override


Annotations Does not require annotations.
annotation (optional but recommended).

Not related to inheritance; works within the Requires inheritance (between parent and
Inheritance
same class. child classes).

Overloaded methods can throw different Overriding methods cannot throw broader
Exceptions
exceptions. exceptions than the parent method.

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

7. Static Vs Non Static


Feature Static Non-static

Belongs to the class itself, rather than


Definition Belongs to an instance of the class.
instances.

No need for a keyword; simply declared


Keyword Declared using the static keyword.
without static.

Allocated once when the class is loaded into


Memory Allocation Allocated every time an object is created.
memory.

Can be accessed without creating an Requires an instance of the class to be


Access
instance of the class. accessed.

Instance Association Does not belong to any particular instance. Belongs to a specific object instance.

Can Access Non-static Cannot directly access non-static members Can access both static and non-static
Members (fields or methods). members.

Inherited by all instances of the class, but Inherited and can be overridden in a
Inheritance
cannot be overridden. subclass.

Static members cannot use constructors


Non-static members are initialized inside
Constructor directly, but can be initialized using static
constructors.
blocks.

Used for class-level methods, variables, and Used for instance-specific methods and
Usage
constants. variables.

Exists as long as the class is loaded in


Lifecycle Exists as long as the object instance exists.
memory.

Example static int count; int count;

8. Collection Vs Collections
Feature Collection Collections

Type Interface Utility class (final class)

Represents a group of objects, typically a Provides static methods for operating on


Definition
single container (like a list, set, or queue). or returning collections.

Package [Link] [Link]

Used to define the base interface for all Used to provide methods to manipulate or
Purpose
collection classes (List, Set, Queue, etc.). query collections (sorting, searching, etc.).

Defines basic collection operations like Provides utility methods like sort(),
Methods
add(), remove(), size(), etc. reverse(), shuffle(), max(), min(), etc.

Extends Iterable and implemented by Does not extend any class and is a final
Extends/Implements
collection classes like List, Set, etc. class.

Used when defining a collection type (e.g., Used when performing operations on a
Use Case
List, Set). collection (sorting, synchronizing, etc.).

Can be inherited and implemented by other


Inheritance Cannot be inherited as it is a final class.
classes.

Example Collection<Integer> list = new ArrayList<>(); [Link](list);

Not necessarily thread-safe (e.g., ArrayList is [Link]() can be used


Thread Safety
not thread-safe). to create thread-safe collections.

Provides a utility method to make


Thread Safety Thread-safety depends on the specific
collections thread-safe (e.g.,
Mechanism collection class (e.g., CopyOnWriteArrayList).
synchronizedList()).

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

9. Static (class) method VS Instance method


Feature Static (Class) Method Instance Method

Definition Belongs to the class, not instances of the class. Belongs to an instance of the class.

Keyword Declared with the static keyword. Declared without the static keyword.

Can be accessed without creating an instance of the Can only be accessed through an instance of the
Access
class. class.

Typically used for operations that are independent of Typically used for operations that depend on object
Usage
object state. state.

Allocated once when the class is loaded into Allocated each time an instance of the class is
Memory Allocation
memory. created.

Cannot be called using an object reference (unless


Call from Instance Can be called using an object reference.
specifically qualified).

Access to Instance Cannot directly access instance variables or Can access both instance and static variables/
Members methods. methods.

Can access both static and non-static variables/


Access to Static Members Can directly access static variables and methods.
methods.

Inheritance Inherited by subclasses, but cannot be overridden. Inherited and can be overridden in subclasses.

Constructor Call Cannot be invoked from constructors. Can be invoked within constructors.

Not inherently thread-safe, but no synchronization Instance methods can be synchronized for thread
Thread Safety
needed for instance-specific data. safety.

public static void display() { public void printMessage() {


Example
[Link]("Hello"); } [Link](message); }

Instance Dependency Does not depend on instance state. Depends on instance state (object variables).

10. Final Vs Finally


Feature final finally

A keyword used to define constants, prevent method A block of code used for exception handling, which
Definition
overriding, or prevent inheritance. always executes after a try-catch block.
Used in exception handling to ensure that the block
Usage Can be applied to variables, methods, and classes. of code is executed regardless of whether an
exception is thrown or not.

Scope Can be applied to: Can only be used within a try-catch block structure.

Can be applied to Variables, Methods, Classes. Only a block of code after a try or catch.

Used to make variables constant (cannot be


Ensures a block of code runs after try-catch,
Purpose changed), prevent method overriding, and prevent
whether an exception is thrown or not.
class inheritance.
The value of a final variable cannot be changed once
Effect on Variables Not applicable.
initialized.

Effect on Methods A final method cannot be overridden by subclasses. Not applicable.

Effect on Classes A final class cannot be subclassed. Not applicable.

The finally block executes after the try-catch block,


Execution final does not influence execution flow directly.
regardless of an exception occurrence.

Can be used in exception Yes, it is used in conjunction with try-catch to


No
handling execute clean-up code.

Example (Variable) final int x = 10; N/A

Example (Method) public final void display() { } N/A

Example (Class) public final class MyClass { } N/A

Example (Finally Block) N/A try { } catch (Exception e) { } finally { }

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

11. Composition vs Aggregation


Feature Composition Aggregation

Represents a "Has-A" relationship where


Represents a "Has-A" relationship where one object
one object contains another, and the
Definition contains another, but the contained object can exist
contained object cannot exist without the
independently.
container.

The lifetime of the contained object is


The lifetime of the contained object is independent of
Lifetime Dependency dependent on the lifetime of the container
the container object.
object.

The container object owns the contained The container object does not own the contained
Ownership object. If the container is destroyed, the object. The contained object can exist outside the
contained object is also destroyed. container.

A Library class contains Books. If the


A Department class contains Professor objects. A
Example library is deleted, the books are deleted as
professor can exist without being in a department.
well.

Contained objects are created and Contained objects can exist independently and may
Life Cycle
destroyed with the container object. outlive the container object.

Typically implemented by declaring the


Typically implemented by passing the contained
Implementation contained object as a field within the
object to the container class via a constructor or setter.
container class.

class Library { private Book book; } (Book class Department { private Professor professor; }
Example Code
cannot exist without Library). (Professor can exist outside the Department).

Stronger relationship, as the contained Weaker relationship, as the contained object can exist
Strength of Relationship
object cannot exist independently. independently.

If the House is deleted, the Room is If a Team is deleted, the Player may still exist in
Example of Independence
deleted. another Team.

12. ArrayList vs LinkedList


Feature ArrayList LinkedList
Implementation Implements a dynamic array. Implements a doubly linked list.
Underlying Data Structure Array-based. Linked list (node-based).

Faster for random access (constant time:


Access Time Slower for random access (linear time: O(n)).
O(1)).

Slower for insertion/deletion (O(n)) due to Faster for insertion/deletion (O(1)) if at the beginning or
Insertion/Deletion Time
shifting elements (except at the end). end, but can be slower in the middle due to traversal.

Lower memory overhead as it uses a Higher memory overhead due to storing references/
Memory Overhead
contiguous block of memory. pointers in each node.

Resizes when the array is full, which can be No resizing required, as it dynamically allocates
Resizing
an expensive operation. memory as needed.

Best suited for scenarios with frequent Best suited for scenarios where frequent insertions or
Use Case
random access operations. deletions occur (especially at the beginning or middle).
Iteration Performance Faster for iteration (due to array structure). Slower iteration (due to traversal of nodes).

More memory efficient, as it stores only the Less memory efficient, as it stores pointers in addition
Memory Efficiency
actual data. to data.

Not thread-safe (can be made thread-safe Not thread-safe (can be made thread-safe using
Thread Safety
using [Link]()). [Link]()).
Example Code ArrayList<String> list = new ArrayList<>(); LinkedList<String> list = new LinkedList<>();

Performance for Add() at


Fast (amortized constant time: O(1)) Fast (constant time: O(1))
End

Performance for Remove()


Fast (constant time: O(1)) Fast (constant time: O(1))
at End

Performance for Add() at


Slow (O(n)) Fast (O(1))
Beginning

Performance for Remove()


Slow (O(n)) Fast (O(1))
at Beginning

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

13. Iterator and ListIterator


Feature Iterator ListIterator

Interface Interface in [Link] Interface in [Link]

Provides basic methods: hasNext(), Extends Iterator and adds methods like
Method Availability
next(), and remove(). hasPrevious(), previous(), add(), and set().

Can only traverse in the forward Can traverse in both forward and backward
Traversal Direction
direction. directions.

Allows modification of the collection Allows modification of the collection through add(),
Modification
through remove(). set(), and remove().

Primarily used to iterate over any Primarily used for iterating over List
Used For
collection (List, Set). implementations (e.g., ArrayList, LinkedList).

Can only move forward and doesn't Can move both forward and backward, and can
Positioning
allow going backward. manipulate the cursor position.

Supports Index-based Provides index-based access (nextIndex() and


No index-based access.
Access previousIndex()).

Does not support adding elements Supports adding elements via add() method
Add Elements
during iteration. during iteration.

Does not support setting elements Supports setting elements via set() method during
Set Elements
during iteration. iteration.

Example Code Iterator<String> iterator = [Link](); ListIterator<String> listIterator = [Link]();

Works with any collection, but typically More efficient for List traversal, as it has additional
Performance
slower than ListIterator for List. capabilities.

Backward Traversal Not supported. Supported.

14. HashMap vs HashTable


Feature HashMap Hashtable

Package [Link] [Link]

Not thread-safe (can be synchronized


Thread Safety Thread-safe (synchronized).
externally).

Allows one null key and multiple null


Null Keys/Values Does not allow null keys or values.
values.

Performance Faster due to lack of synchronization. Slower due to synchronization overhead.

Uses fail-fast iterator (throws


Uses fail-fast iterator, but thread synchronization
Iterator Type ConcurrentModificationException if
can affect performance.
modified while iterating).

Part of the modern Java collection Part of the legacy collection framework
Legacy
framework (introduced in Java 1.2). (introduced in Java 1.0).

Preferred in most scenarios where Mostly used in older applications, or when thread-
Usage
thread-safety is not a concern. safety is a priority.

Synchronization Not synchronized by default. Synchronized by default.

Cannot store null key or value (throws


Null Handling Can store null as a key or value.
NullPointerException).

HashMap<String, Integer> map = new Hashtable<String, Integer> map = new


Example Code
HashMap<>(); Hashtable<>();

Can be resized as required using resize() Resizing is done using rehash() internally, which
Size/Capacity
method when threshold is met. may cause performance issues.

16, and grows dynamically when


Default Initial Capacity 11, and grows when 75% capacity is reached.
threshold is exceeded.

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

15. Comparable and Comparator


Feature Comparable Comparator

Package [Link] [Link]

Used to define the natural ordering of


Purpose Used to define custom ordering for objects of a class.
objects of a class.

Method Used compareTo(Object obj) compare(Object obj1, Object obj2)

A class must implement the Comparable


Implementation A class must implement the Comparator interface.
interface.

Used by methods like [Link]() or Used by [Link]() or [Link]() to sort using


Sorting Method
[Link]() to sort objects naturally. custom criteria.

The class must implement Comparable, No need to modify the class. Can create multiple
Modification of Class
meaning its natural ordering is fixed. comparators.

Multiple sorting criteria (can create different


Number of Sort Criteria One sorting criterion (natural order).
comparators).

Defines a single sorting logic (e.g., Can define multiple sorting logics, like sorting by
Sorting Logic
ascending or descending). name, age, etc.

public class Person implements


public class AgeComparator implements
Comparable<Person> { public int
Example Code Comparator<Person> { public int compare(Person p1,
compareTo(Person p) { return [Link] -
Person p2) { return [Link] - [Link]; } }
[Link]; } }

The comparison logic must handle null Can also handle null values as per custom logic in the
Null Handling
values (if needed). compare() method.

Less flexible since the sorting criteria are More flexible as you can define different comparators
Flexibility
fixed in the class itself. for different sorting orders.

Used when you want a default or natural Used when you want different ways of sorting objects
Use Case
ordering for objects of a class. or need custom sorting logic.

16. Checked vs Unchecked Exceptions


Feature Checked Exceptions Unchecked Exceptions

Exceptions that are checked at compile- Exceptions that are not checked at compile-time
Definition
time. (runtime exceptions).

Subclasses of Exception but not


Class Subclasses of RuntimeException and Error.
RuntimeException.

Must be either caught or declared to be


Handling Requirement Not required to be explicitly caught or declared.
thrown using throws keyword.

Compile-Time Check Checked by the compiler. Not checked by the compiler.

NullPointerException,
IOException, SQLException,
Example ArrayIndexOutOfBoundsException,
FileNotFoundException.
ArithmeticException.

Usually caused by external factors (e.g., file Typically caused by bugs or logical errors in the code
Cause
I/O, network). (e.g., accessing null, array bounds).

Used for scenarios where the programmer


Used for programming errors that should be fixed
Use Case can handle or recover from the exception
(e.g., incorrect array access).
(e.g., I/O operations).

The program will not compile if a checked The program can run and throw these exceptions
Runtime Behavior
exception is not handled. during runtime.

Requires the developer to explicitly


Program Flow handle the exception (either catch it or Does not require explicit handling or declaration.
declare it with throws).

try { FileReader fr = new


int result = 10 / 0; (throws ArithmeticException at
Example Code FileReader("[Link]"); } catch (IOException
runtime).
e) { [Link](); }

Directly inherits from Exception (not


Parent Class Directly inherits from RuntimeException.
RuntimeException).

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

17. List vs Set vs MAP


Feature List Set Map
Package [Link] [Link] [Link]
Interface Implements the List Implements the Set Implements the Map
Type interface. interface. interface.
Does not guarantee
Maintains the insertion Does not guarantee any
any order
Order order (ordered order (unordered
(unordered
collection). collection).
collection).
Does not allow
Allows duplicate
duplicate elements Allows only unique keys
elements (can store
Duplicates (only one but can have duplicate
multiple occurrences
occurrence of each values.
of the same element).
element).
Does not allow
Can access elements
Accessing random access; Accessed by key, not by
by index (random
Elements elements can only index.
access).
be traversed.
Implementat ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap,
ion Classes Vector. LinkedHashSet. LinkedHashMap.
Allows null
Null Allows null elements Allows null values and
elements (but only
Elements (both keys and values). one null key.
one null element).
Not thread-safe (unless Not thread-safe
Not thread-safe (unless
Thread Safety explicitly (unless explicitly
explicitly synchronized).
synchronized). synchronized).
Slower insertion/
Faster access and Very fast retrieval by
removal of elements
Performance retrieval (except for key (average O(1) time
(due to shifting or
TreeSet which sorts). complexity).
linked list traversal).
Used when
Used when ordering
uniqueness is Used when key-value
Use Case and duplicates are
important and order pairs are needed.
important.
does not matter.
Can iterate by index or Iterates over unique Iterates over key-value
Iteration
using an iterator. elements. pairs.
Map<String, Integer>
Example List<String> list = new Set<String> set =
map = new
Code ArrayList<>(); new HashSet<>();
HashMap<>();
TreeSet can be TreeMap sorts by key,
Can be sorted using
Sorting sorted, but HashSet HashMap does not
[Link]().
cannot be sorted. guarantee order.

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

18 PriorityQueue vs TreeSet
Feature PriorityQueue TreeSet
Package [Link] [Link]
Implements the Queue
Interface Implements the Set interface.
interface.
Elements are ordered based on Elements are ordered based on
their natural ordering or by a their natural ordering or by a
Ordering
custom comparator provided custom comparator provided at
at the time of creation. the time of creation.
Does not allow duplicate
Duplicates Allows duplicate elements.
elements (only unique elements).
Null Elements Does not allow null elements. Does not allow null elements.
Implements a priority queue,
Implements a navigable set,
which is an unbounded,
Type of Collection which is a sorted set without
thread-safe collection with
duplicates.
priority-based ordering.
Automatically sorts elements Elements are stored in a sorted
Sorting based on priority (using natural order (ascending or as defined by
ordering or comparator). a comparator).
Useful when elements need to
Useful when a set of unique
be processed in a specific order
Use Case elements needs to be stored and
based on priority (e.g., task
retrieved in a sorted order.
scheduling, event simulation).
Provides O(log(n)) time Provides O(log(n)) time
Performance complexity for insertions and complexity for insertions,
removals. removals, and lookups.
Not thread-safe (must be
Not thread-safe (must be
externally synchronized if used
Thread Safety externally synchronized if used in
in a multi-threaded
a multi-threaded environment).
environment).
Implementation
PriorityQueue TreeSet
Classes
Iterates in ascending order of the
Iterates in order of priority, not
Iterator elements (natural order or
necessarily sorted order.
comparator-defined order).
PriorityQueue<Integer> pq = TreeSet<Integer> ts = new
Example Code
new PriorityQueue<>(); TreeSet<>();
An empty queue has no
elements and throws An empty set simply returns null
Empty Queue/Set
NoSuchElementException on for methods like first() or last().
poll().
Throws NullPointerException if Throws NullPointerException if
Null Handling
null is added. null is added.

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

19 Singly Linked List vs Doubly Linked List

Feature Singly Linked List Doubly Linked List


A linked list where each node
A linked list where each node
contains data, a reference to the
Definition contains data and a reference
next node, and a reference to
to the next node.
the previous node.
Each node has two pointers
Each node has one pointer
Node Structure (next and previous) to the next
(next) to the next node.
and previous nodes.

Can be traversed in both


Can only be traversed in one
Traversal directions (from head to tail and
direction (from head to tail).
tail to head).

Requires less memory Requires more memory due to


Memory Usage because each node only stores two pointers (next and previous)
one pointer. in each node.

Insertion and deletion are Insertion and deletion are faster


Insertion and
simpler and faster at the head, as you can access both the next
Deletion
but slower at the tail. and previous nodes.

Does not have access to the


Access to Has access to the previous node,
previous node, so it's not
Previous Node enabling bidirectional traversal.
possible to move backward.

More efficient in terms of More efficient for operations


Efficiency for memory usage but less requiring reverse traversal or
Operations efficient for certain operations modifications at both ends of
(like reverse traversal). the list.
Reversing is more complex as Reversing is easier since each
Reversing the List you only have a reference to node has a reference to both the
the next node. next and previous nodes.

Easier to implement due to More complex to implement due


Implementation
having fewer references to to managing both next and
Complexity
manage. previous references.

Node head = new Node(10);


Node head = new Node(10); Node second = new Node(20);
Example Code
[Link] = new Node(20); [Link] = second; [Link]
= head;
Suitable for simple use cases Suitable for more complex use
where forward traversal and cases requiring backward
Use Case
memory efficiency are traversal or frequent insertions/
required. deletions at both ends.

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

20 Throw vs Throws vs Throwable


Feature throw throws Throwable
A keyword used to A keyword used in
A class in the Java
explicitly throw an method declarations
hierarchy that is the
Definition exception in a to specify that the
superclass of all
method or block of method can throw one
exceptions and errors.
code. or more exceptions.
Clause in method
Type Statement. Class.
signature.
Used to throw an Used to declare Represents all exceptions
Usage exception object exceptions a method (Exception) and errors
explicitly. might throw. (Error) in Java.
throw new
public void method() public class MyException
Syntax Exception("Error
throws IOException { } extends Throwable { }
message");
Inside the method In the method Used as a base class to
body to throw an declaration to indicate define custom exceptions
When Used
exception at potential exceptions or to handle all errors and
runtime. that might be thrown. exceptions.
Works for both Handles both checked
Only used for checked
Checked vs checked and (Exception) and
exceptions (mandatory
Unchecked unchecked unchecked (Error)
declaration).
exceptions. exceptions.
To declare exceptions
To represent the base
To trigger an for a method,
Purpose class for all exceptions
exception. informing the caller to
and errors.
handle them.
Applies to the exception
Local to the Applies to the
hierarchy and can be
Scope method or block method’s signature,
extended to define
where it is used. visible to the caller.
custom exceptions.
throw new
Example void readFile() throws class MyThrowable
IOException("File
Code IOException { ... } extends Throwable { ... }
not found");
Not part of the Not part of the Superclass of Exception
Hierarchy
hierarchy. hierarchy. and Error.
Used to propagate Used to indicate the
Exception Defines base functionality
an exception for caller should handle
Handling for exception handling.
handling. exceptions declared.

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

Complete Explanation of Question 9 on Fun Doo Testers YT

Complete Explanation of Question 10 on Fun Doo Testers YT

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

Latest Videos

Free Tutorials

In English In Hindi

Checkout "Fun Doo Testers"


YouTube

@fundootesters
@fundootesters
150K+ Community
150K+ Community
Fun Doo
TT EES TSE RT E R S

For more Testing


Events & to stay
updated in industry

Follow "Fun Doo Testers"

Write us on: contact@[Link]

@fundootesters
@fundootesters
150K+ Community
150K+ Community

You might also like