DEV Community

Cover image for Top 50 Java Interview Questions and Answers
Ashish Sharda
Ashish Sharda

Posted on

Top 50 Java Interview Questions and Answers

A comprehensive guide to ace your Java technical interviews, covering fundamentals to advanced concepts.

Basic Java Concepts

1. What is Java?

Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now Oracle) in 1995. It follows the "Write Once, Run Anywhere" (WORA) principle, meaning compiled Java code can run on any platform that supports Java without recompilation.

2. What are the main features of Java?

  • Object-Oriented: Based on objects and classes
  • Platform Independent: Runs on any device with JVM
  • Simple and Secure: Easy syntax, built-in security features
  • Robust: Strong memory management and exception handling
  • Multithreaded: Supports concurrent execution
  • Architecture Neutral: Bytecode can run on any architecture

3. What is JVM, JRE, and JDK?

  • JVM (Java Virtual Machine): Runtime environment that executes Java bytecode
  • JRE (Java Runtime Environment): Provides libraries and JVM to run Java applications
  • JDK (Java Development Kit): Complete development kit including JRE, compiler, debugger, and tools

4. What is the difference between JDK and JRE?

JDK is used for development and contains development tools like compiler and debugger, while JRE is used only for running Java applications. JDK includes JRE, but JRE doesn't include development tools.

5. Explain public static void main(String[] args)

  • public: Access modifier, makes method accessible from anywhere
  • static: Method belongs to class, not instance; can be called without creating object
  • void: Method doesn't return any value
  • main: Entry point of Java application
  • String[] args: Command-line arguments passed as string array

Object-Oriented Programming

6. What are the four pillars of OOP?

  1. Encapsulation: Bundling data and methods, hiding internal details
  2. Inheritance: Acquiring properties from parent class
  3. Polymorphism: Same interface, different implementations
  4. Abstraction: Hiding implementation details, showing only functionality

7. What is the difference between abstract class and interface?

  • Abstract Class: Can have both abstract and concrete methods, can have constructors, supports single inheritance
  • Interface: All methods are abstract by default (before Java 8), no constructors, supports multiple inheritance

8. Can we override static methods?

No, static methods cannot be overridden. They can be hidden through method hiding. Static methods belong to the class, not instances, so they're resolved at compile-time, not runtime.

9. What is method overloading and method overriding?

  • Overloading: Multiple methods with same name but different parameters in the same class (compile-time polymorphism)
  • Overriding: Subclass provides specific implementation of method already defined in parent class (runtime polymorphism)

10. What is constructor in Java?

A constructor is a special method used to initialize objects. It has the same name as the class and no return type. Java provides a default constructor if none is defined.

Data Types and Variables

11. What are primitive data types in Java?

Java has 8 primitive types: byte, short, int, long, float, double, char, and boolean. These are not objects and hold values directly in memory.

12. What is the difference between int and Integer?

  • int: Primitive data type, stores actual value, default is 0
  • Integer: Wrapper class, stores object reference, default is null, provides utility methods

13. What is autoboxing and unboxing?

  • Autoboxing: Automatic conversion of primitive to wrapper class (int to Integer)
  • Unboxing: Automatic conversion of wrapper class to primitive (Integer to int)

14. What is the difference between == and equals()?

  • ==: Compares reference (memory address) for objects, values for primitives
  • equals(): Compares content/values of objects, can be overridden for custom comparison

15. What is String pool in Java?

String pool is a special memory region in heap where JVM stores string literals. When you create a string literal, JVM checks if it exists in pool; if yes, returns reference to existing string, otherwise creates new one. This optimizes memory usage.

Collections Framework

16. What is the difference between ArrayList and LinkedList?

  • ArrayList: Dynamic array, fast random access (O(1)), slow insertion/deletion in middle (O(n))
  • LinkedList: Doubly-linked list, slow random access (O(n)), fast insertion/deletion (O(1))

17. What is the difference between HashSet and TreeSet?

  • HashSet: Uses hash table, unordered, allows null, O(1) operations
  • TreeSet: Uses red-black tree, sorted order, doesn't allow null, O(log n) operations

18. What is the difference between HashMap and Hashtable?

  • HashMap: Not synchronized, allows one null key and multiple null values, faster
  • Hashtable: Synchronized, doesn't allow null keys or values, slower due to synchronization

19. What is the difference between List and Set?

  • List: Ordered collection, allows duplicates, maintains insertion order
  • Set: Unordered collection, doesn't allow duplicates, no guaranteed order (except TreeSet and LinkedHashSet)

20. What is ConcurrentHashMap?

A thread-safe implementation of HashMap that allows concurrent read and write operations. It divides the map into segments, allowing multiple threads to access different segments simultaneously without locking the entire map.

Exception Handling

21. What is the difference between checked and unchecked exceptions?

  • Checked: Must be caught or declared (IOException, SQLException), checked at compile-time
  • Unchecked: Runtime exceptions, not required to be caught (NullPointerException, ArrayIndexOutOfBoundsException)

22. What is the difference between throw and throws?

  • throw: Used to explicitly throw an exception
  • throws: Used in method signature to declare exceptions that method might throw

23. Can we have try without catch?

Yes, we can have try with finally without catch. We can also have try-with-resources without catch. However, we cannot have try alone without catch or finally.

24. What is finally block?

Finally block always executes whether an exception is thrown or not. It's used for cleanup operations like closing resources. It executes even if there's a return statement in try or catch block.

25. Can we override a method that throws unchecked exception?

Yes, we can override a method that throws unchecked exception. The overriding method can throw any unchecked exception regardless of what the parent method throws.

Multithreading

26. What is the difference between process and thread?

  • Process: Independent execution unit with its own memory space
  • Thread: Lightweight process within a process, shares memory with other threads

27. How can we create a thread in Java?

Two ways:

  1. Extending Thread class
  2. Implementing Runnable interface (preferred as it allows extending other classes)

28. What is synchronization?

Synchronization is the capability to control access of multiple threads to shared resources. It prevents thread interference and consistency problems.

29. What is the difference between wait() and sleep()?

  • wait(): Releases lock, must be called from synchronized context, wakes up by notify()/notifyAll()
  • sleep(): Doesn't release lock, can be called from anywhere, wakes up after specified time

30. What is deadlock?

Deadlock is a situation where two or more threads are blocked forever, waiting for each other. It occurs when multiple threads need the same locks but obtain them in different order.

Java 8 Features

31. What are lambda expressions?

Lambda expressions provide a clear and concise way to implement functional interfaces using an expression. They enable functional programming in Java.
Syntax: (parameters) -> expression or (parameters) -> { statements; }

32. What is Stream API?

Stream API is used to process collections of objects. It supports functional-style operations like filter, map, reduce, etc. Streams don't store data and are lazy evaluated.

33. What is functional interface?

A functional interface has exactly one abstract method. It can have multiple default or static methods. Examples: Runnable, Callable, Comparator. Annotated with @FunctionalInterface.

34. What is Optional class?

Optional is a container object used to contain not-null objects. It helps avoid NullPointerException and makes code more readable by explicitly dealing with absence of values.

35. What are default methods in interface?

Default methods allow adding new methods to interfaces without breaking existing implementations. They have a body and are prefixed with 'default' keyword.

Memory Management

36. What is garbage collection?

Garbage collection is the automatic process of reclaiming memory by deleting objects that are no longer reachable or referenced. The JVM's garbage collector handles this.

37. What is the difference between stack and heap memory?

  • Stack: Stores local variables, method calls, primitive values; fast access; small size; LIFO structure
  • Heap: Stores objects and instance variables; slower access; larger size; garbage collected

38. What are memory leaks in Java?

Memory leaks occur when objects are no longer used but still referenced, preventing garbage collector from reclaiming memory. Common causes: unclosed resources, static collections, improper cache implementation.

39. What is finalize() method?

finalize() is called by garbage collector before reclaiming an object's memory. It's used for cleanup operations. However, it's deprecated since Java 9; try-with-resources or explicit cleanup methods are preferred.

40. What is the difference between final, finally, and finalize?

  • final: Keyword for constants, preventing inheritance/overriding
  • finally: Block that always executes in try-catch-finally
  • finalize(): Method called before garbage collection

Advanced Concepts

41. What is reflection in Java?

Reflection is the ability to inspect and modify class structure at runtime. It allows examining classes, interfaces, fields, and methods without knowing their names at compile time.

42. What is serialization?

Serialization is converting an object into byte stream for storage or transmission. Deserialization is the reverse. Classes must implement Serializable interface.

43. What is transient keyword?

Transient keyword prevents a variable from being serialized. When an object is deserialized, transient variables are initialized to default values.

44. What is volatile keyword?

Volatile ensures that variable's value is always read from main memory, not from thread's cache. It guarantees visibility of changes across threads.

45. What is the difference between Comparable and Comparator?

  • Comparable: Interface for natural ordering, has compareTo() method, modifies the class
  • Comparator: Interface for custom ordering, has compare() method, external to class

Design Patterns and Best Practices

46. What is Singleton pattern?

Singleton ensures a class has only one instance and provides global access point. Implementation involves private constructor, static instance variable, and public static method to get instance.

47. What is immutable class?

Immutable class whose state cannot be modified after creation. String is immutable. To create: make class final, all fields private and final, no setters, deep copy mutable objects.

48. What is the difference between shallow copy and deep copy?

  • Shallow Copy: Copies object but references to nested objects are copied (same nested objects)
  • Deep Copy: Copies object and creates new copies of all nested objects

49. What are SOLID principles?

  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

50. What is dependency injection?

Dependency injection is a design pattern where objects receive their dependencies from external sources rather than creating them. It promotes loose coupling and testability. Frameworks like Spring use DI extensively.

Conclusion

These questions cover fundamental to advanced Java concepts commonly asked in interviews. Practice coding examples for each concept and understand the underlying principles. Good luck with your interviews!

Feel free to bookmark this guide and share it with others preparing for Java interviews!

Top comments (0)