Java Programming Interview Questions with Answers

Java Programming Interview Questions with Answers

Below is a curated list of common Java programming interview questions and concise answers to help you prepare. Use these as a starting point for your study, and be ready to elaborate or provide examples during an interview.


1. What is the difference between JDK, JRE, and JVM?

Answer:

  • JVM (Java Virtual Machine): An abstract machine that executes Java bytecode. It provides a runtime environment in which Java bytecode can be executed.
  • JRE (Java Runtime Environment): A package containing the necessary libraries and the JVM for running Java applications but does not include development tools (like a compiler).
  • JDK (Java Development Kit): A superset of the JRE that includes development tools such as the Java compiler (javac), Java debugger, and other tools. It’s used for both developing and running Java applications.

2. What is the difference between == and .equals() in Java?

Answer:

  • == Operator: Compares references (for objects) or values (for primitive types). For objects, == returns true if and only if both references point to the same object in memory.
  • .equals() Method: Typically compares the contents or state of two objects. By default, Object.equals() behaves like ==, but many classes (e.g., String) override .equals() to check for equivalence of values rather than reference equality.

3. Explain the concept of pass-by-value in Java.

Answer: Java uses pass-by-value for all data types. When you pass a variable into a method:

  • For primitive types (e.g., int, boolean), the method receives a copy of the original value.
  • For object references, the method receives a copy of the reference, pointing to the same object. This means changes to the object’s internal state will be visible outside the method, but reassigning the reference inside the method does not affect the original reference.

4. What is the difference between method overloading and method overriding?

Answer:

  • Overloading: Occurs within the same class. Methods have the same name but different parameter lists (e.g., different numbers or types of parameters). It is a compile-time polymorphism.
  • Overriding: Occurs in a subclass that provides a different implementation of a method declared in a superclass. The method signature (name and parameters) must be identical, but the subclass’s version is executed at runtime (runtime polymorphism).

5. What are final, finally, and finalize()?

Answer:

  • final Keyword: Can be applied to classes, methods, and variables.
    • A final class can’t be subclassed.
    • A final method can’t be overridden.
    • A final The variable’s value can’t be changed once it is assigned.
  • finally Block: Part of exception handling. Code in a finally block always executes regardless of whether an exception is thrown or caught (except in rare cases like a System.exit() call).
  • finalize() Method (deprecated in Java 9+): A method the garbage collector could call on an object before collection. It was typically used for cleanup but is discouraged due to unpredictability and performance issues.

6. What is the difference between an abstract class and an interface?

Answer:

  • Abstract Class:
    • It can contain abstract methods (without a body) as well as non-abstract methods (with an implementation).
    • It can have instance variables.
    • A class can only extend one abstract class.
  • Interface:
    • By default, it only contains abstract methods (Java 8 introduced default and static methods in interfaces).
    • It cannot have instance fields (except public static final constants).
    • A class can implement multiple interfaces.

7. What are checked vs. unchecked exceptions?

Answer:

  • Checked Exceptions: Subclasses of Exception (excluding RuntimeException). They must be handled using a try-catch block or declared in the method signature with throws. Examples: IOException, SQLException.
  • Unchecked Exceptions: Subclasses of RuntimeException. They usually result from programming errors (e.g., NullPointerException, ArrayIndexOutOfBoundsException) and do not need to be explicitly handled or declared.

8. What is the purpose of the static keyword?

Answer:

  • Static variables: Belong to the class rather than any individual instance. All instances share the same static variable.
  • Static methods: Can be invoked without creating an instance of the class. They only have access to static data and cannot directly call instance methods or access instance variables without an object reference.
  • Static blocks: These are used for static initialization of variables when the class is loaded.

9. How does HashMap differ from Hashtable?

Answer:

  • Synchronization: Hashtable is synchronized (thread-safe), whereas HashMap is not synchronized by default.
  • Null keys and values: HashMap allows one null key and any number of null values. Hashtable does not allow null keys or values.
  • Performance: Because HashMap is unsynchronized, it generally performs faster than Hashtable under single-threaded or externally synchronized scenarios.

10. Explain the difference between ArrayList and LinkedList.

Answer:

  • Underlying Data Structure: ArrayList is based on a dynamic array while LinkedList is a doubly-linked list.
  • Access/Insertion Performance:
    • ArrayList: Fast random access by index (O(1) on average), but slow inserts/removes in the middle (O(n)).
    • LinkedList: Slow random access (O(n)), but faster inserts/removes when at known positions (e.g., at the head or tail).
  • Use Cases: Use ArrayList when access speed by index is essential; use LinkedList for frequent insertions/removals in the middle.

11. What is polymorphism?

Answer: Polymorphism is the ability of an object to take on many forms. In Java, it typically refers to the use of a superclass reference to refer to a subclass object. The actual method that gets called is determined at runtime (dynamic binding). Method overriding and method overloading are two forms of polymorphism, but overriding represents runtime polymorphism, and overloading represents compile-time polymorphism.


12. How does garbage collection work in Java?

Answer: Java automatically manages memory through garbage collection (GC). The GC identifies and discards objects no longer reachable by any live references. Key points:

  • You don’t manually free memory (like in C/C++).
  • The exact GC algorithm can vary by JVM implementation (e.g., Parallel GC, G1 GC, ZGC).
  • It won't be collected if an object is reachable (through local variables, static references, or other objects).

13. Explain the concept of String immutability in Java.

Answer: Strings in Java are immutable, meaning once an String object is created, its value cannot be changed. Reasons for string immutability:

  • Thread-safety: Multiple threads can safely share the same String instance.
  • Caching: Strings can be cached for performance, allowing features like string interning.
  • Security: In some contexts (e.g., network connections, class loading), having immutable strings helps ensure that values cannot be changed after creation.

14. What are default and static methods in interfaces (Java 8+)?

Answer:

  • Default methods: Provide a default implementation in an interface. Classes implementing that interface can use the default implementation if they do not override it.
  • Static methods: Declared with the static keyword in an interface. They can be called without an instance using the interface’s name (e.g., InterfaceName.methodName()).

15. What is the difference between a process and a thread?

Answer:

  • Process: An independent program is executed with its own memory space.
  • Thread: A smaller execution unit within a process; threads share the process’s memory and resources. Multiple threads can run concurrently within the same process.

16. What is a daemon thread in Java?

Answer: A daemon thread is a service thread that typically performs background tasks (e.g., garbage collection). In Java:

  • The JVM does not wait for daemon threads to finish before shutting down.
  • By default, most threads are user threads; you can make a thread a daemon by calling setDaemon(true) before the thread starts.

17. How does the synchronized keyword work in Java?

Answer: synchronized is used to ensure that only one thread at a time can access a block of code or method, preventing race conditions. It can be applied in two ways:

  1. Method Level: public synchronized void doSomething() { ... }
  2. Block Level: synchronized (lockObject) { ... } A thread entering a synchronized block/method acquires the object’s lock. Other threads trying to enter a synchronized block/method on the same object must wait until the lock is released.

18. What is a volatile variable?

Answer: A volatile variable ensures that:

  • Its value is always read from the main memory, not a thread’s local cache.
  • Writes to a volatile variable are immediately written back to the main memory. This helps maintain consistency of the variable’s value across multiple threads, but it does not provide atomicity for compound operations (e.g., count++).

19. What is the Singleton design pattern? How can it be implemented in Java?

Answer: Singleton is a creational design pattern that ensures only one class instance exists and provides a global point of access to it. Common implementations in Java:

  1. Eager Initialization:
    public class Singleton {
        private static final Singleton INSTANCE = new Singleton();
        private Singleton() { }
        public static Singleton getInstance() {
            return INSTANCE;
        }
    }
    
  2. Lazy Initialization (Thread-Safe with Double-Check Locking):
    public class Singleton {
        private static volatile Singleton instance;
        private Singleton() { }
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
    

20. What is the Collections framework in Java?

Answer: The Java Collections framework provides a set of classes and interfaces for storing and manipulating groups of data. It includes:

  • Interfaces: Collection, List, Set, Map, etc.
  • Implementations: ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, etc.
  • Algorithms: Sorting, searching, shuffling, etc. (in Collections utility class). It standardizes how groups of objects are handled, offering robust data structures and algorithms out of the box.

Additional Tips

  • Always provide real-world examples or code snippets to illustrate your points.
  • Be comfortable discussing time complexity (Big-O notation) when comparing data structures.
  • Stay up-to-date with newer Java versions (records, pattern matching, sealed classes, etc.) and their features.

Good luck with your interview preparation!

Prakash Bojja

I have a personality with all the positives, which makes me a dynamic personality with charm. I am a software professional with capabilities far beyond those of anyone who claims to be excellent.

Post a Comment

Previous Post Next Post

Contact Form