Java Interview Questions

1. What makes Java a platform-independent language?

Java achieves platform independence through its "Write Once, Run Anywhere" (WORA) philosophy. The Java compiler converts source code into an intermediate form called bytecode, which is executed by the Java Virtual Machine (JVM). Since JVM implementations exist for different operating systems, the same bytecode can run across multiple platforms without modification.

2. How does Java differ from C++?

  • Java is purely object-oriented, while C++ supports both procedural and object-oriented paradigms.
  • Java has automatic memory management via garbage collection, whereas C++ requires manual memory management.
  • Java does not support multiple inheritance using classes but uses interfaces instead.
  • Unlike C++, Java lacks pointers for direct memory manipulation, improving security.
  • Java is interpreted at runtime via JVM, while C++ code is compiled directly to machine code.

3. Why isn’t Java considered a purely object-oriented language?

Java is not fully object-oriented because it includes primitive data types (int, char, float, etc.) that are not objects. Pure OOP languages treat everything as an object, whereas Java allows operations on primitives without wrapping them in objects.

4. Explain the difference between Heap and Stack memory in Java. How does Java utilize them?

  • Heap Memory: Stores objects and instance variables; shared among threads. Objects remain until garbage collection removes them.
  • Stack Memory: Stores method calls, local variables, and function execution contexts. Each thread has its own stack, and memory is released as methods finish execution.

5. What is the difference between an instance variable and a local variable?

  • Instance Variable: Declared within a class but outside methods, belongs to an object, and persists as long as the object exists.
  • Local Variable: Declared inside a method or block, exists only during method execution, and is stored in stack memory.

6. Define data encapsulation.

Encapsulation is an OOP principle where data and methods that operate on the data are bundled within a single unit (class). It ensures data security by restricting direct access using access modifiers (private, protected, public).

7. Differentiate between static methods, static variables, and static classes.

  • Static Methods: Belong to the class rather than instances; can be accessed without object creation.
  • Static Variables: Shared among all instances of the class; memory is allocated only once in the class’s lifetime.
  • Static Classes: Nested static classes exist within another class and can be accessed without an instance of the outer class.

8. What is the primary purpose of garbage collection in Java?

Garbage collection in Java automatically reclaims memory occupied by objects that are no longer referenced, preventing memory leaks and improving application efficiency.

9. What is a ClassLoader in Java?

A ClassLoader is responsible for dynamically loading classes into memory at runtime. Java has three primary ClassLoaders:

  • Bootstrap ClassLoader: Loads core Java classes (e.g., java.lang package).
  • Extension ClassLoader: Loads classes from the ext directory.
  • Application ClassLoader: Loads classes from the classpath.

10. Explain method overloading and method overriding with relevant examples.

Method Overloading: Defining multiple methods in the same class with the same name but different parameters.

class MathOperations {
    int add(int a, int b) { return a + b; }
    double add(double a, double b) { return a + b; }
}

Method Overriding: A subclass provides a new implementation for a method inherited from its superclass.

class Parent {
    void show() { System.out.println("Parent class"); }
}
class Child extends Parent {
    void show() { System.out.println("Child class"); }
}

11. Is it possible to override static methods in Java?

No, static methods are associated with the class itself rather than any specific instance, which means they cannot be overridden.

12. Why is the main() method declared static in Java?

Since the JVM calls main() without creating an object of the class, it must be static to allow execution at the class level.

13. Do final, finally, and finalize serve the same purpose in Java?

  • final: A keyword used for variables (constant values), methods (prevent overriding), and classes (prevent inheritance).
  • finally: A block that executes after a try-catch, ensuring resources are released.
  • finalize: A method used for cleanup before garbage collection.

14. Can a single try block have multiple catch blocks in Java? Explain.

Yes, multiple catch blocks allow handling different exception types separately.

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
} catch (Exception e) {
    System.out.println("General Exception");
}

15. Compare String, StringBuffer, and StringBuilder.

  • String: Immutable; every modification creates a new object.
  • StringBuffer: Mutable and thread-safe but slower due to synchronization.
  • StringBuilder: Mutable and faster but not thread-safe.

16. Why is a character array preferred over a string for storing sensitive information?

Strings are immutable and remain in memory until garbage collection, making them a security risk. A char array can be explicitly cleared after use.

17. What are the different ways to use threads in Java?

  • Extending Thread class
  • Implementing Runnable interface
  • Using ExecutorService for thread pooling

18. Why is synchronization necessary? Provide an example.

Synchronization prevents multiple threads from accessing shared resources concurrently, avoiding data inconsistency.

class SharedResource {
    synchronized void display() { System.out.println("Thread-safe execution"); }
}

19. How does HashMap differ from HashTable in Java?

  • HashMap: Not synchronized, allows one null key, faster.
  • HashTable: Synchronized, does not allow null keys, slower.

20. Why is the remove() method faster in a linked list than in an array?

Removing an element in a linked list involves changing pointers, whereas an array requires shifting elements.

21. Though inheritance is widely used in OOP, why is composition often preferred?

Composition provides better flexibility and reduces tight coupling compared to inheritance, making code easier to maintain and modify.

22. What are the different ways an object can become eligible for garbage collection in Java?

  • Setting the reference to null
  • Assigning a new reference to an existing object
  • Object goes out of scope

23. Describe the Java thread lifecycle.

States: New → Runnable → Running → Blocked/Waiting → Terminated

24. Palindrome check using recursion:

boolean isPalindrome(String str, int start, int end) {
    return (start >= end) || (str.charAt(start) == str.charAt(end) && isPalindrome(str, start + 1, end - 1));
}

25. Find missing number in an array:

int findMissing(int[] arr, int n) {
    int sum = n * (n + 1) / 2;
    for (int num : arr) sum -= num;
    return sum;
}