Junior (0-2 years)Java

What is the difference between checked and unchecked exceptions in Java?

Quick answer

Checked exceptions (subclasses of Exception other than RuntimeException) must be caught or declared with throws, while unchecked exceptions (RuntimeException and Error) do not have to be handled and usually signal programming bugs.

Checked exceptions such as IOException and SQLException represent failures the caller can reasonably be expected to handle or recover from, so the compiler forces you to deal with them. Unchecked exceptions such as NullPointerException, IllegalArgumentException and IndexOutOfBoundsException indicate bugs, and fixing the code is better than catching them. Error (for example OutOfMemoryError) signals serious JVM problems you should not catch.

Good practice: never swallow an exception silently, catch the most specific type, add context when you wrap it, and keep the original as the cause (new ServiceException("msg", e)). Many modern frameworks, including Spring, prefer unchecked exceptions because checked ones clutter method signatures.

  • What is the difference between ArrayList and LinkedList in Java?

    ArrayList is backed by a resizable array with O(1) index access and O(n) insertion in the middle, while LinkedList is a doubly linked list with O(n) index access and O(1) insertion once you hold the node; in practice ArrayList is faster for most workloads.

  • What are the main features of Java 8: lambdas, streams and Optional?

    Java 8 introduced lambda expressions, functional interfaces, the Stream API for declarative collection processing, Optional to represent missing values, default methods in interfaces, method references and the java.time date and time API.

  • What is the difference between an abstract class and an interface in Java?

    An abstract class can have instance fields, constructors and a mix of implemented and abstract methods but supports only single inheritance, while an interface defines a contract that a class can implement multiple times and, since Java 8, can include default methods.

  • How does HashMap work internally in Java?

    A HashMap stores entries in an array of buckets; it computes the key's hash code to choose a bucket, resolves collisions with a linked list that becomes a red-black tree when a bucket grows large, and resizes when the load factor of 0.75 is exceeded.