Java interview questions
Common Java questions from technical rounds, with answers that explain the reasoning rather than just the definition.
== compares primitive values, or for objects, whether two references point to the same object. equals() compares logical content when a class overrides it, as String and the wrapper classes do. For example, two Strings created with new String("a") are not == to each other but are equal by equals().
Immutability lets the JVM safely share String literals through the string pool, and it makes Strings safe as HashMap keys because their hash code cannot change. It also makes them thread-safe without locking and protects values like file paths after they have been validated. When I need to build text repeatedly, I use StringBuilder instead.
ArrayList is my default for an ordered list with fast access by index. LinkedList only helps when I add or remove at the ends often, and ArrayDeque usually does that job better. HashMap stores key-value pairs with fast lookup by key, and HashSet stores unique values when I only need to check membership.
Overloading means several methods in a class share a name but have different parameter lists, and the compiler picks one from the argument types. Overriding means a subclass provides its own version of an inherited method with the same signature, and the JVM picks the version at runtime from the actual object. I add @Override so the compiler catches signature mistakes.
Checked exceptions, such as IOException, must be caught or declared with throws, and the compiler enforces this. Unchecked exceptions extend RuntimeException and usually signal programming errors such as a null reference or a bad index. I catch checked exceptions where I can genuinely recover, and fix the cause of unchecked ones rather than hiding them.
A stream is a pipeline for processing a collection with operations such as filter, map and collect, written in a declarative style. Intermediate operations are lazy and only run when a terminal operation such as collect or count is called. I use streams for clear transformations, for example filtering active users and collecting their emails into a list, and keep a plain loop when the logic has many side effects.
Practise out loud. Say each answer once as written, then again in your own words with your own number or story.
Have a number ready. "My Java score is at benchmark on a timed test" is a stronger answer than "I am good at it". Take the test and quote the result.
More in Programming