🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, we will discuss 100+ frequently asked core Java tricky interview questions for both beginners and experienced developers.
Let's begin with simple questions.
1. What is the difference between JVM, JRE, and JDK?
JVM (Java Virtual Machine) is the engine that executes Java bytecode. When you compile a Java program, it becomes bytecode, and the JVM converts that bytecode into machine instructions. The JVM handles memory management, garbage collection, and runtime execution.
JRE (Java Runtime Environment) includes the JVM along with the core libraries required to run Java applications. It allows you to execute Java programs but does not include development tools.
JDK (Java Development Kit) includes everything in the JRE plus tools such as the compiler and debugger, making it necessary for development.
In simple terms, the JVM runs code, the JRE runs applications, and the JDK is used to develop applications.
2. What are the key components of JVM architecture?
The JVM consists of three main parts: the Class Loader subsystem, Runtime Data Areas, and the Execution Engine. The Class Loader loads compiled class files into memory. Runtime Data Areas store memory structures such as the heap and the stack. The Execution Engine interprets and optimizes bytecode execution.
Garbage Collection is also an important part of the JVM. It automatically removes unused objects from memory. Together, these components ensure secure, platform-independent execution of Java programs.
3. What memory areas exist inside the JVM?
The JVM memory is divided into heap, stack, method area (Metaspace), program counter, and native method stack. The heap stores objects and is shared across threads. The stack stores method calls and local variables and is private to each thread.
The method area stores class-level information such as metadata and static variables. The program counter keeps track of the currently executing instruction. These memory areas work together to manage application execution efficiently.
4. What is the difference between Heap and Stack memory?
Heap memory is used to store objects created during runtime. It is shared across all threads and managed by the Garbage Collector. Since it holds objects, it generally consumes more memory and has slower access compared to the stack.
Stack memory is used for method execution. It stores local variables and method call information. Each thread has its own stack, and memory is automatically released when the method finishes execution. A heap is for objects; a stack is for execution flow.
5. What are the Young Generation and the Old Generation in JVM?
The heap is divided into generations to improve garbage collection efficiency. The Young Generation stores newly created objects. Most objects are short-lived, so this area is cleaned frequently.
Objects that survive multiple garbage collection cycles are moved to the Old Generation. Garbage collection in the old generation happens less often but takes longer. This generational approach improves overall performance.
6. How does Garbage Collection work in Java?
Garbage Collection automatically removes objects that are no longer reachable. When no active reference points to an object, it becomes eligible for garbage collection.
The JVM periodically scans memory to identify unreachable objects and reclaims that memory. Modern garbage collectors focus on cleaning short-lived objects quickly while managing long-lived objects more carefully to reduce pause times.
7. What GC algorithms are available in Java?
Java provides multiple garbage collectors designed for different performance needs. Serial GC is simple and single-threaded. Parallel GC focuses on throughput using multiple threads. G1 GC balances latency and throughput and is the default in modern versions.
Newer collectors, such as ZGC and Shenandoah, aim to significantly reduce pause times. The choice of GC depends on application size and performance requirements.
8. What is Java Memory Model (JMM)?
The Java Memory Model defines how threads interact through shared memory. It ensures that changes made by one thread become visible to others in a predictable way.
JMM guarantees atomicity, visibility, and operation ordering. It explains how constructs like synchronized and volatile work. Without JMM, multi-threaded programs would produce inconsistent results due to CPU caching and instruction reordering.
9. What are Soft, Weak, and Phantom references?
Soft references allow objects to remain in memory until the JVM needs memory urgently. They are often used in caching mechanisms. Weak references allow objects to be collected as soon as no strong reference exists.
Phantom references are used for advanced memory cleanup after an object is finalized. These reference types give developers more control over memory-sensitive applications.
10. What is Java Flight Recorder (JFR)?
Java Flight Recorder is a built-in profiling and monitoring tool inside the JVM. It collects runtime data such as memory usage, garbage collection activity, and thread behavior.
It has very low overhead and is suitable for production environments. JFR helps analyze performance issues without restarting the application.
11. What is the role of the finalize() method?
The finalize() method was designed to allow cleanup before an object is garbage collected. However, it is unreliable because there is no guarantee when it will run.
Due to unpredictability and performance issues, finalize() is deprecated. Modern Java recommends using try-with-resources or explicit cleanup methods instead.
12. Can a Java application run without installing JRE?
Yes. In modern Java, applications can be packaged with a custom runtime image using tools like jlink. This bundles the required runtime components with the application.
From the user’s perspective, a separate JRE installation is not required because the runtime is included within the packaged application.
13. Can JDK exist without JRE?
In older versions, JDK and JRE were separate downloads. In modern Java versions, JRE is no longer distributed separately.
The JDK includes all runtime components required to execute Java applications. Installing JDK provides both development and runtime capabilities.
14. What is ClassLoader, and how does it work?
ClassLoader is responsible for loading class files into memory at runtime. It follows a delegation model where parent class loaders are consulted before loading a class.
This model prevents duplicate loading and ensures core Java classes are loaded safely. ClassLoader plays a critical role in maintaining security and modularity.
15. What happens during class loading in Java?
Class loading happens in three phases: loading, linking, and initialization. During loading, the class file is read into memory. Linking verifies and prepares the class for execution.
During initialization, static variables are assigned values and static blocks are executed. Only after these steps is the class ready for use.
16. What are primitive and non-primitive data types?
Primitive data types are basic data types provided by Java to store simple values. They include int, double, char, boolean, byte, short, long, and float. Primitive types store actual values directly in memory and are not objects.
Non-primitive data types, also called reference types, store references to objects rather than the actual data. Examples include String, arrays, classes, and interfaces. These types are stored in heap memory and accessed through references.
17. Can primitive types be null?
No, primitive types cannot be null because they do not represent objects. They always store a default value if not explicitly initialized as instance variables.
Only reference types can hold null because null represents the absence of an object. If a primitive needs to represent null, its corresponding wrapper class must be used instead.
18. Why doesn’t Java support pointers?
Java does not support explicit pointers like C or C++ to ensure security and memory safety. Pointers allow direct memory manipulation, which can lead to memory leaks, crashes, and security vulnerabilities.
Instead, Java uses references that point to objects without exposing memory addresses. This abstraction prevents illegal memory access and makes Java safer and more stable.
19. What are wrapper classes, and why are they needed?
Wrapper classes are object representations of primitive data types. For example, Integer wraps int, Double wraps double, and Boolean wraps boolean.
They are needed because Java is an object-oriented language, and many APIs, collections, and frameworks work only with objects. Wrapper classes allow primitive values to be treated as objects.
20. Why are wrapper classes required in collections?
Java collections such as List, Set, and Map store objects, not primitives. Since primitives are not objects, they cannot be directly stored in collections.
Wrapper classes solve this problem by converting primitive values into objects. For example, an int must be wrapped as Integer before being stored in an ArrayList.
21. What is autoboxing and unboxing?
Autoboxing is the automatic conversion of a primitive value into its corresponding wrapper object. For example, converting int to Integer happens automatically when required.
Unboxing is the reverse process, where a wrapper object is converted back into a primitive value. Java performs these conversions automatically in many situations to simplify code.
22. Can autoboxing cause unexpected behavior?
Yes, autoboxing can sometimes cause confusion, especially when comparing wrapper objects. For example, using == with wrapper objects compares references instead of values.
Additionally, repeated autoboxing and unboxing inside loops can create unnecessary objects, affecting performance. Developers should understand how conversions happen internally.
23. When can unboxing cause a NullPointerException?
Unboxing can cause a NullPointerException if the wrapper object is null. When Java tries to convert a null wrapper into a primitive, it fails because primitives cannot hold null values.
This is a common mistake when working with collections or database results. Always ensure the wrapper object is not null before unboxing.
24. What is String Pool?
The String Pool is a special memory area inside the heap where string literals are stored. When a string literal is created, Java checks whether it already exists in the pool. If it does, the same reference is reused.
This mechanism saves memory and improves performance by avoiding duplicate string objects. String literals are automatically stored in this pool.
25. When is String Pool not beneficial?
The String Pool is not beneficial when many unique strings are created dynamically. For example, generating thousands of unique strings may increase memory usage in the pool.
In such cases, using new String() or dynamic string building may be more appropriate. Excessive pooling of unique strings can lead to memory overhead.
26. Difference between String, StringBuilder, and StringBuffer?
String is immutable, meaning once created, its value cannot change. Any modification creates a new object. This makes String safe but less efficient for frequent modifications.
StringBuilder is mutable and not thread-safe. It is faster than StringBuffer and is preferred when multiple modifications are required in a single-threaded environment.
StringBuffer is also mutable but thread-safe. It is slower than StringBuilder due to synchronization.
27. When should StringBuffer be used?
StringBuffer should be used in multi-threaded environments where multiple threads modify the same string object. Its synchronized methods ensure thread safety.
If thread safety is not required, StringBuilder is usually preferred due to better performance.
28. What are packages and why are they used?
Packages are namespaces used to organize classes and interfaces. They help avoid naming conflicts and improve code organization.
Packages also control access levels and improve modularity. Large applications rely on packages to maintain clean architecture and structure.
29. What are access modifiers in Java?
Java provides four access modifiers: private, default (package-private), protected, and public.
Private members are accessible only within the same class. Public members are accessible everywhere. Protected members are accessible within the same package and subclasses. Default members are accessible within the same package only.
Access modifiers help enforce encapsulation and security.
30. Why use getters and setters instead of public fields?
Getters and setters provide controlled access to class fields. They allow validation, transformation, or logic before setting or returning values.
Public fields break encapsulation and make future modifications difficult. Using getters and setters preserves flexibility and maintains object integrity.
31. Can a top-level class be private or protected?
No, a top-level class cannot be private or protected. It can only be public or package-private (default).
Private and protected modifiers are allowed only for inner classes.
32. What is a transient keyword?
The transient keyword is used during serialization. When a field is marked transient, it will not be serialized.
This is useful for sensitive data such as passwords or for fields that can be recomputed after deserialization.
33. What is reflection in Java?
Reflection is a feature that allows inspection and modification of classes, methods, and fields at runtime.
It is used in frameworks such as Spring and Hibernate for dependency injection and object mapping. However, reflection can impact performance and bypass encapsulation if misused.
34. What is serialization and deserialization?
Serialization is the process of converting an object into a byte stream so that it can be stored or transmitted.
Deserialization is the reverse process of reconstructing the object from the byte stream. It is commonly used in distributed systems and file storage.
Good. Same structure. Clean English. 2–3 small but complete paragraphs per question. Beginner-friendly and interview-strong.
35. What is Object-Oriented Programming?
Object-Oriented Programming, or OOP, is a programming paradigm based on the concept of objects. An object represents a real-world entity and contains both data (fields) and behavior (methods). OOP allows developers to model real-world problems using classes and objects.
The main goal of OOP is to improve code organization, reusability, and maintainability. Instead of writing procedural code, OOP encourages structuring programs around objects that interact with each other.
36. What are the four pillars of OOP?
The four pillars of OOP are Encapsulation, Abstraction, Inheritance, and Polymorphism. These principles help design flexible and maintainable systems.
Encapsulation protects internal data, abstraction hides implementation details, inheritance allows reuse of existing code, and polymorphism allows objects to behave differently based on context. Together, these principles form the foundation of object-oriented design.
37. What is encapsulation?
Encapsulation is the process of bundling data and methods inside a single unit, usually a class. It restricts direct access to internal data and allows controlled access through methods.
By making fields private and providing public getters and setters, encapsulation ensures that object state cannot be modified arbitrarily. This improves reliability and maintainability of the code.
38. How does encapsulation improve security?
Encapsulation improves security by hiding sensitive data from external access. Since fields are private, external classes cannot modify them directly.
All modifications must go through controlled methods, where validation and business rules can be applied. This prevents invalid or malicious data manipulation and protects object integrity.
39. What is abstraction?
Abstraction means hiding internal implementation details and exposing only essential features. It focuses on what an object does rather than how it does it.
In Java, abstraction is achieved using abstract classes and interfaces. It helps reduce complexity and allows developers to design systems at a higher level.
40. Where is abstraction used in Java libraries?
Abstraction is widely used in Java libraries. For example, the List interface defines behavior like add and remove without specifying implementation details.
Different implementations such as ArrayList and LinkedList provide their own internal logic. The user interacts with the abstraction (List) without worrying about how it works internally.
41. What happens if a class contains an abstract method?
If a class contains an abstract method, the class itself must be declared abstract. An abstract class cannot be instantiated directly.
Any subclass of that abstract class must provide implementation for the abstract methods unless it is also declared abstract.
42. What is polymorphism?
Polymorphism means “many forms.” It allows a single interface or method name to represent different behaviors.
In Java, polymorphism enables writing flexible and extensible code. It allows objects to behave differently based on their actual runtime type.
43. What is method overloading?
Method overloading occurs when multiple methods in the same class have the same name but different parameter lists.
The compiler decides which method to call based on the number and type of arguments. Overloading is resolved at compile time and improves readability.
44. What is method overriding?
Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass.
The method signature must be the same. Overriding allows runtime polymorphism, where the method executed depends on the object’s actual type.
45. What is the difference between overloading and overriding?
Overloading happens within the same class and depends on different method parameters. It is resolved at compile time.
Overriding happens between parent and child classes with the same method signature. It is resolved at runtime using dynamic binding.
46. What is dynamic method dispatch?
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at runtime.
When a superclass reference points to a subclass object, the method that gets executed is determined by the object type, not the reference type. This enables runtime polymorphism.
47. Can constructors be polymorphic?
No, constructors cannot be polymorphic. They are not inherited and cannot be overridden.
Although constructors can be overloaded within the same class, they do not participate in runtime polymorphism.
48. What is inheritance?
Inheritance is a mechanism where one class acquires properties and behaviors of another class. The class that inherits is called a subclass, and the class being inherited from is called a superclass.
Inheritance promotes code reuse and logical hierarchy. It allows extending existing functionality without rewriting code.
49. Why is multiple inheritance not supported in Java?
Java does not support multiple inheritance with classes to avoid ambiguity problems, often referred to as the “diamond problem.”
If two parent classes contain the same method, it becomes unclear which method the child class should inherit. Java solves this by allowing multiple inheritance through interfaces only.
50. Difference between inheritance and composition?
Inheritance represents an “is-a” relationship. For example, a Dog is an Animal. It allows reuse by extending a class.
Composition represents a “has-a” relationship. For example, a Car has an Engine. Composition is generally preferred because it provides more flexibility and reduces tight coupling.
51. What is an interface?
An interface defines a contract that classes must follow. It contains method declarations without implementation, although modern Java allows default and static methods.
Interfaces support abstraction and multiple inheritance of type. They allow different classes to implement common behavior.
52. Difference between interface and abstract class?
An abstract class can contain both abstract and concrete methods, and it can have constructors and state. It is used when classes share common behavior.
An interface defines only behavior contracts and supports multiple inheritance. It is preferred when unrelated classes need to share a common capability.
53. Can an interface contain static methods?
Yes, since Java 8, interfaces can contain static methods. These methods belong to the interface itself and cannot be overridden by implementing classes.
Static methods inside interfaces are useful for utility or helper functionality related to that interface.
54. Can a functional interface extend another interface?
Yes, a functional interface can extend another interface as long as the resulting interface contains only one abstract method.
If extending another interface adds more abstract methods, it will no longer qualify as a functional interface.
55. What is the SOLID principle?
SOLID is a set of five design principles that improve code maintainability and flexibility. They include Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion principles.
These principles encourage writing modular, loosely coupled, and easily extendable code. SOLID is widely used in enterprise-level application design.
56. Explain public static void main(String[] args).
This is the entry point of a Java application. When a Java program starts, the JVM looks for this exact method signature to begin execution.
public allows the JVM to access it from outside the class. static means the method belongs to the class and can be called without creating an object. void indicates that the method does not return any value. String[] args allows passing command-line arguments when the program runs.
57. What happens if main is not static?
If the main method is not declared static, the JVM cannot invoke it. The JVM calls the main method without creating an instance of the class.
Since non-static methods require an object, the program will fail to start and result in a runtime error stating that the main method is not found in the expected format.
58. Can we overload the main method?
Yes, the main method can be overloaded. A class can contain multiple methods named main with different parameter lists.
However, only the specific signature public static void main(String[] args) is recognized as the entry point of the program.
59. Can JVM execute overloaded main?
No, the JVM only executes the main method with the standard signature. Overloaded versions of main can be called manually from inside the program.
The JVM does not automatically choose any overloaded version. It strictly looks for the predefined signature.
60. Can we override main method?
Yes, the main method can be overridden because it is static and belongs to the class. However, overriding static methods does not support runtime polymorphism.
If a subclass defines its own main method, it simply hides the parent class’s main method rather than overriding it in the traditional sense.
61. What is the static keyword?
The static keyword means the member belongs to the class rather than to an object. Static variables and methods are shared among all instances of the class.
Static members are created once when the class is loaded. They are useful for utility methods, constants, and shared resources.
62. What is a static block?
A static block is a block of code that runs when the class is loaded into memory. It executes only once, before any object is created.
Static blocks are commonly used to initialize static variables or perform setup tasks during class loading.
63. Can static block throw exception?
Yes, a static block can throw an exception. However, if an unchecked exception occurs during static initialization, it results in an ExceptionInInitializerError.
If a static block throws a checked exception, it must be handled within the block itself, as it cannot declare throws.
64. Can static methods be overridden?
Static methods cannot be overridden in the true sense. They can be hidden if a subclass defines a method with the same signature.
Since static methods belong to the class and not the object, method resolution happens at compile time, not runtime.
65. Can non-static members be accessed in static method?
Non-static members cannot be accessed directly inside a static method because static methods do not belong to any specific object.
To access non-static members, an object of the class must be created inside the static method.
66. What are this and super keywords?
The this keyword refers to the current object of the class. It is used to differentiate instance variables from local variables or to call another constructor within the same class.
The super keyword refers to the immediate parent class object. It is used to access parent class variables, methods, or constructors.
67. Can this be reassigned?
No, this cannot be reassigned. It is a final reference that always points to the current object.
It is automatically managed by the JVM and cannot be modified by the programmer.
68. Can super be used in static method?
No, super cannot be used in a static method. Since static methods belong to the class and not an object, there is no instance context.
super requires an object reference to access parent members.
69. What happens if super is used without superclass?
Every class in Java implicitly extends the Object class. Therefore, even if no explicit superclass is mentioned, super refers to Object.
However, if super is used incorrectly in a static context or where no parent member exists, it results in a compilation error.
70. What is the final keyword?
The final keyword is used to restrict modification. It can be applied to variables, methods, and classes.
A final variable cannot be reassigned. A final method cannot be overridden. A final class cannot be extended.
71. Use cases of the final keyword?
Final variables are commonly used for constants. Final methods are used to prevent modification of critical behavior in subclasses.
Final classes are used to create immutable classes or to prevent inheritance when extension is not desired.
72. How does final contribute to immutability?
In immutable classes, fields are declared final so their values cannot change after initialization.
By preventing reassignment and ensuring no setters are provided, the object’s state remains constant. This improves thread safety and reliability.
73. Performance impact of final?
Using final can allow the compiler and JVM to perform certain optimizations, such as method inlining.
However, the performance impact is usually minimal. The primary benefit of final is design clarity and immutability rather than performance improvement.
74. What is exception handling?
Exception handling is a mechanism in Java that allows a program to handle runtime errors gracefully without crashing. When an abnormal situation occurs, such as division by zero or file not found, Java creates an exception object.
Using exception handling, developers can separate normal logic from error-handling logic. This improves program stability and makes debugging easier.
75. Difference between checked and unchecked exceptions?
Checked exceptions are checked at compile time. The compiler forces the programmer to either handle them using try-catch or declare them using the throws keyword. Examples include IOException and SQLException.
Unchecked exceptions occur at runtime and are not checked by the compiler. They usually represent programming errors, such as NullPointerException or ArithmeticException. These do not require explicit handling.
76. Role of try, catch, and finally?
The try block contains code that may throw an exception. The catch block handles the exception if it occurs.
The finally block executes whether an exception occurs or not. It is typically used for cleanup activities like closing files or releasing resources.
77. Can try exist without catch?
Yes, a try block can exist without a catch block, but it must be followed by a finally block.
This pattern is commonly used when the program wants to ensure that cleanup code executes, regardless of whether an exception occurs.
78. What happens if the return is inside the try?
If a return statement is executed inside a try block, the finally block still executes before the method actually returns.
The value to be returned is determined before the finally block runs. However, if finally modifies that value, the modified value may be returned.
79. When will finally not execute?
The finally block does not execute if the JVM terminates abruptly. For example, if System.exit() is called, the finally block will not run.
It may also not execute if the program crashes due to severe errors such as hardware failure.
80. Can multiple finally blocks exist?
No, a single try block can have only one finally block.
However, multiple try-catch structures can each have their own finally block.
81. How to handle multiple exceptions in one catch?
Since Java 7, multiple exceptions can be handled in a single catch block using the pipe symbol.
This is useful when multiple exceptions require the same handling logic. It reduces code duplication and improves readability.
82. What is immutability?
Immutability means that once an object is created, its state cannot be changed.
Immutable objects do not allow modification of their internal data after construction. Examples include String and wrapper classes.
83. How to create an immutable class?
To create an immutable class, declare the class as final so it cannot be extended. Make all fields private and final.
Do not provide setter methods. Initialize all fields through the constructor. If the class contains mutable objects, return defensive copies instead of original references.
84. Why are immutable objects thread-safe?
Immutable objects are thread-safe because their state cannot change after creation.
Since no thread can modify the object, multiple threads can safely read the same object without synchronization.
85. What is a Singleton class?
A Singleton class ensures that only one instance of a class exists throughout the application.
It provides a global access point to that single instance. Singleton is commonly used for configuration, logging, and resource management.
86. How to implement a thread-safe Singleton?
A thread-safe Singleton can be implemented using synchronized methods, double-checked locking, or static initialization.
The safest and simplest approach is using an enum or static initialization because it guarantees thread safety and prevents multiple instantiations.
87. What happens if multiple threads create a Singleton simultaneously?
If a Singleton is not implemented properly, multiple threads may create multiple instances simultaneously.
This breaks the Singleton principle and can lead to inconsistent behavior. Proper synchronization or safe initialization techniques are necessary to prevent this issue.
88. What is the Java Collection Framework?
The Java Collection Framework is a unified architecture for storing and manipulating groups of objects. It provides ready-made data structures such as lists, sets, queues, and maps, along with algorithms to operate on them.
It reduces the need to write custom data structures and ensures consistent, reusable, and efficient implementations. The framework improves productivity and performance by offering optimized and well-tested collections.
89. Main interfaces ofthe Collection Framework?
The main interfaces are List, Set, Queue, and Map.
List allows duplicate elements and maintains insertion order. Set does not allow duplicates.
Queue represents elements in a processing order such as FIFO.
Map is slightly different because it stores key-value pairs rather than individual elements. These interfaces define contracts that are implemented by concrete classes like ArrayList, HashSet, and HashMap.
90. How does Iterator work?
Iterator is used to traverse elements in a collection one by one. It provides methods to check whether more elements exist and to retrieve the next element.
Iterator also allows safe removal of elements during traversal. It helps avoid concurrent modification issues that may occur when modifying a collection during iteration.
91. How to choose the right collection?
Choosing the right collection depends on requirements such as ordering, duplication, lookup speed, and thread safety.
If duplicates and order matter, List is appropriate. If uniqueness is required, Set is better. If fast key-based lookup is needed, Map is suitable. Performance characteristics such as insertion and retrieval complexity also influence the choice.
92. Internal working of HashMap?
HashMap stores data in key-value pairs using a hashing mechanism. When a key is inserted, its hash code is calculated to determine the bucket location.
Each bucket stores entries either as a linked list or a balanced tree. When retrieving a value, HashMap calculates the hash again to quickly locate the correct bucket and then searches within it.
93. What happens when two keys have the same hashcode?
If two keys have the same hash code, they are stored in the same bucket. This situation is called a collision.
In earlier Java versions, collisions were handled using a linked list. In modern Java versions, if the number of elements in a bucket exceeds a threshold, the structure converts into a balanced tree to improve performance.
94. Changes in HashMap after Java 8?
Before Java 8, collisions were handled using linked lists. This could degrade performance to linear time if many collisions occurred.
From Java 8 onwards, if a bucket contains more than a certain number of entries, it converts into a red-black tree. This improves worst-case performance from O(n) to O(log n).
95. Time complexity of HashMap and HashSet?
In average cases, insertion, deletion, and retrieval operations in HashMap and HashSet take constant time, O(1).
In worst-case scenarios with heavy collisions, time complexity can degrade. However, after Java 8 improvements, worst-case complexity becomes O(log n) when tree structures are used.
96. Time complexity of TreeSet?
TreeSet is implemented using a balanced tree structure. Therefore, insertion, deletion, and retrieval operations take O(log n) time.
Unlike HashSet, TreeSet maintains elements in sorted order, which explains the logarithmic complexity.
97. When to use TreeSet over HashSet?
TreeSet should be used when the sorted order of elements is required. It automatically sorts elements according to natural ordering or a custom comparator.
If ordering is not required and faster performance is needed, HashSet is usually preferred.
98. What is ConcurrentHashMap?
ConcurrentHashMap is a thread-safe version of HashMap designed for multi-threaded environments.
Unlike a traditional HashMap, it allows multiple threads to read and write concurrently without locking the entire map.
99. How does ConcurrentHashMap improve performance?
ConcurrentHashMap improves performance by allowing concurrent access to different segments of the map.
Instead of locking the whole structure, it uses finer-grained locking or lock-free mechanisms, allowing higher throughput in multi-threaded applications.
100. Can a class be used as a key in HashMap?
Yes, a class can be used as a key in a HashMap. However, the class must properly override the equals() and hashCode() methods.
If these methods are not implemented correctly, the map may behave unpredictably, such as failing to retrieve stored values correctly.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment