Advance java interview questions [top 100 FAQ]

 Here’s a list of Top 100 Advanced Java Interview Questions that cover a range of topics including advanced Java concepts, multi-threading, design patterns, Spring framework, JDBC, Java 8 features, performance optimization, and more.


1. What is the difference between HashMap and ConcurrentHashMap?

Answer:

  • HashMap: Not thread-safe, supports only one thread accessing it at a time.
  • ConcurrentHashMap: Thread-safe, designed for high concurrency and allows multiple threads to read and write concurrently.

2. What is the synchronized keyword and how does it work?

Answer:
The synchronized keyword is used to lock an object or method so that only one thread can access the method or block at a time, preventing thread interference.


3. What are the different ways to create threads in Java?

Answer:

  • By extending Thread class: Override the run() method and call start().
  • By implementing Runnable interface: Implement the run() method and pass it to a Thread object.
  • Using ExecutorService: A higher-level replacement for managing threads.

4. What is the difference between wait(), notify(), and notifyAll() in Java?

Answer:

  • wait(): Releases the lock and waits for a condition to be met.
  • notify(): Wakes up one thread waiting on the object's monitor.
  • notifyAll(): Wakes up all threads waiting on the object's monitor.

5. What is the use of volatile keyword in Java?

Answer:
The volatile keyword ensures that changes to a variable are immediately visible to all threads, and prevents thread caching.


6. Explain the concept of Deadlock in Java. How can it be prevented?

Answer:
Deadlock occurs when two or more threads are blocked forever because they are each waiting on the other to release a resource. It can be prevented by avoiding nested locks, using timeouts, and applying lock ordering.


7. What is a ThreadLocal class in Java?

Answer:
ThreadLocal is used to create variables that can only be accessed by the current thread. Each thread will have its own independent copy of the variable.


8. What is the difference between ExecutorService and Executor?

Answer:

  • Executor: Basic interface that provides a way to execute tasks.
  • ExecutorService: A more advanced interface that extends Executor and adds methods like submit(), shutdown(), invokeAll(), etc.

9. What are some key features introduced in Java 8?

Answer:

  • Lambda Expressions
  • Stream API
  • Default Methods in Interfaces
  • Optional Class
  • Nashorn JavaScript Engine

10. What is the Stream API in Java 8?

Answer:
The Stream API allows processing sequences of elements (collections, arrays) in a functional style. It provides operations like filter(), map(), reduce(), and collect() to perform various tasks.


11. What are functional interfaces in Java?

Answer:
A functional interface is an interface that has exactly one abstract method. It can have multiple default or static methods. Examples include Runnable, Comparator, Callable, etc.


12. What is a default method in Java 8?

Answer:
A default method is a method defined in an interface with a default implementation. It allows backward compatibility for interfaces.


13. What is the Optional class in Java 8?

Answer:
The Optional class is a container object that may or may not contain a value. It is used to prevent NullPointerException by providing methods like isPresent(), ifPresent(), orElse(), etc.


14. What is a Comparator interface in Java 8?

Answer:
The Comparator interface is used to define custom comparison logic. Java 8 introduced default methods like reversed(), thenComparing(), and comparing() to simplify comparisons.


15. Explain the concept of method references in Java 8.

Answer:
Method references allow you to refer to a method by its name and can be used to simplify lambda expressions. They can refer to static methods, instance methods, or constructor methods.


16. What is Nashorn in Java?

Answer:
Nashorn is a JavaScript engine introduced in Java 8 that allows you to run JavaScript code within Java applications, replacing the old Rhino engine.


17. What is the difference between Callable and Runnable in Java?

Answer:

  • Runnable: Represents a task that does not return a result and cannot throw an exception.
  • Callable: Similar to Runnable but can return a result and throw exceptions.

18. What is Future in Java?

Answer:
A Future represents the result of an asynchronous computation. It provides methods to check if the task is complete, retrieve the result, or cancel the task.


19. What is the difference between ArrayList and Vector?

Answer:

  • ArrayList: Not synchronized and generally faster than Vector.
  • Vector: Synchronized and generally slower than ArrayList.

20. What is Garbage Collection in Java?

Answer:
Garbage collection is the automatic process of reclaiming memory by deleting objects that are no longer reachable by the program.


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

Answer:

  • final: Can be used with variables, methods, or classes to make them constant, unchangeable, or non-overridable.
  • finally: Block used to execute code after a try-catch block, regardless of whether an exception occurs or not.
  • finalize(): Method called by the garbage collector before an object is destroyed.

22. What is the transient keyword in Java?

Answer:
The transient keyword is used to indicate that a variable should not be serialized. It is useful when you want to exclude certain fields from the serialization process.


23. What is serialization and deserialization in Java?

Answer:

  • Serialization: The process of converting an object into a byte stream to save it to a file or send it over a network.
  • Deserialization: The process of converting the byte stream back into an object.

24. What is the Cloneable interface?

Answer:
The Cloneable interface marks a class that allows its objects to be cloned. It requires the clone() method to be implemented.


25. What is the purpose of hashCode() in Java?

Answer:
The hashCode() method provides a unique identifier for an object that is used in hash-based collections like HashMap, HashSet, and Hashtable.


26. What are the different types of class loaders in Java?

Answer:
Java uses the following class loaders:

  • Bootstrap ClassLoader: Loads core Java libraries.
  • Extension ClassLoader: Loads libraries from the JDK’s extension directories.
  • System ClassLoader: Loads classes from the classpath.

27. What is Reflection in Java?

Answer:
Reflection is the ability to inspect and manipulate classes, methods, fields, and constructors at runtime. The java.lang.reflect package provides the necessary tools.


28. What is the difference between StringBuilder and StringBuffer?

Answer:

  • StringBuilder: Not synchronized (faster).
  • StringBuffer: Synchronized (thread-safe but slower).

29. What is the ThreadPoolExecutor in Java?

Answer:
ThreadPoolExecutor is an implementation of the ExecutorService that manages a pool of worker threads, optimizing resource usage and task execution.


30. What are the types of thread pools in Java?

Answer:
Java provides several types of thread pools:

  • FixedThreadPool: A pool with a fixed number of threads.
  • CachedThreadPool: A pool with a dynamic number of threads that can grow as needed.
  • SingleThreadExecutor: A pool with a single worker thread.
  • ScheduledThreadPoolExecutor: A pool for scheduling tasks with fixed-rate or fixed-delay execution.

31. What is a volatile variable in Java?

Answer:
A volatile variable ensures that changes to the variable are visible to all threads immediately, and it prevents caching by threads.


32. What is Observer and Observable in Java?

Answer:

  • Observer: An interface for objects that need to be notified of changes in another object.
  • Observable: A class that maintains a list of observers and notifies them of any changes.

33. How does Java handle exceptions?

Answer:
Java uses try, catch, throw, throws, and finally blocks for exception handling. It allows you to catch exceptions, throw custom exceptions, and perform cleanup tasks.


34. What is the difference between throw and throws in Java?

Answer:

  • throw: Used to explicitly throw an exception.
  • throws: Used in method signatures to declare that a method might throw certain exceptions.

35. What is a HashSet and how does it work in Java?

Answer:
A HashSet is a collection that implements the Set interface and uses a hash table for storage. It does not allow duplicate elements and does not guarantee any specific order of elements.


36. What is a TreeMap in Java?

Answer:
A TreeMap is a Map that implements the SortedMap interface. It stores key-value pairs in sorted order based on the natural ordering of the keys or a custom comparator.


37. What is the difference between ArrayList and LinkedList?

Answer:

  • ArrayList: Uses a dynamic array, providing fast access but slower insertions.
  • LinkedList: Uses a doubly linked list, providing faster insertions but slower access.

38. What are Stack and Queue in Java?

Answer:

  • Stack: A collection that follows Last-In-First-Out (LIFO) principle.
  • Queue: A collection that follows First-In-First-Out (FIFO) principle.

39. What is the use of java.nio package in Java?

Answer:
The java.nio package provides high-performance I/O operations, including buffer management, channels, and selectors for non-blocking I/O.


40. What is a Semaphore in Java?

Answer:
A Semaphore is a thread synchronization aid that restricts the number of threads that can access a particular resource at the same time.


41. What is the CountDownLatch in Java?

Answer:
A CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations in other threads is completed.


42. What is a CyclicBarrier in Java?

Answer:
A CyclicBarrier allows a set of threads to wait for each other to reach a common barrier point. Once all threads reach the barrier, they can proceed.

43. What is a ReentrantLock in Java?

Answer:
A ReentrantLock is a lock implementation that allows a thread to acquire the lock multiple times and supports fairness policies.


44. What is the difference between ReentrantLock and synchronized keyword?

Answer:

  • ReentrantLock: Provides more advanced locking features like try-lock, timed lock, and interruptible lock.
  • synchronized: Simple mechanism to ensure thread safety but lacks advanced features.

45. What is an Atomic class in Java?

Answer:
Atomic classes (like AtomicInteger, AtomicLong, etc.) provide thread-safe operations on variables without needing synchronization.

46. What is the ForkJoinPool in Java?

Answer:
The ForkJoinPool is a specialized implementation of the ExecutorService designed for parallel computing tasks that can be recursively divided into smaller tasks, such as divide and conquer algorithms.


47. What is the difference between Serializable and Externalizable interfaces?

Answer:

  • Serializable: A marker interface that indicates that an object can be serialized without any customization.
  • Externalizable: Extends Serializable and allows the programmer to define custom serialization logic by overriding writeExternal() and readExternal() methods.

48. What is the difference between StringBuilder and StringBuffer?

Answer:

  • StringBuilder: Not synchronized, which makes it faster for single-threaded use.
  • StringBuffer: Synchronized, making it thread-safe but slower due to the overhead of synchronization.

49. What is the ScheduledExecutorService in Java?

Answer:
ScheduledExecutorService is an interface for scheduling tasks at fixed-rate or with fixed-delay execution in a pool of threads.


50. What is the use of java.util.concurrent package?

Answer:
The java.util.concurrent package provides high-level concurrency utilities, such as thread pools, semaphores, locks, and atomic variables, for better managing multithreaded environments.


51. What is a WeakHashMap in Java?

Answer:
A WeakHashMap is a type of map where keys are stored as weak references. If a key is no longer in use (i.e., no strong references), it can be garbage collected, helping prevent memory leaks.


52. What is a LinkedHashMap?

Answer:
A LinkedHashMap is a hash table implementation of the Map interface that maintains the order of insertion of elements. It can also be configured to order entries based on their access order.


53. What is the difference between Comparable and Comparator?

Answer:

  • Comparable: Provides a single compareTo() method for natural ordering.
  • Comparator: Provides a compare() method and can be used to define multiple ways of comparing objects.

54. What is the difference between throw and throws?

Answer:

  • throw: Used to explicitly throw an exception from a method or block of code.
  • throws: Declares the exceptions a method might throw, so that the caller can handle them.

55. How does the LinkedList class work in Java?

Answer:
LinkedList is a doubly linked list implementation of the List and Deque interfaces. It allows fast insertions and deletions at both ends but slower access compared to ArrayList.


56. How does the HashMap handle collisions?

Answer:
HashMap handles collisions using chaining. When two keys have the same hash code, they are stored in a linked list or a tree structure (for large number of collisions) at that bucket index.


57. What is the purpose of join() method in Java?

Answer:
The join() method allows one thread to wait for the completion of another thread. This method is often used to ensure that the main thread waits for worker threads to finish before proceeding.


58. What is java.nio.file package?

Answer:
The java.nio.file package provides the Path API for file I/O operations, supporting modern filesystem access, including symbolic links and file attributes, along with more efficient I/O operations.


59. What is the difference between FileInputStream and BufferedReader?

Answer:

  • FileInputStream: Reads raw byte data from a file.
  • BufferedReader: Reads text data from a file with buffering, improving efficiency by reading larger chunks of data at once.

60. What is java.lang.instrument package in Java?

Answer:
The java.lang.instrument package provides tools to instrument classes at runtime. It is often used to enhance classes and methods in applications, such as bytecode manipulation and monitoring.


61. What is the Observer Design Pattern in Java?

Answer:
The Observer pattern defines a one-to-many dependency between objects so that when one object changes its state, all its dependent observers are notified and updated automatically.


62. What is Proxy Design Pattern in Java?

Answer:
The Proxy design pattern provides an object that controls access to another object. It can be used for lazy initialization, access control, logging, or performance optimization.


63. What is the Singleton Design Pattern?

Answer:
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. This is commonly used for managing shared resources.


64. What is the Factory Design Pattern?

Answer:
The Factory pattern defines an interface for creating objects but allows subclasses to alter the type of objects that will be created. It is commonly used to create instances of subclasses based on input or configuration.


65. What is the Abstract Factory Design Pattern?

Answer:
The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. It’s often used in frameworks to allow customization of object creation.


66. What is the Builder Design Pattern?

Answer:
The Builder pattern allows the creation of complex objects step by step. It isolates the construction of an object from its representation, allowing different types of objects to be created in a consistent way.


67. What is the Composite Design Pattern?

Answer:
The Composite pattern allows you to compose objects into tree-like structures to represent part-whole hierarchies. It allows clients to treat individual objects and composites uniformly.


68. What is the Decorator Design Pattern?

Answer:
The Decorator pattern allows behavior to be added to an individual object dynamically, without affecting the behavior of other objects of the same class.


69. What is the Facade Design Pattern?

Answer:
The Facade pattern provides a simplified interface to a complex subsystem, making it easier to use by hiding the complexities of the subsystem behind a simple interface.


70. What is the Command Design Pattern?

Answer:
The Command pattern encapsulates a request as an object, thereby allowing parameterization of clients with queues, requests, and operations. It decouples the sender and receiver of the request.


71. What is the State Design Pattern?

Answer:
The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class as its state changes.


72. What is the Strategy Design Pattern?

Answer:
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the algorithm to be selected at runtime.


73. What is the Iterator Design Pattern?

Answer:
The Iterator pattern provides a way to access the elements of an aggregate object sequentially, without exposing its underlying representation.


74. What is the Mediator Design Pattern?

Answer:
The Mediator pattern defines an object that controls the interaction between a group of objects, simplifying their communication by centralizing the control.


75. What is Spring Framework?

Answer:
The Spring Framework is an open-source, lightweight container framework for building Java-based enterprise applications. It provides support for dependency injection, aspect-oriented programming, transaction management, and more.


76. What is Dependency Injection in Spring?

Answer:
Dependency Injection (DI) is a design pattern used in Spring to reduce the coupling between objects by injecting dependencies at runtime, instead of having them hard-coded inside the class.


77. What is AOP (Aspect-Oriented Programming) in Spring?

Answer:
AOP is a programming paradigm that allows you to separate cross-cutting concerns (like logging, transaction management, security) from business logic. In Spring, AOP is used to define aspects that can be applied across methods or classes.


78. What is @Autowired annotation in Spring?

Answer:
@Autowired is used to automatically inject dependent beans into a class. Spring’s container can automatically resolve the dependency by type, constructor, or setter method.


79. What is @Component, @Service, @Repository, and @Controller in Spring?

Answer:

  • @Component: Marks a class as a Spring bean.
  • @Service: A specialization of @Component for service-layer beans.
  • @Repository: A specialization of @Component for DAO or persistence-layer beans.
  • @Controller: A specialization of @Component for Spring MVC controller classes.

80. What is Spring Boot?

Answer:
Spring Boot is a framework that simplifies the setup and development of Spring applications by providing default configurations, embedded servers (like Tomcat), and an easy-to-use approach to deploying microservices.


81. What is Spring Data JPA?

Answer:
Spring Data JPA is a part of the Spring Data project, which simplifies database interaction by providing an abstraction layer for data access using the Java Persistence API (JPA).


82. What is a Spring Bean?

Answer:
A Spring Bean is an object that is managed by the Spring IoC container. Beans are created, configured, and managed by Spring’s container and are used for dependency injection.


83. What is the @RequestMapping annotation in Spring MVC?

Answer:
@RequestMapping is used to map HTTP requests to handler methods in Spring MVC. It can be used on methods or classes to define the URL patterns and request types that the method handles.


84. What is the @SpringBootApplication annotation?

Answer:
The @SpringBootApplication is a convenience annotation in Spring Boot that combines @Configuration, @EnableAutoConfiguration, and @ComponentScan, simplifying the configuration of a Spring Boot application.


85. What is the purpose of application.properties file in Spring Boot?

Answer:
application.properties file in Spring Boot is used for externalizing configuration, where developers can define properties like database configurations, server ports, logging levels, etc.


86. What are Profiles in Spring?

Answer:
Spring Profiles allow you to define different configurations for different environments (e.g., development, testing, production). You can activate profiles using @Profile or via application properties.


87. What is Spring Security?

Answer:
Spring Security is a powerful and customizable authentication and access control framework. It provides comprehensive security features like authentication, authorization, CSRF protection, and more for Spring applications.


88. What is a Transaction in Spring?

Answer:
A Transaction in Spring represents a unit of work that is executed as a single operation. Spring provides declarative transaction management using @Transactional annotation for handling transactions.


89. What is JDBC Template in Spring?

Answer:
JdbcTemplate is a part of Spring JDBC module that simplifies the interaction with the database by eliminating boilerplate code for handling connections, statements, and result sets.


90. What is Spring Cloud?

Answer:
Spring Cloud is a set of tools and frameworks for building microservices-based architectures, providing solutions for configuration management, service discovery, circuit breakers, etc.


91. What is the @Transactional annotation in Spring?

Answer:
The @Transactional annotation is used to mark a method or class to indicate that Spring should handle transaction management for it. It can define rollback rules and isolation levels.


92. What is the difference between @Component and @Bean in Spring?

Answer:

  • @Component: Marks a class as a Spring-managed bean, which will be automatically registered in the Spring context.
  • @Bean: Used to explicitly define a bean through a method in a configuration class, allowing for greater control.

93. What is Spring AOP used for?

Answer:
Spring AOP is used for aspect-oriented programming, which allows cross-cutting concerns (e.g., logging, transaction management) to be applied to multiple classes without modifying their code.


94. What is Spring Boot Actuator?

Answer:
Spring Boot Actuator provides production-ready features like monitoring and management, offering built-in endpoints to check the health, metrics, and environment of your Spring Boot application.


95. What is @EnableAutoConfiguration in Spring Boot?

Answer:
@EnableAutoConfiguration tells Spring Boot to automatically configure the application based on the project’s dependencies, so you don't need to configure beans manually.


96. What is H2 Database?

Answer:
H2 is an in-memory, lightweight relational database that is often used for testing or development purposes. It can be embedded into Java applications or used as a standalone database.


97. What is Docker in the context of Java?

Answer:
Docker is a containerization platform that allows packaging Java applications and their dependencies into containers. It simplifies deployment and ensures consistent behavior across different environments.


98. How can you integrate Spring Boot with a database?

Answer:
You can integrate Spring Boot with a database by configuring DataSource, setting up JPA or JdbcTemplate, and providing connection details in application.properties or application.yml.


99. What is the @Repository annotation in Spring?

Answer:
@Repository is a specialization of @Component used to indicate that a class is a Data Access Object (DAO), which interacts with the database. It also enables exception translation for database-related exceptions.


100. What is Spring Integration?

Answer:
Spring Integration is a framework built on top of the Spring framework to provide enterprise integration patterns for connecting applications, services, and systems using message-driven architecture.


These advanced questions cover a broad spectrum of Java concepts, including multithreading, design patterns, Spring Framework, and other important Java features.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

oAuth in angular