Comprehensive Java Interview Guide: Basics, Collections, Concurrency, Spring Boot, MySQL, and Network Concepts

This article provides a thorough overview of Java interview topics, covering core language fundamentals, collection frameworks, concurrency mechanisms, Spring Boot transaction handling, database indexing strategies, and network protocol comparisons, all presented in clear English with code examples and diagrams.

IT Services Circle
IT Services Circle
IT Services Circle
Comprehensive Java Interview Guide: Basics, Collections, Concurrency, Spring Boot, MySQL, and Network Concepts

Java Basics

Difference between Overloading and Overriding

Overloading allows multiple methods with the same name in the same class but with different parameter lists; the compiler selects the appropriate method based on the argument types.

Overriding lets a subclass redefine a method from its superclass with the same name, parameters, and return type, typically marked with the @Override annotation.

In short, overloading is about multiple signatures within one class, while overriding is about redefining behavior in a subclass.

Java Collection Classes

List is an ordered collection; common implementations include ArrayList, LinkedList, Vector, and Stack. ArrayList uses a dynamic array, offering fast random access (O(1)) but slower insert/delete operations due to array copying. LinkedList is a doubly‑linked list, providing O(1) insert/delete at the ends but O(n) random access.

Set disallows duplicate elements and is unordered; typical implementations are HashSet, LinkedHashSet, and TreeSet. HashSet is backed by HashMap and is not thread‑safe. LinkedHashSet preserves insertion order via a linked hash map. TreeSet maintains sorted order using a red‑black tree.

Map stores key‑value pairs; common implementations include HashMap, LinkedHashMap, TreeMap, Hashtable, and ConcurrentHashMap. HashMap switches to a red‑black tree when a bucket exceeds a threshold (default 8) to improve lookup performance.

ArrayList vs LinkedList

Data‑structure differences: ArrayList uses a dynamic array (fast O(1) random access), while LinkedList uses a doubly‑linked list (fast O(1) insert/delete at head or tail).

Performance differences: ArrayList incurs O(n) cost when expanding or inserting/removing non‑tail elements; LinkedList requires O(n) traversal for non‑head/tail operations and also O(n) for random access.

String, StringBuilder, and StringBuffer

String

is immutable; each modification creates a new object, which can be costly for heavy string manipulation. StringBuilder and StringBuffer are mutable. StringBuffer is thread‑safe because its methods are synchronized, while StringBuilder is not synchronized and therefore faster in single‑threaded contexts.

Java Concurrency

Ways to Create a Thread

Extend Thread, implement Runnable, implement Callable, or use the Executors utility to obtain a thread pool.

Thread Lifecycle and Pool States

Thread states include RUNNING, SHUTDOWN, STOP, TIDYING, and TERMINATED. A thread pool has core size, maximum size, keep‑alive time, work queue, thread factory, and rejection handler.

The pool creates new threads up to corePoolSize; excess tasks go to the queue; if the queue is full, new threads are created up to maximumPoolSize; beyond that, the rejection policy applies.

corePoolSize : number of core threads that stay alive even when idle.

maximumPoolSize : upper limit of threads; new threads are created when the queue is full.

keepAliveTime : idle time after which non‑core threads are terminated.

unit : time unit for keepAliveTime.

workQueue : holds tasks awaiting execution.

threadFactory : creates new threads (e.g., naming).

handler : rejection strategy when the pool cannot accept more tasks.

Thread‑Safety Techniques in Java

synchronized

blocks or methods. ReentrantLock for explicit lock control.

Atomic classes such as AtomicInteger, AtomicLong.

Thread‑safe collections like ConcurrentHashMap, CopyOnWriteArrayList. ThreadLocal for per‑thread variables.

Optimistic Locking

Optimistic locking assumes low contention: a thread updates a resource first, then verifies that no other thread modified it in the meantime (often using a version number). If a conflict is detected, the operation is aborted and may be retried.

Typical use‑case: collaborative document editing where each client sends the original version number with its changes; the server rejects the update if the version has advanced.

Java Frameworks

How to Enable Transactions in Spring Boot

Annotate the service method with @Transactional. Example:

public interface UserService {
    void saveUser(User user);
}
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional
    public void saveUser(User user) {
        userRepository.save(user);
    }
}

Spring will start a transaction when saveUser() is called and commit or roll back automatically based on success or failure.

Difference Between Spring and Spring Boot

Spring Boot bundles Spring with auto‑configuration, convention‑over‑configuration, and embedded servers, eliminating the need for extensive XML/Java configuration and simplifying dependency management.

MySQL

Creating an Index for a Query

For SELECT a,b,c FROM t WHERE a = ? AND b = ? ORDER BY c ASC, create a composite index on (a,b,c) so that the WHERE clause and the ORDER BY can be satisfied without extra sorting.

Follow‑up: If the index is defined as (a,c,b) , it will still be used, but only columns a and c can benefit; b cannot because the left‑most prefix rule is broken.

SQL Exercise: Top Student per Class

SELECT class,
       MAX(score) AS max_score,
       student_id
FROM student
GROUP BY class;

Preventing Phantom Reads in Repeatable‑Read Isolation

Issue a SELECT ... FOR UPDATE immediately after starting the transaction; this acquires a next‑key lock that blocks other transactions from inserting rows that would appear in the result set, thus avoiding phantom reads.

Network

TCP vs HTTP

TCP operates at the transport layer, providing reliable, ordered, error‑checked delivery.

HTTP is an application‑layer protocol that runs on top of TCP to exchange web resources.

TCP vs UDP

TCP is connection‑oriented, reliable, with flow and congestion control; UDP is connectionless, best‑effort.

TCP header is 20 bytes (more with options); UDP header is a fixed 8 bytes.

TCP streams data; UDP sends discrete packets.

Typical TCP use‑cases: HTTP, FTP; typical UDP use‑cases: video/audio streaming, DNS.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencySpring BootmysqlinterviewNetworking
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.