Interview Questions 1 - 10  «Prev Next»

Java Interview: Iterators, Objects, and Web Sessions

Review Java SE 25 iteration and object behavior, Jakarta Servlet session handling, and the historical Struts 1 Action execution signature.

  1. What is a suitable way to traverse a List?

    Answer: Use an enhanced for loop or Iterator for forward traversal. Use ListIterator when you need bidirectional traversal or supported insertion, replacement, and removal during iteration. Indexed loops suit efficient random-access lists but can be costly on LinkedList.

    No traversal method is universally best. ListIterator starts at a cursor position between elements; listIterator(index) permits indices from zero through size.

  2. How can a ListIterator modify a list?

    Answer: When supported by the list, add inserts at the cursor, set replaces the last element returned by next or previous, and remove removes that last-returned element. State restrictions apply: you cannot call remove before a successful traversal or repeat it without another traversal.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.ListIterator;
    
    public class IteratorEdits {
        public static void main(String[] args) {
            List<String> names = new ArrayList<>(List.of("A", "B"));
            ListIterator<String> cursor = names.listIterator();
            cursor.next();
            cursor.set("Alpha");
            cursor.add("Middle");
            cursor.next();
            cursor.remove();
            System.out.println(names);
        }
    }
    

    Use the iterator's supported operations rather than independently modifying the list during traversal. Fail-fast detection is best effort, not a synchronization mechanism.

  3. How does garbage collection reclaim memory?

    Answer: The collector determines object reachability from roots such as live thread state and static references. Objects no longer strongly reachable can become eligible for reclamation, subject to reference-processing rules. A cycle of otherwise unreachable objects does not prevent collection.

    Collection timing is not guaranteed, and System.gc is only a request. Garbage collection does not replace closing files, sockets, or database resources; use their explicit lifecycle APIs and try-with-resources where applicable.

  4. What is a local class?

    Answer: It is a named class declared within a block, commonly inside a method. It can capture local variables that are final or effectively final. A local class declared in a static context has no enclosing instance, so the claim that every local-class object requires an enclosing object is false.

    Local records and enum classes are implicitly static. The exact kind of declaration and its context determine which enclosing state is available.

  5. What is Comparator for?

    Answer: Comparator supplies an external ordering through compare(a,b). It can sort types you cannot modify or express alternate orderings for one type. Helpers such as comparing and thenComparing combine criteria. The ordering must be consistent and transitive; subtraction is unsafe when integer overflow can reverse the intended sign.

  6. How do Error and Exception differ?

    Answer: Both extend Throwable. Error generally represents serious conditions that ordinary application code is not expected to recover from. Exception represents exceptional conditions applications may handle. RuntimeException and Error subclasses are unchecked; other exception classes are checked.

    Checked exceptions must be caught or declared where the language requires it. The distinction is a type-system rule, not a promise that all Exceptions are recoverable or that every Error instantly stops the entire JVM.

  7. What does this refer to?

    Answer: In an instance context, this refers to the current object. It can qualify a shadowed field, pass or return the current instance, and appear in a constructor invocation this(...). It is unavailable as an instance reference in a static method.

    Inside an ordinary inner-class method, this denotes that inner instance; Outer.this can identify an enclosing instance. A lambda retains the enclosing meaning of this. getClass returns the runtime class, which can differ from a named class literal such as Parent.class.

  8. What is HttpSession?

    Answer: Jakarta Servlet HttpSession stores attributes across requests associated with a session. A servlet obtains it from the request, for example with getSession(false) to avoid creating one when none exists. The session ID lets the container associate later requests with server-side state.

    Several requests can access one session concurrently. Session attributes do not automatically become thread-safe. Invalidation, timeout, and attribute removal affect lifetime; session scope is not permanent storage.

  9. How can servlet session tracking work without cookies?

    Answer: If URL-based tracking is enabled, use HttpServletResponse.encodeURL for application links and encodeRedirectURL for redirects. The container decides whether to add its session identifier, typically as a path parameter such as ;jsessionid=.... Do not manually concatenate a query parameter.

    Ordinary request data can also travel in query parameters or request bodies; that is separate from session tracking. Keep session-bearing URLs within the application and account for their exposure in logs or copied links. Container policy can disable URL tracking.

  10. In legacy Struts 1, what are the four Action.execute parameters?

    Answer: They are ActionMapping, ActionForm, HttpServletRequest, and HttpServletResponse. ActionForward is the return type of that execution method, not the name of a four-parameter operation. The historical API uses javax.servlet types.

    Struts 1 reached end of life in 2013. This question is useful for understanding legacy code, not as a current Java SE 25 or Jakarta Servlet API. Do not transplant its imports into a Tomcat 11 example without a migration design.

References: ListIterator, Throwable, Java SE 25 Language Specification, Jakarta Servlet 6.1, Struts 1 end-of-life notice, Apache Struts 1 dispatch documentation.

SEMrush Software