This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.
Identity, Image, and Privacy Notice
To respect individual privacy, some names, profile photographs, avatars, biographical details, and other identifying information displayed in this guide may be replaced with pseudonyms, licensed stock images, illustrative avatars, composite images, or representative descriptions. Unless a person is expressly identified as an actual contributor, a displayed name, image, or profile should not be understood as depicting or identifying a specific candidate, interviewer, employee, or other real individual. These representations are provided for editorial and illustrative purposes only and do not imply endorsement, employment, participation, or affiliation with this guide or any company mentioned in it. Any resemblance to an actual person is coincidental.
Company Notice
This guide is an independent educational resource and is not affiliated with, endorsed by, sponsored by, or approved by the company named in this guide. Company names are used only to identify interview experiences commonly reported by candidates. Interview practices can change without notice, and inclusion of company-specific content does not mean these questions are official, complete, or guaranteed to be asked. To the fullest extent permitted by law, the author, contributors, and publisher are not responsible for outcomes related to use of this material.
Questions or comments?
Contact us for general questions, or share feedback, technical corrections, and comments with the community.
31. What is the difference between TreeMap and HashMap?Language SpecificMedium
i Question Details
Compare TreeMap and HashMap in ordering, complexity, and common use cases.
Short Interview Answer (30-60 seconds)
I use HashMap when I need fast key based access and do not need sorted keys. Its get, put, and remove operations are usually constant time. I use TreeMap when I need keys to remain sorted or need range and nearest key operations. Its main operations take logarithmic time. HashMap allows one null key. TreeMap normally requires non null comparable keys. Neither map is thread safe.
The practical choice depends on whether the keys must remain sorted. HashMap is usually better when a program only needs to store and find a value by its key. TreeMap is better when a program must read keys in order or find the closest key. For example, both maps can store employee names by employee number. HashMap usually finds a name faster. TreeMap also keeps employee numbers sorted, but each lookup requires more work. The correct choice therefore depends on the operations the application needs most often.
Useful Questions to Ask the Interviewer
Must the keys always be returned in sorted order?
Does the application need nearest key or range searches?
Can a key be null?
Will multiple threads modify the map?
How to Explain It in an Interview
HashMap uses each key's hashCode result to choose a bucket in an internal table. It then uses equals to identify the matching key. get, put, and remove are O(1) on average when hashes are distributed well. Collisions make a bucket contain multiple entries. Modern Java can convert a large collision group into a tree when internal conditions are met. This often improves collision handling, but O(log n) is not an unconditional guarantee for every possible key type and hash pattern.
HashMap does not promise sorted order or insertion order. Its iteration order can change after updates or resizing. It allows one null key and multiple null values.
TreeMap stores entries in a red black tree. It compares keys using natural ordering or a Comparator supplied at construction time. get, put, and remove are O(log n). Iteration follows sorted key order. It also supports firstKey, lastKey, floorKey, ceilingKey, and range views.
TreeMap keys must be mutually comparable under the selected ordering. Natural ordering does not allow a null key. A custom comparator may allow null when it explicitly defines null ordering. TreeMap can store null values. If the comparator returns zero for two different keys, TreeMap treats them as the same map key even when equals returns false.
HashMap uses a backing table whose capacity may be larger than its entry count. TreeMap creates a tree node for each entry with several references. Exact memory use depends on the JVM, but TreeMap usually has more per entry pointer overhead. Neither map is thread safe.
Interviewers ask this question to check whether a candidate understands Java map ordering, lookup cost, key comparison, null handling, equality rules, memory tradeoffs, and practical collection selection. It also tests whether the candidate can choose a map based on required behavior instead of using HashMap for every situation.
Common interview mistakes
A common mistake is saying that HashMap returns entries in insertion order. It provides no such guarantee. Another mistake is saying that every HashMap operation is always O(1). That is only the expected average behavior with suitable keys. Candidates may also assume that a tree shaped collision bucket always gives a strict O(log n) guarantee for every key type. Another mistake is forgetting that TreeMap uses comparison rather than hashCode and equals to identify key positions. A comparator that returns zero for unequal keys causes one value to replace the other. Candidates may also forget that natural ordering rejects null keys and that neither implementation is safe for unsynchronized shared writes.
Interview tip
Start with the decision rule. Use HashMap for fast general lookup and TreeMap for sorted keys, range searches, and nearest key operations. Then compare average complexity, ordering, null keys, comparison rules, iteration cost, memory tradeoffs, and thread safety. Make clear that HashMap iteration order must never be treated as stable.
Interviewer may ask next
What happens if two different keys have the same hash code in a HashMap?
HashMap can still store and find both keys when equals says they are different. It places the colliding entries in the same bucket and checks equals to identify the requested key. A large collision group may become a tree when internal conditions are met. This can improve performance, but a strict O(log n) result should not be promised for every possible key type. This matters because a poor hashCode implementation can cause many collisions and slower access.
When should you choose TreeMap instead of sorting HashMap keys when needed?
Choose TreeMap when sorted access, range queries, or nearest key operations happen frequently while the map continues to change. TreeMap maintains order during every insertion and removal, with O(log n) main operations. Sorting HashMap keys can be better when updates are frequent but sorted output is rare. The tradeoff is that each sorted snapshot requires collecting and sorting the keys, which takes O(n log n) time and usually needs an additional collection.
32. What is the difference between Collection, List, Set, and Map?Language SpecificMedium
i Question Details
Explain the Java Collections Framework hierarchy and the role of each main interface.
Short Interview Answer (30-60 seconds)
Collection is the main interface for groups of individual elements. List and Set extend Collection. A List keeps elements in a sequence and allows duplicates. A Set stores unique elements according to its equality or comparison rules. Map is separate from Collection because it stores key and value pairs. I choose List for sequence, Set for uniqueness, and Map for lookup by key.
Detailed Explanation
These interfaces provide different ways to keep related information. The correct choice depends on how the program will use that information. A program may need to preserve a sequence, allow repeated values, prevent repeated values, or find a value through a separate identifier. Choosing the right interface makes the purpose clear and avoids unnecessary work. Before selecting one, I would confirm whether order matters, whether repeated elements are valid, how items are found, and whether several threads will modify the data.
Useful Questions to Ask the Interviewer
Must elements keep a defined order or support access by position?
Are duplicate elements allowed?
Must values be found through unique keys?
Which implementation guarantees are required for nulls, ordering, and concurrency?
How to Explain It in an Interview
Iterable is above Collection in the hierarchy and provides iteration. Collection represents a group of individual elements. It defines operations such as add, remove, contains, size, and iteration. List and Set extend Collection. Queue also extends Collection, although it is not one of the four interfaces named in this question.
List represents a sequence. It allows duplicate elements. Implementations may also allow null. ArrayList provides fast access by numeric position and is the usual general purpose List. Inserting or removing near the front can require shifting later elements. LinkedList uses a separate node for each element, so it normally uses more memory and has weaker memory locality.
Set represents unique elements. HashSet uses equals and hashCode. TreeSet normally uses natural ordering or a Comparator. LinkedHashSet preserves insertion order. A duplicate add operation returns false and does not add another equal element.
Map is not a subtype of Collection. It stores key and value entries. Each key is unique, but values may repeat. HashMap uses equals and hashCode for keys. TreeMap sorts keys. LinkedHashMap provides a defined encounter order.
Ordering, null support, thread safety, and exact performance depend on the implementation. HashMap and HashSet normally provide constant time basic operations on average when hashing is effective. ArrayList provides constant time position access. TreeMap and TreeSet normally provide logarithmic basic operations.
Mutable hash keys and mutable Set elements are risky. Changing equality data after insertion can make an entry difficult to find or remove. Shared mutable collections also need a suitable concurrent implementation or correct external synchronization.
Practical Insights
For common implementations, ArrayList position access is constant time, while insertion or removal near the front is linear because elements may move. HashMap and HashSet lookup, insertion, and removal are constant time on average, but collisions can increase the cost. TreeMap and TreeSet lookup, insertion, and removal are logarithmic. These are implementation specific costs, not guarantees of the List, Set, Map, or Collection interfaces themselves.
Why Interviewers Ask This
Interviewers ask this question to check whether a candidate understands the Java Collections Framework hierarchy and can select an interface that matches a real requirement. It tests knowledge of ordering, duplicates, uniqueness, key lookup, equality rules, implementation guarantees, performance, memory use, and production safety.
Common interview mistakes
Common mistakes include saying that Map extends Collection, assuming every Collection preserves insertion order, and assuming every Set is sorted. Another mistake is saying that Set uniqueness always uses object identity. HashSet normally uses equals and hashCode, while TreeSet normally uses comparison. Candidates may also confuse unique keys with unique values in a Map. Keys must be unique, but values may repeat. Null support, ordering, thread safety, and performance must not be generalized across all implementations.
Interview tip
Start with the hierarchy. State that List and Set extend Collection, while Map is separate. Then give one decision rule for each interface: List for sequence and duplicates, Set for uniqueness, and Map for lookup by key. Finish by saying that ordering, null support, performance, memory use, and thread safety depend on the implementation.
Interviewer may ask next
What can happen if an object stored in a HashSet is changed after insertion?
The object can become difficult to find or remove when the change affects fields used by equals or hashCode. HashSet places the object according to its hash value at insertion time. A later hash value may direct lookup to a different location. This matters because contains and remove may fail even though the object is still stored. Equality data should therefore remain stable while the object is in a hash based Set.
How would you choose between ArrayList, HashSet, and HashMap in production code?
Choose ArrayList when sequence, duplicates, and position access matter. Choose HashSet when uniqueness or membership testing is the main requirement. Choose HashMap when values must be found through keys. The tradeoff is that each implementation has a different access model and memory layout. The decision must also consider iteration order, null handling, equality rules, expected size, concurrency, and whether stable performance guarantees are required.
33. What is the difference between Comparator and Comparable?Language SpecificMedium
i Question Details
Explain how Comparator and Comparable are used for ordering objects and when each is appropriate.
Short Interview Answer (30-60 seconds)
Comparable defines one natural order inside the class through compareTo. Comparator defines an external order through compare, so I can create several sorting rules without changing the class. I use Comparable when one clear default order belongs to the type. I use Comparator for alternate orders, classes I cannot modify, or ordering rules that depend on the current use case.
The practical choice is simple. Use Comparable when a class has one clear default order that should be understood wherever the type is used. Use Comparator when the order belongs to a particular task, when several valid orders exist, or when the class cannot be changed. For example, employees may normally appear by identifier, while one screen sorts them by name and another by salary. Comparable lets the employee type own the identifier order. Separate Comparator objects let each screen choose another order without changing the employee type.
Useful Questions to Ask the Interviewer
Does the class have one clear default order?
Do we need several different ordering rules?
Can we modify the class being ordered?
How should null values and equal comparison results be handled?
How to Explain It in an Interview
Comparable is implemented by the class whose objects need a natural order. The class implements Comparable<T> and provides compareTo(T other). When List.sort receives null as its Comparator, or when Collections.sort is called without a Comparator, Java uses this natural order.
Comparator is a separate comparison rule. It implements Comparator<T> and provides compare(T first, T second). It can also be created with a lambda, a method reference, or helpers such as Comparator.comparing, comparingInt, reversed, and thenComparing. A type can have many Comparators, so callers can sort the same objects in different ways.
Both comparison methods return a negative number when the first object comes before the second, zero when both have the same ordering position, and a positive number when the first comes after the second. The exact numeric value does not matter. Only its sign matters.
The comparison must be consistent and transitive. If a comparison says a is before b and b is before c, it must also say a is before c. Avoid subtracting numbers because subtraction can overflow. Use Integer.compare, Long.compare, or Comparator helper methods.
Comparable normally does not accept null. Calling compareTo with null should throw NullPointerException. A Comparator may support null when that policy is defined explicitly with Comparator.nullsFirst or Comparator.nullsLast.
TreeSet and TreeMap use comparison results to decide whether elements or keys occupy the same ordering position. If comparison returns zero for two objects that are not equal according to equals, the collections can treat them as the same set element or map key. The behavior is defined, but it does not follow the normal Set or Map equality contract. Production code should make this choice intentional, document it, and test duplicate fields, nulls, tie breakers, and boundary values.
Interviewers ask this question to check whether a candidate understands how Java defines object ordering. They want to see whether the candidate can choose between a natural order owned by a class and an external order supplied for a particular use case. The question also tests comparison contracts, null handling, sorting behavior, and the effect of comparison results on TreeSet and TreeMap.
Common interview mistakes
A common mistake is saying that Comparable and Comparator are interchangeable. Comparable belongs to the type and defines its natural order. Comparator is a separate rule supplied by the caller. Another mistake is putting several unrelated orders into compareTo instead of choosing one clear natural order. Developers may also subtract integers, which can overflow, forget a tie breaker, violate transitivity, or assume null is handled automatically. Another important mistake is returning zero for unequal objects without understanding how TreeSet and TreeMap will treat those objects.
Interview tip
Start with ownership and purpose. Say that Comparable belongs to the class and defines one natural order, while Comparator stays outside the class and supports alternate orders. Then name compareTo and compare, explain that only the sign of the result matters, and mention null handling, comparison consistency, and the effect of returning zero in TreeSet and TreeMap.
Interviewer may ask next
What happens if compare or compareTo returns zero for two objects that are not equal according to equals?
The ordering treats the objects as occupying the same position even though equals treats them as different. A List can still contain and sort both objects. TreeSet and TreeMap use comparison results to identify elements and keys, so TreeSet may reject the second object and TreeMap may replace the value associated with the first key. This behavior is defined, but the collection no longer follows the normal Set or Map equality contract. It matters because lookup, insertion, and duplicate handling may surprise callers.
When should you prefer a Comparator even when you can modify the class?
Prefer a Comparator when the ordering belongs to a use case rather than to the type itself, or when several valid orders exist. An Employee may need ordering by name, salary, department, or hire date. Defining all of those choices through Comparable would not create one clear natural order. Separate Comparators keep the type focused and allow composition with thenComparing. The tradeoff is that callers must select and pass the correct Comparator, and the application should reuse well named Comparator instances when the rules are shared.
34. How does HashMap work internally?Language SpecificMedium
i Question Details
Explain hashing, buckets, collisions, resizing, and retrieval in HashMap.
Short Interview Answer (30-60 seconds)
HashMap stores key and value entries in an internal array of buckets. It calculates a spread hash from the key, uses that hash to choose a bucket, and uses equals to find the correct key inside that bucket. Collisions share a bucket through a linked list or, in some cases, a balanced tree. When the map passes its size threshold, it normally doubles the table and redistributes entries. Get and put are usually O(1), but poor hashing, mutable keys, or heavy collisions can make them slower.
Detailed Explanation
A HashMap stores information by a key, such as a user identifier or product code. Java turns the key into a number and uses that number to choose one storage position. Different keys can choose the same position, so Java keeps those entries together and compares their keys when searching. As the map becomes crowded, Java creates a larger set of positions and moves the entries. This keeps normal searches fast. The exact layout is an implementation detail, while the Map interface defines the behavior callers can rely on.
Useful Questions to Ask the Interviewer
Should I explain current JDK implementation details as well as the Map contract?
Should I include tree conversion and resize thresholds?
Should I discuss mutable keys and thread safety?
How to Explain It in an Interview
In current JDK implementations, HashMap uses an internal table whose positions are called buckets. For a non null key, it calls hashCode and spreads the bits using the hash value combined with its unsigned right shift by 16 bits. Because the table length is a power of two, the bucket index is calculated from the table length and the spread hash. A null key is allowed, uses hash value zero, and goes to bucket zero.
During put, HashMap checks the chosen bucket. If it is empty, it adds a new node. Otherwise, it compares the stored hash and then checks whether the keys are identical or equal according to equals. An equal key causes the value to be replaced. A different key creates a collision and is added to the same bucket.
A collision bucket normally uses a linked list. In current JDK implementations, a bucket may become a red black tree when it reaches at least eight nodes and the table capacity is at least 64. With a smaller table, HashMap prefers resizing. A tree may return to a list when it becomes small.
HashMap normally uses a load factor of 0.75. When size passes the threshold, it creates a table with twice the capacity. During redistribution, an entry either stays at its old index or moves by the old capacity, based on one hash bit.
During get, HashMap repeats the hash and bucket calculation, then searches the first node, linked list, or tree. HashMap permits one null key and multiple null values. It does not guarantee iteration order and is not thread safe.
Why Interviewers Ask This
Interviewers ask this question to check whether a candidate understands hashing, bucket selection, equality checks, collision handling, resizing, and lookup cost in a core Java collection. It also tests practical judgment about key design, initial capacity, thread safety, iteration order, and production performance.
Common interview mistakes
A common mistake is saying that hashCode identifies the final entry. It only helps select a bucket, while equals confirms the matching key. Another mistake is assuming every collision replaces the existing value. Replacement happens only when the keys are equal. Developers also misuse mutable keys. If a field used by equals or hashCode changes after insertion, get and remove may search a different bucket and fail to find the entry. Other mistakes include expecting a stable iteration order, assuming HashMap is thread safe, believing every collision bucket becomes a tree, ignoring resize cost, and implementing equals without a consistent hashCode.
Interview tip
Explain one operation from start to finish. Calculate and spread the hash, choose the bucket, compare keys with equals, handle collisions, and resize after the threshold is crossed. Then mention average O(1) performance, mutable key risk, iteration order, and lack of thread safety.
Interviewer may ask next
What happens if a key changes after it has been inserted into a HashMap?
Retrieval can fail when the changed fields affect equals or hashCode. The entry remains in the bucket selected from the old hash, but get and remove calculate a new hash from the modified key and may search a different bucket. This matters because the entry can remain stored while normal lookup cannot find it. Keys should therefore be immutable, or every field used by equals and hashCode should remain unchanged while the key is in the map.
How do initial capacity and load factor affect HashMap performance and memory use?
A larger initial capacity can reduce resizing when many entries are expected, while a smaller capacity uses less table memory at the beginning. The load factor controls how full the table may become before resizing, and the usual value is 0.75. A lower value can reduce collisions but uses more bucket space. A higher value saves bucket space but can increase collisions and search work. In production, the main tradeoff is extra memory against resize cost and lookup performance.
35. How does ConcurrentHashMap achieve scalability?Language SpecificHard
i Question Details
Explain how ConcurrentHashMap supports concurrent access and why it scales better than synchronized map implementations.
Short Interview Answer (30-60 seconds)
ConcurrentHashMap scales by avoiding one map wide lock. Reads normally proceed without locking. Updates use atomic operations when possible and coordinate only around the affected bucket when required. Threads can also share resize work. This allows operations on unrelated keys to make progress at the same time, so it usually scales much better than Collections.synchronizedMap or Hashtable under concurrent access.
Detailed Explanation
A ConcurrentHashMap is useful when many tasks share one table of names and values. A simple protected table can make every task wait at the same entrance, even when the tasks use different names. ConcurrentHashMap reduces that waiting by letting unrelated work continue together. It keeps each completed change safe and visible while avoiding one rule that stops the whole table. The interviewer is checking whether you understand where waiting can still happen, which actions are atomic, and when a result is only an changing view.
Useful Questions to Ask the Interviewer
Is the workload mostly reads, writes, or a balanced mix?
Must an update that depends on an existing value be atomic?
Does the application require an exact snapshot while iterating?
How to Explain It in an Interview
ConcurrentHashMap uses a hash table divided into buckets. Keys with different calculated positions usually reach different buckets. The map therefore does not place one exclusive lock around every operation.
Retrieval operations such as get normally do not lock. The implementation reads safely published nodes, and a completed update for a key has a visibility relationship with a later retrieval that observes that value.
For an empty bucket, the current OpenJDK implementation can install a node with an atomic compare and set operation. If a bucket already contains nodes, an update may synchronize on the first node of that bucket while it changes the bucket. This coordination is local, so an update in another bucket can often continue. These internal details describe modern OpenJDK implementations and are not a promise that every Java implementation must use the same mechanism.
Heavy hash collisions can place several keys in one bucket. After the required thresholds and table size are reached, the implementation can convert that bucket from linked nodes to tree nodes. This improves the worst case search behavior inside that bucket. Good and stable hashCode and equals implementations are still important.
When the table grows, threads that encounter the resize can help transfer buckets to the new table. This distributes the work instead of making one thread perform the complete transfer alone.
ConcurrentHashMap does not allow null keys or null values. Its iterators are weakly consistent. They do not throw ConcurrentModificationException because of concurrent changes, but they do not provide one fixed snapshot. Aggregate methods such as size can describe a changing map and should not be used for exact control decisions while updates continue.
Use putIfAbsent, replace, compute, computeIfAbsent, or merge when a change depends on the current mapping. A separate get followed by put is not one atomic operation. Mapping functions should be short and should not perform slow input, network, or database work because updates involving the affected area may wait.
Why Interviewers Ask This
Interviewers ask this question to test whether a candidate understands how Java allows many threads to share a map safely without forcing every operation through one map wide lock. It also evaluates knowledge of concurrent reads, atomic updates, contention, resizing, collision handling, iteration behavior, memory visibility, performance limits, and correct production use.
Common interview mistakes
A common mistake is saying that ConcurrentHashMap has no locks. Modern OpenJDK implementations combine lock free retrievals, atomic operations, and small synchronized regions for some updates. Another mistake is describing the old Java 7 segment design as the current implementation. Java 8 and later use a table of nodes rather than fixed segments for ordinary locking. Developers also incorrectly treat get followed by put as atomic, expect iteration to produce a fixed snapshot, use size for an exact concurrent decision, or place slow work inside compute methods. Poor or mutable key state can break lookup behavior. The map also does not make mutable stored values thread safe and does not provide coordination across JVM processes.
Interview tip
Begin with the contrast that a synchronized map uses one map wide lock while ConcurrentHashMap reduces shared contention. Then explain lock free retrievals, atomic insertion, local bucket coordination, cooperative resizing, collision trees, atomic update methods, weakly consistent iteration, and the limits of its thread safety. Clearly separate public API guarantees from current OpenJDK implementation details.
Interviewer may ask next
Does ConcurrentHashMap make a mutable object stored as a value thread safe?
No. ConcurrentHashMap makes access to its mappings thread safe, but it does not protect the internal state of a mutable value. After a thread obtains a mutable list or other object from the map, changes to that object follow the thread safety rules of the object itself. Use immutable values, a suitable concurrent value type, or additional coordination. This matters because safe publication through the map does not make every later mutation of the published object safe.
When can a synchronized map be a better choice than ConcurrentHashMap?
A synchronized map can be a reasonable choice when concurrency is low, the map is small, or several operations must be protected by the same external lock as one larger action. Its advantage is simpler map wide coordination. Its main cost is contention because unrelated operations use the same lock, and iteration also requires correct external synchronization. ConcurrentHashMap usually provides better throughput for independent key operations, but it does not provide one automatic transaction across several keys.
36. What is autoboxing and unboxing?Language SpecificEasy
i Question Details
Explain autoboxing and unboxing and mention performance implications.
Short Interview Answer (30-60 seconds)
Autoboxing is Java automatically converting a primitive value into its matching wrapper object, such as int to Integer. Unboxing is Java converting the wrapper back to its primitive value. This makes code easier to write, especially with generic collections. However, boxing can create or reuse wrapper objects, and unboxing a null reference throws NullPointerException. I prefer primitives when null is not needed and object behavior is not required.
Java has simple values for numbers, letters, and true or false choices. It also has object forms that hold the same kinds of values. Java can automatically change a simple value into its matching object form. It can also change that object form back into a simple value. This saves the programmer from writing each conversion by hand. However, the object form may use more memory, and changing an empty object reference back into a simple value causes an error while the program is running.
Useful Questions to Ask the Interviewer
Should I explain how this works with generic collections such as ArrayList?
Should I include null handling, object reuse, and performance implications?
How to Explain It in an Interview
Autoboxing is a Java language conversion from a primitive value to its corresponding wrapper type. For example, assigning an int to an Integer causes boxing. Unboxing is the reverse conversion from a wrapper reference to its primitive value.
Java provides these conversions because generics and generic collections use reference types. They cannot use primitive types directly. For example, ArrayList<Integer> stores Integer references. Adding an int performs boxing. Reading an Integer into an int performs unboxing.
For an int value, boxing behaves like calling Integer.valueOf. Unboxing an Integer behaves like calling intValue. Boxing may reuse an existing cached wrapper for some values. Otherwise, a wrapper object may be created, although JVM optimization can sometimes remove an allocation that is not observable. Code must not depend on wrapper identity. When both operands are Integer references, two equality signs compare references. Use equals to compare their numeric values.
Unboxing requires a real wrapper object. If the reference is null, Java throws NullPointerException. This can happen during assignment, arithmetic, comparison, method invocation, or a conditional expression when Java needs a primitive value.
Boxing and unboxing are constant time conversions, but repeated boxing can increase object allocation, heap use, garbage collection work, and CPU work. The exact cost depends on caching, escape analysis, JIT compilation, and the surrounding code. Use primitives for calculations, counters, large numeric data, and frequently executed loops when null is not meaningful. Use wrappers when a generic API requires an object or when null intentionally represents a missing value.
Interviewers ask this question to check whether a candidate understands the difference between Java primitive values and wrapper objects. They also evaluate knowledge of automatic conversion rules, null failures, object identity, possible allocation, memory use, and the performance impact of repeated conversions in collections and frequently executed code.
Common interview mistakes
A common mistake is assuming that wrapper objects behave exactly like primitives. When both values are wrapper references, comparing them with two equality signs checks whether the references point to the same object. It does not reliably compare their numeric values. Use equals for wrapper value comparison. Another mistake is unboxing without checking for null, which can cause NullPointerException. Developers may also overlook repeated boxing in loops or large collections. This can add allocation, heap use, garbage collection work, and CPU cost. Code should never rely on wrapper caching or assume that every boxing conversion creates a new object.
Interview tip
Define both conversions with one int and Integer example. Then explain why generic collections need wrapper types. Finish with the main practical risks: unboxing null throws NullPointerException, wrapper identity is not a safe way to compare values, and repeated boxing can add memory and runtime cost.
Interviewer may ask next
What happens when Java unboxes a null Integer?
Java throws NullPointerException because unboxing requires Java to obtain an int value from an actual Integer object. A null reference points to no object, so the conversion cannot complete. This matters because unboxing may happen implicitly during assignment, arithmetic, comparison, method invocation, or conditional expression evaluation. A null check, an explicit default value, or an API that avoids nullable wrappers can prevent the failure.
When should you prefer int over Integer in production code?
Prefer int when the value cannot be null and the code performs calculations, counting, large scale storage, or frequently repeated operations. A primitive stores the value directly and avoids the wrapper reference and possible boxing allocation. Use Integer when a generic API requires a reference type or when null has a deliberate business meaning. The tradeoff is object compatibility and nullable state versus possible memory cost, conversion work, and null related failures.
37. What is an enum in Java?Language SpecificEasy
i Question Details
Explain Java enums and where they are useful compared with constants.
Short Interview Answer (30-60 seconds)
An enum in Java is a special type used to define a fixed set of named values, such as NEW, PAID, SHIPPED, and CANCELLED. Each constant is one instance of the enum type, so Java checks the type at compile time. Enums are safer than string or integer constants because they limit the allowed values. They can also contain fields, methods, constructors, and interface implementations. I use an enum when the choices are fixed in the code.
An enum is useful when a value must come from a small list that the program already knows. For example, an order may be NEW, PAID, SHIPPED, or CANCELLED. Using one clear kind of value prevents unrelated words or numbers from being used by mistake. It also keeps the allowed choices together, which makes the program easier to read and change. The main decision is whether the choices are truly fixed in the program or must be added later without changing and releasing the code. Before giving the full answer, I would ask:
Useful Questions to Ask the Interviewer
Is the set of values fixed in the code, or can users add new values later?
Does each value need extra information or its own behavior?
Will the values be stored in a database or received from an external interface?
How to Explain It in an Interview
In Java, an enum is a special class used to declare a fixed set of named values. Each declared constant is an implicitly public static final instance of that enum type. The instances are created when the enum class is initialized. Application code cannot create more instances because an enum constructor can be called only as part of declaring its constants.
This is safer than using strings or integers. A method that accepts OrderStatus can receive only an OrderStatus value or null. It cannot receive an unrelated string such as "finished" or an integer such as 3.
An enum may contain fields, constructors, methods, and implemented interfaces. Its constructor cannot be public or protected. Each constant can pass arguments to the constructor, so a constant can carry stable data such as a display label. An enum implicitly extends java.lang.Enum and therefore cannot extend another class.
The compiler provides values(), which returns the constants in declaration order, and valueOf(String), which requires an exact, case sensitive name. valueOf throws IllegalArgumentException for an unknown name and NullPointerException for null. Each call to values() returns a new array, so repeated calls allocate arrays.
Use enums for fixed states, modes, priorities, and supported options. Do not use one when administrators or external systems must add values without a code release. In production, do not persist ordinal(), because reordering constants changes those numbers. Store a stable name or explicit code instead. When parsing external data, handle unknown values deliberately. Enum constants are normally created once per class loader, so using them is cheap, but extra fields still consume memory and values() can create avoidable short lived arrays.
Code
publicclassMain {
enumOrderStatus {
NEW("New order"),
PAID("Payment received"),
SHIPPED("Order shipped"),
CANCELLED("Order cancelled");
privatefinal String displayLabel;
privateOrderStatus(String displayLabel) {
this.displayLabel = displayLabel;
}
public String getDisplayLabel() {
return displayLabel;
}
}
static String statusMessage(OrderStatus status) {
returnswitch (status) {
case NEW -> "The order is waiting for payment";
case PAID -> "The order is ready to ship";
case SHIPPED -> "The order is on the way";
case CANCELLED -> "The order will not be processed";
};
}
staticvoidprintStatus(OrderStatus status) {
System.out.println(status.name());
System.out.println(status.getDisplayLabel());
System.out.println(statusMessage(status));
}
publicstaticvoidmain(String[] args) {
printStatus(OrderStatus.SHIPPED);
}
}
Why Interviewers Ask This
Interviewers ask this question to check whether the candidate understands how Java represents a fixed set of named values. They also want to see whether the candidate knows that enum constants are objects with type safety, controlled construction, fields, and methods, rather than simple string or integer constants. A strong answer also shows judgment about external data, persistent storage, and when an enum is not suitable.
Common interview mistakes
A common mistake is treating an enum as only a group of integer constants. Enum constants are objects of one specific enum type. Another mistake is assuming valueOf ignores letter case or returns null for an unknown name. It requires an exact name and throws an exception when the input is invalid. Developers also sometimes persist ordinal values, which is unsafe because reordering constants changes those numbers. Other mistakes include passing null into a switch, calling values() repeatedly in a frequently executed loop, and using an enum when values must be added without changing and releasing the application.
Interview tip
Start by saying that an enum represents a fixed set of named, type safe values. Give one small example, such as order status. Explain that each constant is an object and that an enum can contain fields and methods. Then mention one production rule, such as storing stable names or explicit codes instead of ordinal values. Finish by explaining that an enum is not suitable when values must change without a code release.
Interviewer may ask next
What happens when valueOf receives an unknown name or null, and does values() reuse the same array?
valueOf fails instead of returning a default value. It requires the exact, case sensitive constant name. An unknown name causes IllegalArgumentException, while null causes NullPointerException. This matters when reading user input, database values, or external messages because the input must be validated or translated before calling valueOf. Also, each call to values() returns a new array containing the constants in declaration order. Repeated calls therefore create new arrays, so frequently executed code can cache the result when exposing a private, safely used copy is appropriate.
When should you use an enum instead of a class or database table?
Use an enum when the allowed values are small, fixed by the application, and changed only through a code release. It provides compile time type checking and can keep stable data or behavior with each constant. Use a class, configuration source, or database table when values must be created, removed, or edited while the application is running. The main tradeoff is that an enum is simple and safe, but adding a constant normally requires changing, testing, and redeploying the code.
38. What are checked and unchecked exceptions?Language SpecificEasy
i Question Details
Explain checked versus unchecked exceptions and when each type is used.
Short Interview Answer (30-60 seconds)
Checked exceptions must be caught or declared with throws because Java enforces that rule during compilation. IOException and SQLException are common examples. Unchecked exceptions are RuntimeException subclasses, such as IllegalArgumentException and NullPointerException. Java does not require callers to catch or declare them. Checked exceptions are useful when a method contract expects the caller to consider a failure, while unchecked exceptions usually report invalid use, invalid state, or a programming defect.
Detailed Explanation
The practical difference is whether Java requires code to acknowledge a possible failure before it can compile. For one group, a method must handle the failure or state that it may pass the failure to its caller. For the other group, Java allows the failure to travel through method calls without any required declaration. This affects method contracts and caller responsibilities. It does not tell us when the failure occurs, whether recovery is always possible, or whether one group is more serious than the other.
Useful Questions to Ask the Interviewer
Is the exception part of a public method contract?
Can the caller take a useful action after the failure?
Should the failure be handled locally or by a central exception handler?
How to Explain It in an Interview
A checked exception is a Throwable subtype that is not a subtype of RuntimeException or Error. Most checked exceptions used in application code extend Exception. Java performs compile time checking for them. If a method can throw a checked exception, it must catch the exception or declare a compatible type in its throws clause. IOException and SQLException are common examples.
An unchecked exception is a RuntimeException subtype or an Error subtype. Java does not require it to appear in a throws clause or to be caught. IllegalArgumentException, IllegalStateException, and NullPointerException are unchecked exceptions. Error types are also unchecked, but they usually represent serious runtime conditions and are not normally handled by application code.
The compiler rule is the exact language difference. Recovery is a design consideration, not a strict classification rule. A checked exception is often suitable when callers are expected to consider a failure described by the method contract. An unchecked exception is often suitable when a caller violates a method requirement or when the program reaches an invalid state.
Both types are created and thrown at runtime. The checked category does not make an exception slower or larger. Creating an exception object allocates memory, and collecting its stack trace can use time and memory for either category. Exceptions should therefore represent exceptional failures rather than normal control flow. Production code should catch only exceptions it can handle correctly, preserve useful causes when wrapping exceptions, and avoid broad catch blocks that hide defects.
Why Interviewers Ask This
Interviewers ask this question to check whether a candidate understands the Java exception hierarchy, compiler enforcement, exception propagation, and method contract design. They also want to see whether the candidate can choose an appropriate exception type and avoid handling failures in ways that hide defects or prevent useful recovery.
Common interview mistakes
A common mistake is saying that checked exceptions occur during compilation while unchecked exceptions occur during execution. Both are thrown during execution. Compilation only enforces handling or declaration rules for checked exceptions. Another mistake is claiming that every checked exception is recoverable or every unchecked exception is unrecoverable. Classification does not guarantee recovery. Catching Exception or Throwable without a specific handling plan can hide defects and serious runtime failures. Swallowing InterruptedException is also dangerous because it can prevent cancellation and shutdown logic from working. Another mistake is wrapping a checked exception in an unchecked exception without preserving the original cause.
Interview tip
Begin with the compiler rule. Then explain the hierarchy and give one example of each type. Finish by saying that recovery is a design consideration rather than the formal definition, and mention that Error types are unchecked but are not normally caught by application code.
Interviewer may ask next
Can an unchecked exception be declared in a throws clause, and does that change its behavior?
Yes. A method may declare a RuntimeException subtype in its throws clause, but it remains unchecked. Callers are still not required to catch or declare it. The declaration can document the method contract, but it does not change compiler enforcement or runtime propagation. This matters because a throws clause alone does not determine whether an exception is checked.
When should a library use a checked exception instead of wrapping it in an unchecked exception?
A library should consider a checked exception when callers are expected to recognize the failure as part of the method contract and can take a meaningful action. Wrapping it in an unchecked exception can simplify calling code when most callers cannot recover, but it removes compiler enforced acknowledgment. When wrapping is appropriate, the original exception should be preserved as the cause so production logs and debugging retain the failure details.
39. What is the difference between break and continue?Language SpecificEasy
i Question Details
Explain how break and continue change loop control flow.
Short Interview Answer (30-60 seconds)
The main difference is that break ends the loop, while continue skips the rest of the current repetition and lets the loop move toward the next repetition. I use break when no more items need to be checked. I use continue when the current item should be ignored but later items still need processing.
Use break when the entire loop should stop. Use continue when only the current item should be skipped and later items should still be checked. Both statements change the normal order of work inside a loop. For example, a search can stop after finding its result, while a data check can ignore one invalid value and keep reading the remaining values. They are useful when the reason for changing the flow is simple and clear. Too many such changes can make the loop difficult to understand and maintain.
Useful Questions to Ask the Interviewer
Should I demonstrate the behavior with a for loop?
Should I also explain nested loops and labels?
Do you want me to show the exact program output?
How to Explain It in an Interview
In a Java loop, break immediately ends the nearest enclosing loop unless it names an enclosing label. Execution then continues with the first statement after the loop.
Continue does not end the loop. It skips the remaining statements in the current repetition. In a basic for loop, control moves to the update expression, such as increasing the counter. Java then checks the loop condition before another repetition begins. In a while loop, control moves directly to the condition check. In a do while loop, control moves to the condition check at the bottom.
Consider a for loop that visits the numbers one through six. When the number is two, continue skips the print statement. When the number is five, break ends the loop. The program therefore prints one, three, and four. It does not print two because that repetition is skipped. It does not print five or six because the loop ends when five is reached.
Use break when a result has been found, a stopping value has appeared, or further work is unnecessary. Use continue when one item is invalid or irrelevant but later items still need processing.
An unlabeled break or continue affects the nearest valid enclosing statement. A labeled break can transfer control out of an enclosing labeled statement. A labeled continue can target an enclosing labeled loop and start its next repetition. The target of a labeled continue must be a loop.
Neither statement creates a collection or copies loop data. Its extra memory use does not grow with the number of repetitions. Its performance benefit comes from avoiding work. In production code, use these statements only when they make the loop easier to read.
Code
publicclassMain {
publicstaticvoidmain(String[] args) {
for (intnumber=1; number <= 6; number++) {
if (number == 2) {
continue;
}
if (number == 5) {
break;
}
System.out.println(number);
}
}
}
Why Interviewers Ask This
Interviewers ask this question to check whether a candidate understands how Java changes normal loop control flow. They want to know whether the candidate can correctly choose between ending a loop and skipping one repetition. The question also tests understanding of nested loops, labeled statements, loop updates, and bugs caused by skipped state changes.
Common interview mistakes
A common mistake is thinking that continue ends the loop. It only skips the remaining work in the current repetition. Another mistake is expecting an unlabeled break to exit every nested loop. It exits only the nearest enclosing loop or switch statement. Developers may also place an important state change after continue. In a while loop, skipping that state change can cause the condition to remain true forever. Another mistake is using many break and continue statements in deeply nested code, which can make execution difficult to follow.
Interview tip
Begin with the direct difference: break ends the loop, while continue skips one repetition. Then explain exactly where control moves after each statement. Use one small example with clear output, and mention nested loops or labels only after the basic behavior is clear.
Interviewer may ask next
What happens when break or continue is used inside nested loops?
An unlabeled break exits only the nearest enclosing loop, while an unlabeled continue starts the next repetition of only the nearest enclosing loop. A labeled break can exit an enclosing labeled statement. A labeled continue can start the next repetition of an enclosing labeled loop, but its target must be a loop. This matters because assuming that an ordinary break or continue affects every nested loop can produce incorrect output.
Can break or continue improve performance in production code?
Yes, either statement can reduce work when it prevents unnecessary processing. Break can stop a search after the required result is found. Continue can skip costly work for an invalid or irrelevant item. Neither statement creates loop data or adds memory use that grows with the number of repetitions. The main tradeoff is readability, because frequent control transfers can make a complex loop harder to understand, test, and maintain.
40. What are command-line arguments in Java?Language SpecificEasy
i Question Details
Explain how command-line arguments are passed into a Java program and how you can use them.
Short Interview Answer (30-60 seconds)
Command line arguments are text values supplied when a Java program starts. Java passes them to the String array parameter of the main method in the same order. I check the array length before reading an index, and I convert a value when I need a number or another type because every argument is received as a String.
Command line arguments let a person provide values when starting a program. For example, the person can provide a name, file path, mode, or number without changing the program. The program receives the values in the order entered. This is useful for small tools, scheduled jobs, and programs that need different settings for each run. The program should check that required values are present and valid before using them. Missing values, invalid numbers, or unexpected input should produce a clear message instead of an unclear failure.
Useful Questions to Ask the Interviewer
How many arguments should the program accept?
Which arguments are required or optional?
What should happen when an argument is missing or invalid?
How to Explain It in an Interview
A Java application normally receives command line arguments through the parameter of its main method:
public static void main(String[] args)
Each array element contains one argument as a String. The first argument is args[0], the second is args[1], and args.length gives the number of arguments.
For example, running java Main Alice 3 passes two values. args[0] contains Alice, and args[1] contains 3. The second value is still text. The program must call Integer.parseInt if it needs an int. Invalid numeric text causes NumberFormatException, so production code should handle that case and return a useful error message.
When the standard Java launcher invokes main with no arguments, it supplies an empty array. Therefore, args.length is zero. Reading args[0] without checking the length causes ArrayIndexOutOfBoundsException.
The operating system shell separates the entered command into arguments before Java receives them. Quotes are commonly needed when one argument contains spaces. For example, java Main "Alice Smith" normally passes Alice Smith as one argument. Exact quoting and escaping rules depend on the shell.
Direct array access is suitable for a small and fixed argument format. A parsing library is often clearer when an application needs named options, defaults, optional values, repeated values, validation, and generated help text.
Command line arguments should not normally carry passwords or secret tokens. They may be exposed through shell history, logs, diagnostic output, or process inspection tools.
Reading one array element takes constant time. Checking every argument takes time proportional to the number of arguments. Parsing a value takes time proportional to the length of that value. The args array and its String values use memory related to the number of arguments and their total text length, although exact allocation details depend on the launcher and JVM implementation.
Code
publicclassMain {
publicstaticvoidmain(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java Main <name> <repeatCount>");
return;
}
Stringname= args[0];
int repeatCount;
try {
repeatCount = Integer.parseInt(args[1]);
} catch (NumberFormatException exception) {
System.out.println("repeatCount must be a whole number");
return;
}
if (repeatCount < 0) {
System.out.println("repeatCount must not be negative");
return;
}
for (inti=0; i < repeatCount; i++) {
System.out.println("Hello, " + name);
}
}
}
Why Interviewers Ask This
Interviewers ask this question to check whether the candidate understands how a Java program receives startup values, how the main method exposes those values, and how to validate and convert them safely. It also tests awareness of array access, text parsing, shell behavior, and practical production risks.
Common interview mistakes
Common mistakes include reading args[0] before checking args.length, assuming numeric input is already a number, ignoring NumberFormatException, forgetting that array indexes begin at zero, and misunderstanding shell quoting. Other mistakes include accepting invalid values without validation, assuming all shells use identical escaping rules, and placing passwords or secret tokens in command line arguments.
Interview tip
Begin by saying that Java receives startup arguments as an ordered String array in main. Then explain length checks, zero based indexing, type conversion, invalid input handling, shell quoting, and the risk of passing secrets.
Interviewer may ask next
What happens when no command line arguments are supplied?
The standard Java launcher passes an empty String array to main, so args.length is zero. Accessing args[0] causes ArrayIndexOutOfBoundsException. This matters because the program should check the length and show a clear usage message before reading any index.
When should a production application use a command line parsing library instead of reading args directly?
A parsing library is usually better when the application needs named options, optional values, defaults, repeated values, validation rules, or help text. Reading args directly has little setup and works well for a small fixed format, but manual index handling becomes harder to understand and maintain as the interface grows.
More questions load as you scroll
Disclaimer: This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.