Java interview questions
JVM, strings, exceptions, collections, multithreading and the questions asked most in service company interviews.
1. What is the difference between JDK, JRE and JVM?
The JVM runs Java bytecode and makes Java platform-independent. The JRE is the JVM plus the standard libraries needed to run programs. The JDK is the JRE plus development tools such as the compiler (javac) and debugger.
2. What is the difference between C++ and Java?
Java compiles to bytecode that runs on the JVM (platform-independent); C++ compiles to native code. Java has automatic garbage collection, no explicit pointers and no multiple inheritance of classes; C++ has manual memory management, pointers, multiple inheritance and operator overloading.
Asked in: Wipro Elite NTH
3. What is the difference between an error and an exception?
Both extend Throwable. An Error is a serious problem the program usually should not try to handle, such as OutOfMemoryError or StackOverflowError. An Exception is a condition the program can catch and recover from, such as IOException or ArithmeticException.
Asked in: TCS NQT, Wipro Elite NTH
4. What are checked and unchecked exceptions?
Checked exceptions (IOException, SQLException) are checked at compile time and must be caught or declared with throws. Unchecked exceptions (subclasses of RuntimeException, such as NullPointerException or ArrayIndexOutOfBoundsException) are not checked by the compiler.
5. How do try, catch and finally work? Does finally always run?
try holds code that may throw, catch handles a matching exception, and finally runs whether or not an exception occurred, even after a return in try. It is skipped only if the JVM stops (for example System.exit). If finally has its own return, that value wins, which is a common output question.
Asked in: Tech Mahindra
6. What is the difference between final, finally and finalize?
final is a keyword: a final variable cannot be reassigned, a final method cannot be overridden, a final class cannot be extended. finally is the block after try/catch that always runs. finalize() was a method called by the garbage collector before removing an object; it is deprecated.
7. Why are strings immutable? String versus StringBuilder versus StringBuffer?
String objects cannot change, which makes them safe to share, cache in the string pool and use as map keys. StringBuilder is mutable and fast for building strings in one thread; StringBuffer is mutable and synchronised (thread-safe) but slower.
8. What is the difference between == and equals()?
== compares references (whether both variables point to the same object; for primitives it compares values). equals() compares contents when the class overrides it, as String does. If you override equals, override hashCode too.
9. What does static mean?
A static member belongs to the class rather than to objects: one shared copy, accessed with the class name. Static methods cannot use this or non-static members directly. main is static so the JVM can call it without creating an object.
10. What is garbage collection?
The JVM automatically frees memory used by objects that are no longer reachable from any live reference. You cannot force it; System.gc() is only a request. It removes the need for manual free/delete.
Asked in: Tech Mahindra
11. What is the difference between ArrayList and LinkedList?
ArrayList is backed by a resizable array: fast random access by index, slower insertion and removal in the middle. LinkedList is a doubly linked list: fast insertion and removal at known positions, slow access by index.
12. How does a HashMap work?
It stores key-value pairs in an array of buckets. The key's hashCode() picks the bucket and equals() finds the right key inside it. Collisions are kept in a list (turned into a tree when a bucket gets large). It allows one null key and is not thread-safe; use ConcurrentHashMap for that.
13. What is the Collections framework?
A set of interfaces and classes for groups of objects: List (ArrayList, LinkedList), Set (HashSet, TreeSet), Queue (PriorityQueue, ArrayDeque) and Map (HashMap, TreeMap). Collection is the root interface; Collections is a utility class with methods like sort.
Asked in: Cognizant GenC, Deloitte
14. How do you create a thread? Thread versus Runnable?
Either extend Thread and override run(), or implement Runnable and pass it to a Thread, then call start() (not run()). Implementing Runnable is preferred because the class can still extend another class. Executors and thread pools are used in real projects.
Asked in: Cognizant GenC
15. What is synchronisation?
Controlling access to shared data so only one thread uses it at a time, using synchronized methods or blocks (or locks). It prevents race conditions but can cause deadlock if locks are taken in different orders.
16. What is serialisation?
Converting an object into a byte stream so it can be saved to a file or sent over a network, and later rebuilt (deserialisation). A class must implement Serializable; fields marked transient are skipped.
Asked in: Tech Mahindra
17. What are lambdas and streams (Java 8)?
A lambda is a short anonymous function, such as (a, b) -> a + b, used with functional interfaces. Streams process collections in a pipeline: list.stream().filter(x -> x > 10).map(x -> x * 2).collect(Collectors.toList()). They make code shorter and easy to parallelise.
Asked in: Accenture
18. What is Spring Boot? Name some annotations.
A framework that makes it quick to build Java web applications and REST APIs with auto-configuration and an embedded server. Common annotations: @SpringBootApplication, @RestController, @GetMapping/@PostMapping, @Autowired (dependency injection), @Service, @Repository and @Entity.
Asked in: Accenture