Every fresher-level question on collections, multithreading basics, Java 8 streams and coding-round programs, in one-line form with links.
Published September 25, 2026
This page condenses every question from the Fresher to 2 Years course in these areas into a single line: the question, linked to its full answer, and the one-sentence answer you should be able to give instantly. Read down the list and answer each question aloud before reading the line. Wherever you hesitate, follow the link and revise the full answer — interviewers at your level expect these basics to be fluent, and they often open with them before going deeper.
Collections Framework Basics — Interview Questions — open the lesson
Collection, List, Set, Queue, Deque, Map), implementations (ArrayList, HashSet, HashMap, ArrayDeque, …) and algorithms (sorting, searching and shuffling in Collections and Arrays) for storing and processing groups of objects.Collection (the root for groups of elements), with its sub-interfaces: - List: ordered, allows duplicates, index-based. - Set: no duplicates. - Queue/Deque: processing order.Iterator work? — An Iterator walks through a collection one element at a time with hasNext() and next(). It can also safely remove the current element with iterator.remove().Collection types share? — - add, addAll, remove, removeAll, retainAll, clear. - size, isEmpty, contains, containsAll. - iterator, toArray. - Since Java 8: stream(), removeIf() and forEach().ArrayList, HashMap) are not thread-safe. For concurrent use there are three options: - Synchronized wrappers: Collections.synchronizedList(...).collection.stream()), and lambda-friendly default methods: forEach, removeIf, replaceAll, sort on List, and the new Map methods (getOrDefault, putIfAbsent, computeIfAbsent, merge).Iterator and ListIterator? — Iterator works on any Collection, moves forward only, and can remove. ListIterator works only on lists, moves in both directions (hasPrevious()/previous()), knows the current index (nextIndex()), and can also set (replace) and add elements during iteration.Arrays.sort() and Collections.sort() use? — - Arrays.sort() on primitive arrays uses Dual-Pivot Quicksort. It's fast, but not stable (stability doesn't matter for primitives). - On object arrays, Arrays.sort() uses TimSort, a stable hybrid of merge sort and insertion sort that exploits runs already in order. -…LinkedHashSet. It's a HashSet whose entries are also linked together in a doubly linked list, so iteration follows insertion order, with O(1) operations like HashSet.TreeSet (unique elements) or a TreeMap (keys). They keep elements in natural order (Comparable), or in the order of a Comparator you supply, with O(log n) operations and navigation methods such as first(), ceiling() and headSet().ArrayList, LinkedList and HashSet? — - ArrayList: the default list. O(1) index access, and amortised O(1) appends. It's cache-friendly, because the elements sit in one contiguous array. - LinkedList: O(1) inserts and removals at the ends, or at a position you already hold an iterator to.ArrayList and LinkedList? — - ArrayList is backed by an Object[] array. - When the array is full, it grows by about 50% (a new array plus a copy), so appends cost amortised O(1). - get(i) is O(1).HashMap, HashSet & TreeMap Internals — Interview Questions — open the lesson
HashSet guarantee no duplicates? — A HashSet is backed by a HashMap. Each element is stored as a key, with a shared dummy value. Map keys are unique, so add of an equal element just finds the existing key and returns false.hashCode() and equals() work together in hash-based collections? — hashCode() decides which bucket an object belongs in. equals() decides whether two objects in that bucket are the same key.hashCode() when you override equals()? — If two objects are equal but have different hash codes, they land in different buckets. HashMap and HashSet then never compare them with equals, so lookups fail, and "duplicate" entries appear.contains returns false for an equal object, get returns null, and sets hold logical duplicates.TreeSet more appropriate than a HashSet? — When you need the elements sorted, or need range and nearest-value queries. Examples: displaying customer names alphabetically, finding the next free appointment slot after 3 pm, or getting the top-N scores.HashMap work internally? — HashMap is an array of buckets (a Node<K,V>[] table). Here's what put(key, value) does: 1. It computes key.hashCode() and spreads it: h ^ (h >>> 16), which mixes the high bits into the low ones. 2.HashMap tells them apart with equals().HashMap handle collisions, and what changed in Java 8? — Before Java 8, each bucket was a linked list, so a badly colliding bucket made lookups O(n). Since Java 8, when a bucket holds more than 8 entries (and the table has at least 64 buckets), it's converted into a red-black tree, which makes the worst case O(log n).HashMap key? — Yes. Any object can be a key, but it must implement equals() and hashCode() consistently, and it should be immutable.ConcurrentHashMap, and how does it improve multi-threaded performance? — It's a thread-safe Map that allows many threads to read and write at the same time without locking the whole map: - Reads are mostly lock-free, because they rely on volatile reads. - Writes use CAS (compare-and-swap) to put a node into an empty bin, or lock only the…HashMap/HashSet versus TreeMap/TreeSet? — Compared side by side in the full answer (table) — know each row.HashMap, TreeMap, HashSet and TreeSet use internally? — - HashMap: an array of buckets. Each bucket is a linked list, or a red-black tree when it has many collisions. - TreeMap: a red-black tree, a self-balancing binary search tree ordered by key. - HashSet: wraps a HashMap. - TreeSet: wraps a TreeMap.HashMap and TreeMap? — HashMap is unordered, with O(1) average operations, and allows one null key. TreeMap keeps keys sorted, has O(log n) operations, offers navigation (firstKey, floorKey, subMap), and doesn't allow null keys with natural ordering, because compareTo would throw an…TreeMap over a HashMap? — When you need keys in sorted order, or range queries. Examples: showing a price list sorted by product name, finding "the tax slab for this income" with floorEntry(income), or pulling all events between two timestamps with subMap(from, to).TreeMap? — Only if the keys can be compared: either they implement Comparable, or you pass a Comparator to the TreeMap constructor.Threads, Synchronization & volatile Basics — Interview Questions — open the lesson
Thread a task and call start(). There are three ways to supply the task: 1. Implement Runnable (or use a lambda). 2.Thread class and the Runnable interface? — Runnable represents the task (what to run). Thread represents the worker that runs it. Implementing Runnable is preferred: your class stays free to extend another class, the task stays separate from the threading mechanism, and the same task can be run by a thread pool.Thread.State values: - NEW: created, but start() not called yet. - RUNNABLE: running, or ready to run. - BLOCKED: waiting to acquire a monitor lock. - WAITING: waiting indefinitely, for example in wait(), join() or LockSupport.park(). -…start() a second time on the same Thread object throws an IllegalThreadStateException, even after it has finished.synchronized keyword do? — It ensures that only one thread at a time executes a block or method guarded by the same monitor lock. It also guarantees visibility: changes made before releasing the lock are seen by the next thread that acquires it.volatile? — volatile guarantees visibility and ordering for a single variable. A write by one thread is immediately visible to other threads that read it, and the compiler and CPU can't reorder operations around it in ways that break that guarantee.ConcurrentHashMap.merge, ConcurrentLinkedQueue), or guard every access to the shared structure with the same lock.wait() and notify()? — For one thread to wait for a condition that another thread will make true. The classic example is producer-consumer: the consumer waits while the queue is empty, and the producer notifies it after adding an item.Exchanger class? — java.util.concurrent.Exchanger<V> is a synchronisation point where two threads swap objects. Each thread calls exchange(myObject), blocks until its partner arrives, and then receives the partner's object.java.net.ServerSocket for a raw TCP server. - com.sun.net.httpserver.HttpServer for a simple HTTP server. - Java 18's jwebserver tool for serving static files.Java 8 to Java 21 Features — Interview Questions — open the lesson
java.util.function). - The Stream API. - Default and static methods in interfaces. - Optional. - The new Date-Time API (java.time). - Also: CompletableFuture, StringJoiner/String.join, collection…Optional, lambdas and the Stream API introduced? — - Lambdas: to pass behaviour as data concisely, instead of writing anonymous classes. That was essential for parallel and functional-style libraries. - Streams: to express bulk operations on collections declaratively (what, not how), with pipelines that can be lazy and easily…filter and map in streams? — filter(predicate) keeps or drops elements, so the stream may get smaller but the element type stays the same.java.net.http, supporting HTTP/2 and async). - var in lambda parameters. - Running single-file programs directly (java Hello.java). - New String methods: isBlank(), strip(), stripLeading(), stripTrailing(), lines(), repeat(). -…instanceof; - text blocks; - switch expressions. - Also: strong encapsulation of JDK internals, new random-number…getFirst(), getLast(), reversed()). - Record patterns. - Pattern matching for switch. - Generational ZGC.for loop or a stream? — For simple operations on small or medium collections, a plain loop is usually a little faster. There's no pipeline set-up, no lambda calls, and no boxing.filter, map, sorted, distinct, limit) return a new stream and are lazy: nothing runs until a terminal operation is called.String.join() used for? — It concatenates strings with a delimiter, without manual loops or trailing separators.Stream API Coding Questions (Part 1) — Interview Questions — open the lesson
List<Integer> evens = numbers.stream() .filter(n -> n % 2 == 0)Optional<Integer> max = numbers.stream().max(Comparator.naturalOrder());int sum = numbers.stream().mapToInt(Integer::intValue).sum();List<String> upper = names.stream() .map(n -> n.toUpperCase(Locale.ROOT))List<Integer> asc = numbers.stream().sorted().toList();long count = numbers.stream().filter(n -> n > 5).count();List<Integer> unique = numbers.stream().distinct().toList();reduce. — int total = numbers.stream().reduce(0, Integer::sum);Optional<Integer> any = numbers.stream().findAny();List<String> firstNames = names.stream() .map(String::strip)Stream API Coding Questions (Part 2) — Interview Questions — open the lesson
boolean allPositive = numbers.stream().allMatch(n -> n > 0);boolean noNegatives = numbers.stream().noneMatch(n -> n < 0);Optional<Integer> first = numbers.stream().findFirst();List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3, 4, 5), List.of()); List<Integer> flat =…Map<Integer, List<User>> byAge = users.stream() .collect(Collectors.groupingBy(User::age));List<Integer> result = numbers.stream() .filter(n -> n > 5)List<Integer> firstThree = numbers.stream().limit(3).toList();List<Integer> rest = numbers.stream().skip(2).toList();Set to remove duplicates. — Set<Integer> unique = numbers.stream().collect(Collectors.toSet());IntSummaryStatistics stats = numbers.stream().mapToInt(Integer::intValue).summaryStatistics(); stats.getMin();Classic Number & String Programs — Interview Questions — open the lesson
a = a + b; b = a - b; a = a - b;) or XOR (a ^= b; b ^= a; a ^= b;).fib(n) = fib(n-1) + fib(n-2), with fib(0) = 0 and fib(1) = 1. The plain recursive version is O(2ⁿ), because it recomputes the same values again and again.n == 0 ? 0 : 1 + (n - 1) % 9.n & (n - 1) clears the lowest set bit, so the result is 0 only for powers of two.String & Collection Programs — Interview Questions — open the lesson
HashMap. — Normalise the text, split it on whitespace, and count with Map.merge (or getOrDefault). O(n) time.HashMap using a while loop and an enhanced for loop. — Iterate over entrySet(), so you get the key and the value together without extra lookups. Use the enhanced for loop for reading.ArrayList using a for loop, a while loop and an enhanced for loop. — List<Integer> list = List.of(10, 20, 30); for (int i = 0; i < list.size(); i++)…int[] for a small alphabet), then report the characters with a count above 1.highest and the second highest. When a value beats highest, the old highest becomes second.replace(). — Build a new string with a StringBuilder, appending only the characters that aren't whitespace. O(n).Array & String Problem Solving — Interview Questions — open the lesson
[val, index] (add val to nums[index]), return the sum of the even numbers. — maintain a running total incrementally instead of re-summing the array after every query. O(n + q) instead of O(n·q).p's anagrams in s. — a fixed-size sliding window with character counts. Slide a window of length p.length() across s, updating the counts in O(1) per step.left past its previous occurrence.n numbers in the range [1, n], find the numbers in that range that don't appear. — in-place marking. Use the sign of nums[v - 1] to record that value v was seen. O(n) time, O(1) extra space (not counting the output).Q: How should I use this list in the last week before an interview? A: Do one pass per day. Cover the answer text, say your answer out loud, then check it. Mark every question you could not answer crisply, and spend your study time only on the marked ones by opening the linked full answer. By the third pass the marked list should be short.
Q: The interviewer asks one of these basics — should I give only the one-liner? A: Lead with the one-liner, then add one concrete detail or example from your own work. At this level the follow-up usually probes the mechanism behind the basic answer, so be ready to go one layer deeper using the key points in the full lesson.
Q: Some answers here were corrected compared with common prep sheets — why? A: Several widely shared answers are outdated or wrong (for example, Java version details, removed Spring APIs, or SQL queries that miss edge cases). The full lessons call these out under "Common trap" — reading those is the fastest way to stand out from candidates who memorised the same sheets.