This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.
Identity, Image, and Privacy Notice
To respect individual privacy, some names, profile photographs, avatars, biographical details, and other identifying information displayed in this guide may be replaced with pseudonyms, licensed stock images, illustrative avatars, composite images, or representative descriptions. Unless a person is expressly identified as an actual contributor, a displayed name, image, or profile should not be understood as depicting or identifying a specific candidate, interviewer, employee, or other real individual. These representations are provided for editorial and illustrative purposes only and do not imply endorsement, employment, participation, or affiliation with this guide or any company mentioned in it. Any resemblance to an actual person is coincidental.
Company Notice
This guide is an independent educational resource and is not affiliated with, endorsed by, sponsored by, or approved by the company named in this guide. Company names are used only to identify interview experiences commonly reported by candidates. Interview practices can change without notice, and inclusion of company-specific content does not mean these questions are official, complete, or guaranteed to be asked. To the fullest extent permitted by law, the author, contributors, and publisher are not responsible for outcomes related to use of this material.
Questions or comments?
Contact us for general questions, or share feedback, technical corrections, and comments with the community.
61. What are annotations in Java?Language SpecificMedium
i Question Details
Explain annotations, why they are useful, and how they are consumed at runtime or compile time.
Short Interview Answer (30-60 seconds)
Annotations are structured metadata attached to Java declarations or type uses. They do not execute business logic by themselves. A compiler, annotation processor, framework, or application reads them and decides what action to take. For example, @Override lets the compiler verify method overriding, while a framework may inspect a runtime annotation through reflection. The practical decision is to choose a target that permits the intended location and a retention policy that keeps the annotation for as long as its consumer needs it.
Detailed Explanation
Annotations are labels that add structured information to Java code. They can describe classes, methods, fields, parameters, constructors, packages, modules, or uses of a type. The label itself normally performs no action. Java, a build tool, a library, or application code must recognize it and decide what it means. This allows useful information to stay close to the code it describes. Annotations can support compiler checks, generated files, testing, validation, configuration, and decisions made while an application is running.
Useful Questions to Ask the Interviewer
Must the annotation be available only during compilation or also while the application runs?
Which declarations or type locations may use it?
Which compiler, processor, framework, or application component will consume it?
How to Explain It in an Interview
An annotation starts with the @ symbol. Standard examples include @Override, @Deprecated, and @SuppressWarnings. A custom annotation interface is declared with @interface. Its elements define the values that users may supply. These values are limited to primitive values, String, Class, enum constants, annotation values, and arrays of those types. Annotation values cannot be null.
@Target controls where an annotation may appear. For example, it can permit methods, fields, parameters, declarations, or type uses. If @Target is absent, the annotation can be used in every declaration context except type parameter declarations, and it cannot be used in type contexts.
@Retention controls how long the annotation is retained. SOURCE means it is discarded during compilation. CLASS means it is stored in the class file but is not required to be available through reflection. RUNTIME means runtime reflection can expose it. CLASS is the default when @Retention is absent.
Compile time annotation processors can inspect source level program elements, report errors, and generate source files, class files, or resources. Runtime consumers usually inspect RUNTIME annotations through reflection. Reflection and repeated scanning add work, so production frameworks commonly inspect annotations during startup or first use and cache the derived metadata.
@Inherited has a narrow rule. It affects runtime lookup on classes only. It searches superclasses, not interfaces, methods, fields, or other members. Repeatable annotations use @Repeatable and a compatible container annotation.
Why Interviewers Ask This
Interviewers ask this question to check whether the candidate understands how Java attaches structured metadata to program elements and how compilers, tools, frameworks, and application code consume it. They also evaluate knowledge of annotation targets, retention policies, reflection, annotation processing, inheritance rules, and production costs.
Common interview mistakes
Common mistakes include saying annotations execute code automatically, assuming every annotation is visible through runtime reflection, forgetting that CLASS is the default retention, using an incompatible target, and expecting @Inherited to copy annotations onto methods, fields, interfaces, or subclasses. @Inherited only affects certain reflective class lookups through the superclass chain. Other mistakes include assuming annotation values may be null, confusing annotation processing with runtime reflection, repeatedly scanning annotations on frequently executed paths, and hiding important business behavior behind annotation consumers that are difficult to discover or test.
Interview tip
Begin by saying that annotations are metadata and need a consumer. Then explain @Target and @Retention, give @Override as a compiler example, and give runtime reflection as a framework example. Mention the default CLASS retention and the narrow behavior of @Inherited to show deeper understanding.
Interviewer may ask next
Can every annotation be read through reflection at runtime, and are annotations inherited by subclasses?
No. Normal runtime reflection can expose an annotation only when its retention policy is RUNTIME. SOURCE annotations are discarded during compilation. CLASS annotations remain in the class file but are not required to be exposed through reflection. Inheritance is also limited. An annotation marked with @Inherited may be found through reflective lookup on a subclass when it is present on a superclass. This rule applies only to class annotations and does not search interfaces or inherit annotations on methods, fields, constructors, or parameters.
What is the tradeoff between compile time annotation processing and runtime reflection?
Compile time processing moves validation and generation into the build, while runtime reflection allows decisions to be made from annotations while the application is running. Compile time processing can catch problems earlier and reduce runtime discovery work, but it adds build configuration and generated output that developers must understand. Runtime reflection is flexible and useful for framework configuration, but repeated scanning adds execution and allocation costs. Production code commonly performs runtime discovery during startup or first use and caches the derived metadata.
62. What is reflection in Java?Language SpecificMedium
i Question Details
Explain Java reflection, what it enables, and the tradeoffs around safety and performance.
Short Interview Answer (30-60 seconds)
Reflection lets Java code inspect classes, constructors, methods, fields, and annotations while the program is running. It can also create objects, call methods, and access fields dynamically. It is useful when a framework or tool does not know the exact type at compile time. I prefer normal Java calls when the type is known because they are safer, clearer, easier to refactor, and usually faster.
Detailed Explanation
Reflection lets a running Java program examine the structure of a type and use parts of that type without selecting them directly in the original code. For example, a tool can discover available operations, read labels attached to a type, create an object, or call an operation chosen from a name. This flexibility helps general purpose tools work with many different types. The cost is that some mistakes are found only while the program is running. Access rules, missing names, wrong inputs, and failures inside called code must therefore be handled carefully.
Useful Questions to Ask the Interviewer
Does the application need to discover types or members at runtime?
Are public members enough, or must nonpublic members be accessed?
Is the application using named Java modules?
How to Explain It in an Interview
Java reflection is mainly provided by Class and the types in java.lang.reflect. A Class object represents a loaded Java type. Code can obtain one from a class literal such as User.class, from an object through getClass, or from a name through Class.forName. Class.forName normally loads and initializes the named class, so initialization side effects must be considered.
The Class object can expose constructors, methods, fields, modifiers, interfaces, and annotations. Methods beginning with getDeclared inspect members declared directly by that type. Methods such as getMethods return public methods and can include inherited methods. The order returned by reflection APIs should not be treated as stable unless the API explicitly promises an order.
Code can create an object with Constructor.newInstance, call a method with Method.invoke, and read or write a field with Field.get and Field.set. The compiler cannot fully verify member names, parameter matching, casts, or access permissions. Missing members can cause NoSuchMethodException or NoSuchFieldException. A method called through Method.invoke can throw InvocationTargetException, which contains the exception thrown by the target method.
Access rules still apply. Calling setAccessible does not guarantee access. With named modules, the target package may need to be open to the caller. Otherwise Java can throw InaccessibleObjectException. Strong encapsulation also limits reflective access to JDK internals.
Reflection is appropriate for frameworks, test tools, object mapping, dependency injection, annotation based configuration, and plugin discovery. It should not replace a direct call when the target type is already known. Reflection does not copy the inspected object. Memory cost mainly comes from retained metadata references, cached reflective objects, argument arrays, boxing, and objects created by the invoked code. Repeated lookup and invocation can cost more than direct access, so production frameworks often validate and cache discovered members.
Why Interviewers Ask This
Interviewers ask this question to check whether a candidate understands runtime type inspection, dynamic invocation, Java access rules, module boundaries, exception handling, and the production tradeoffs of replacing normal compiler checked calls with reflection.
Common interview mistakes
Common mistakes include saying that reflection ignores Java access control, assuming setAccessible always succeeds, using the deprecated Class.newInstance method instead of Constructor.newInstance, forgetting that Method.invoke wraps a target exception in InvocationTargetException, confusing declared members with inherited public members, depending on an unspecified member order, expecting generic type arguments to be fully available despite type erasure, repeatedly performing lookups in frequently executed code, retaining unbounded metadata caches, and using reflection when an interface or direct method call would be simpler.
Interview tip
Start with the practical conclusion that reflection provides runtime flexibility but should be used only when normal compile time calls are not enough. Then explain Class, inspection, dynamic invocation, access and module limits, exceptions, performance cost, memory considerations, and one realistic framework use case.
Interviewer may ask next
Can reflection always access a private field or method in modern Java?
No. Calling setAccessible only requests that normal language access checks be suppressed. The request can still fail when a named module does not open the target package to the caller, and reflective access to protected JDK internals is strongly restricted. Java can throw InaccessibleObjectException in these cases. This matters because code that depends on private implementation details can fail after module configuration or runtime changes and is harder to maintain.
What performance and memory costs should be considered when reflection is used in production?
Reflection generally costs more than direct access because member discovery, access checks, argument handling, boxing, dynamic invocation, and exception wrapping may add work and can reduce optimization opportunities. Reflection itself does not copy the target object. Memory cost can come from cached Class, Method, Field, and Constructor references, temporary argument arrays, boxed values, and objects created by the invoked operation. Caching validated lookups can reduce repeated discovery cost, but an unbounded cache can retain classes and their class loaders, so cache lifetime must be controlled.
63. What is Apache Maven?NEWLanguage SpecificEasy
i Question Details
Define Maven as a Java project build and dependency-management tool. Explain the purpose of pom.xml, artifact coordinates, repositories, dependencies, plugins, the standard project layout, and the main lifecycle phases from compile and test through package, install, and deploy. Distinguish Maven from the JDK and from an application framework.
Short Interview Answer (30-60 seconds)
Apache Maven is a build and dependency management tool commonly used for Java projects. It reads project settings from pom.xml, downloads required libraries from repositories, runs build plugins, and follows a standard lifecycle such as compile, test, package, install, and deploy. Maven is not the JDK because it does not provide the Java compiler or runtime itself. It is also not an application framework. It organizes and automates the work needed to build and manage a project.
Detailed Explanation
Maven helps a Java project follow the same build process every time. A project describes what it needs in a file called pom.xml. Maven can then get required libraries, compile the program, run tests, create the final file, and make that file available for other projects. It also encourages a common folder structure, so developers can understand unfamiliar projects more easily. Maven does not replace Java itself. Java still needs the JDK to compile and run code. Maven also does not provide application features such as web handling or database access.
Useful Questions to Ask the Interviewer
Would you like me to explain the Maven lifecycle as well as dependency management?
Should I also compare Maven with the JDK and application frameworks?
How to Explain It in an Interview
Apache Maven is mainly a project build and dependency management tool. Its central project file is pom.xml, which stands for Project Object Model. This file describes the project, its dependencies, plugins, and other build settings.
A Maven artifact is identified by coordinates. The core coordinates are groupId, artifactId, and version. groupId usually identifies an organization or project group. artifactId identifies a particular library or project. version identifies a specific release. Some dependency declarations can also use details such as type or classifier when needed.
Dependencies are external libraries that the project needs. Maven first checks whether the required artifact is available in the local repository. If it is not available there, Maven can download it from configured remote repositories. Maven Central is a common public repository. Companies can also use private repositories. The local repository lets later builds reuse downloaded artifacts.
Plugins perform build work. For example, one plugin can compile Java source and another can run tests. Maven connects plugin goals to lifecycle phases.
A standard Maven project normally keeps application source in src/main/java, application resources in src/main/resources, test source in src/test/java, and test resources in src/test/resources. This convention reduces custom setup.
The main build lifecycle contains ordered phases. compile compiles the main source. test reaches the test phase after earlier phases have prepared and compiled the needed test code, then runs tests. package creates an artifact such as a JAR or WAR. install copies the built artifact into the local Maven repository. deploy publishes the artifact to a configured remote repository. When a later lifecycle phase is requested, Maven runs the earlier phases in that lifecycle first.
Maven still relies on the JDK for Java tools such as the compiler. Maven is also different from frameworks such as Spring because Maven manages the project build, while a framework provides APIs and application behavior.
Why Interviewers Ask This
Interviewers ask this to check whether a Java developer understands how real Java projects are built, how external libraries are managed, and how Maven gives a project a repeatable build process. They also want to see whether the candidate can separate Maven from the JDK and from application frameworks.
Common interview mistakes
A common mistake is saying that Maven is part of the Java language or that it replaces the JDK. Maven relies on JDK tools to perform Java compilation. Another mistake is calling Maven an application framework. It does not provide application features in the way a framework does. Developers also sometimes confuse dependencies with plugins. Dependencies are libraries used by the project, while plugins perform build tasks. Another mistake is thinking that install publishes an artifact to a shared server. install places it in the local Maven repository, while deploy normally publishes it to a configured remote repository.
Interview tip
Start by saying that Maven manages builds and dependencies. Then explain pom.xml, artifact coordinates, repositories, dependencies, plugins, and the standard project layout. Finish by walking through compile, test, package, install, and deploy, and clearly state that Maven is different from both the JDK and an application framework.
Interviewer may ask next
What happens when Maven cannot find a required dependency in the configured repositories?
The build normally fails because Maven cannot resolve the required artifact. Maven uses coordinates such as groupId, artifactId, and version to identify the dependency. It can reuse an artifact already available in the local repository. Otherwise it tries the configured remote repositories. If the artifact still cannot be resolved, Maven cannot complete the build. This matters because repeatable builds depend on required artifacts and repository settings being available and correct.
Why would a team use Maven instead of running javac and other JDK tools manually?
Maven provides a repeatable project build process around the JDK tools. It manages dependencies, standard project locations, plugins, tests, packaging, and artifact publication through one project model and lifecycle. Running javac manually can compile Java source, but the team would need separate commands or scripts for the rest of the build. Maven adds structure and automation. The main tradeoff is that developers must understand Maven configuration, lifecycle phases, dependency resolution, and plugin settings.
64. What is the Spring Framework?NEWLanguage SpecificEasy
i Question Details
Define Spring Framework as a Java application framework whose core container manages application objects and their dependencies. Explain beans, ApplicationContext, dependency injection, configuration, and the major facilities commonly used for web applications, data access, transactions, testing, and integration. Distinguish Spring Framework from Spring Boot.
Short Interview Answer (30-60 seconds)
Spring Framework is a Java application framework that helps me build applications from separate, loosely connected objects. Its core container creates and manages application objects called beans and supplies their dependencies through dependency injection. ApplicationContext is the main Spring container interface commonly used by applications. Spring also provides facilities for web applications, data access, transactions, testing, and integration. Spring Boot is different because it builds on Spring Framework and adds easier setup, auto configuration, starter dependencies, and common production features.
Detailed Explanation
Spring Framework helps developers organize a Java application so its parts are easier to create, connect, test, and change. Instead of each object creating every other object it needs, Spring can create those objects and connect them. This reduces direct coupling between parts of the application. Spring also provides common support for building web applications, working with databases, controlling groups of database changes, testing application components, and connecting systems. Spring Boot is related, but it builds on Spring Framework and makes application setup easier by providing useful defaults and automatic configuration.
Useful Questions to Ask the Interviewer
Would you like me to focus mainly on the Spring container and dependency injection, or also cover the major Spring facilities?
Would you like me to explain the difference between Spring Framework and Spring Boot in more detail?
How to Explain It in an Interview
Spring Framework is a Java application framework. Its central feature is a container that creates and manages application objects. Spring calls these managed objects beans.
ApplicationContext is the main container interface commonly used in Spring applications. It holds information about configured beans, creates them when required, resolves their dependencies, and manages important lifecycle behavior.
Dependency injection means an object receives the other objects it needs instead of creating those objects itself. For example, an OrderService may need a PaymentService. Spring can create both beans and provide the PaymentService to the OrderService. Constructor injection is commonly preferred for required dependencies because the dependencies are explicit and the class is easier to test.
Spring learns what to create from configuration. Modern Spring applications commonly use Java configuration and annotations. A developer can define beans explicitly with configuration methods or allow Spring to discover suitable components through component scanning.
Spring Framework also provides major facilities used by production Java applications. Spring MVC supports traditional web applications and HTTP APIs. Spring WebFlux supports reactive web applications. Spring JDBC and related data access support simplify database access. Spring transaction management provides a consistent abstraction for transaction boundaries. Spring Test provides support for testing Spring managed components and application contexts. Spring also provides integration support for messaging and communication between application components and external systems.
Spring Boot is not a replacement for Spring Framework. Spring Boot uses Spring Framework underneath. It adds auto configuration, starter dependencies, common defaults, embedded server support, and production focused features. Spring Framework provides the core container and application facilities. Spring Boot makes those facilities easier to configure and run.
Why Interviewers Ask This
Interviewers ask this question to check whether a Java developer understands the role of Spring in real applications. They want to see whether the candidate understands the Spring container, beans, dependency injection, configuration, and common Spring facilities for web applications, data access, transactions, testing, and integration. They also want the candidate to clearly distinguish Spring Framework from Spring Boot.
Common interview mistakes
A common mistake is saying that Spring Framework and Spring Boot are the same thing. Spring Boot uses Spring Framework but adds easier setup, conventions, and automatic configuration. Another mistake is describing Spring only as a web framework. Its core container manages application objects and dependencies, while other Spring facilities support web development, data access, transactions, testing, and integration. Another mistake is thinking dependency injection removes dependencies. The dependencies still exist. The difference is that they are supplied to the object instead of being created inside that object. It is also incorrect to assume every Spring bean is created immediately. Bean creation timing depends on bean scope, configuration, and whether lazy initialization is used.
Interview tip
Start by saying that Spring Framework is a Java application framework whose container manages beans and their dependencies. Then explain ApplicationContext and dependency injection with one small example. Next, mention the main facilities for web applications, data access, transactions, testing, and integration. Finish by saying that Spring Boot builds on Spring Framework and mainly makes configuration, dependency setup, and application startup easier.
Interviewer may ask next
What happens if Spring cannot find a required dependency for a bean?
Spring normally fails to create the affected bean when a required dependency cannot be resolved. If that bean must be created while the ApplicationContext is starting, application context initialization normally fails. For example, if an OrderService constructor requires a PaymentService and no matching bean is available, Spring cannot satisfy that constructor dependency. This matters because many dependency configuration errors are detected during startup. If multiple matching beans exist and Spring cannot choose one, dependency resolution can also fail unless the configuration provides enough information to select the intended bean.
When would you use Spring Framework without Spring Boot?
I would use Spring Framework without Spring Boot when I need to integrate Spring into an environment whose startup, deployment, or configuration is already managed in another way, or when I want explicit control over that setup. Spring Boot is usually more convenient for new standalone services because it adds auto configuration, starter dependencies, common defaults, embedded server support, and production features. The tradeoff is convenience versus explicit setup. Both approaches still use Spring Framework for the core container and Spring facilities.
65. What is dependency injection in Spring?NEWLanguage SpecificEasy
i Question Details
Define dependency injection as providing an object with the collaborators it needs instead of making the object construct or locate them itself. Explain how the Spring container creates beans and resolves their dependencies, show constructor injection as the normal choice for required dependencies, mention setter injection for optional dependencies, and explain the effects on coupling and testing.
Short Interview Answer (30-60 seconds)
Dependency injection in Spring means an object receives the other objects it needs instead of creating or finding them itself. Spring creates managed objects called beans and supplies their dependencies. I normally use constructor injection for required dependencies because the object receives everything it needs when it is created. It also makes testing simple because a test can pass a test object or mock directly. Setter injection is useful when a dependency is truly optional. This reduces coupling to object creation and makes classes easier to test.
Detailed Explanation
The practical idea is simple. A class should focus on its own job instead of building every helper object it needs. In a Spring application, Spring can create those objects and connect them together. For example, an order service may need a payment service. Instead of the order service creating the payment service itself, Spring gives it one. This makes the parts easier to replace and test. Required helpers are usually given when the object is created. Optional helpers can be supplied later when that behavior is truly optional.
Useful Questions to Ask the Interviewer
Would you like me to compare constructor injection and setter injection?
Should I also explain how Spring finds and creates the required beans?
How to Explain It in an Interview
Dependency injection means a class receives its collaborators from outside rather than constructing or locating them itself. A collaborator is another object that the class needs to do its work.
In Spring, the application context acts as the container. It creates and manages objects called beans. When Spring creates a bean, it resolves the dependencies required by that bean from the application context and supplies them during creation or configuration.
Constructor injection is normally the best choice for required dependencies. For example, if OrderService cannot work without PaymentService, OrderService can declare a constructor that accepts PaymentService. Spring resolves a suitable PaymentService bean and passes it when creating OrderService. The requirement is clear from the constructor. The field can also be final when appropriate, so the reference does not change after construction.
Setter injection is more suitable when a dependency is genuinely optional. Spring can create the object first and then supply that dependency through a setter. A required dependency should usually not rely on setter injection because the object can exist before that required collaborator has been supplied.
Dependency injection reduces coupling to object creation. OrderService depends on a collaborator instead of containing the logic for constructing or locating that collaborator. Testing is simpler because a test can create OrderService directly and pass a controlled implementation or mock through its constructor.
Spring still needs an unambiguous bean configuration. If no suitable bean exists, dependency resolution can fail. If several beans are valid candidates and Spring cannot determine which one to use, resolution can also fail while the application context is being created. In production code, required dependencies should therefore be explicit and bean selection should be clear.
Why Interviewers Ask This
Interviewers ask this to check whether a Java developer understands how Spring connects application objects, how required and optional collaborators should be supplied, and how that choice affects coupling and testing. They also want to see whether the candidate understands the role of the Spring container and can choose constructor injection or setter injection appropriately.
Common interview mistakes
A common mistake is creating a dependency inside the class with new even though Spring is intended to manage that dependency. This couples the class to a particular construction choice and makes substitution in tests harder. Another mistake is using setter injection for something that is actually required, which allows the object to exist before that dependency is supplied. Developers may also assume that Spring can always choose a matching bean automatically. Resolution can fail when no suitable bean exists or when several suitable beans exist and Spring cannot determine which one should be injected. Another mistake is thinking dependency injection belongs only to Spring. Dependency injection is a general design pattern, while Spring provides a container that implements it.
Interview tip
Start with the main idea that the object receives its collaborators instead of creating them. Then explain that Spring creates beans and resolves their dependencies. State that constructor injection is the normal choice for required dependencies and setter injection is mainly for optional dependencies. Finish by connecting the design to lower coupling and easier testing.
Interviewer may ask next
What happens if Spring finds more than one bean that can satisfy a required dependency?
Spring must be able to select one candidate unambiguously. If several beans match and Spring has no rule or configuration that identifies the intended bean, dependency resolution fails while the application context is being created. This matters because a required constructor dependency must be resolved before the bean can be created. The ambiguity can be removed with clear bean selection, such as marking a preferred candidate or identifying the intended bean with a qualifier.
Why is constructor injection usually preferred over setter injection for required dependencies?
Constructor injection is usually preferred because every required dependency must be supplied when the object is created. This makes the requirement explicit and allows the reference to be final when appropriate. It also makes direct unit testing simple because the test passes the required collaborator to the constructor. Setter injection allows construction before the dependency is supplied, so it is a better fit for a genuinely optional dependency. The tradeoff is that constructor injection can make a class with too many dependencies visibly awkward, which is useful because it can reveal that the class has too many responsibilities.
66. What is Spring Boot?NEWLanguage SpecificEasy
i Question Details
Define Spring Boot as a way to create and run Spring applications with opinionated defaults and less manual setup. Explain starters, auto-configuration, external configuration, embedded servers, executable application packaging, and production features. Distinguish Spring Boot from the underlying Spring Framework and state that defaults can be overridden.
Short Interview Answer (30-60 seconds)
Spring Boot is a way to create and run Spring applications with useful defaults and less manual setup. It provides starters for common dependencies, automatic configuration based on what the application contains, external configuration, and embedded servers such as Tomcat. A Spring Boot application can commonly be packaged as an executable JAR and run directly with Java. It also provides production support through features such as Spring Boot Actuator. Spring Boot uses the Spring Framework underneath, and its defaults can be changed when the application needs different behavior.
Detailed Explanation
Spring Boot helps developers create and run Java applications with less setup work. Instead of connecting many common parts by hand, it chooses sensible starting settings for you. It can also start the web server as part of the application, so you often do not need to install a separate server. Settings can come from files, environment values, or values given when the program starts. The finished application can commonly be placed in one file and started directly. You can still change the default choices whenever your application needs something different.
Useful Questions to Ask the Interviewer
Would you like me to explain how automatic configuration decides what to create?
Would you like me to compare Spring Boot with the Spring Framework?
How to Explain It in an Interview
Spring Boot is built on top of the Spring Framework. The Spring Framework provides core features such as dependency injection, web support, data access, and transaction support. Spring Boot makes common Spring applications easier to configure, package, and run.
A starter is a dependency definition that brings together libraries commonly needed for one purpose. For example, a web starter adds the main dependencies normally needed for a Spring web application. This reduces the amount of dependency setup that developers must do manually.
Automatic configuration examines information such as the classes available to the application, Spring objects that already exist, and configuration properties. It then creates suitable Spring configuration when its conditions match. This behavior is conditional. If the application supplies its own configuration, Spring Boot can often step back and use the application choice instead.
Spring Boot also supports external configuration. Settings can come from application property files, environment variables, command line arguments, and other supported property sources. This lets the same packaged application use different settings in development, testing, and production.
For a web application, Spring Boot can include an embedded server such as Tomcat. The application starts that server as part of its own startup process. A Spring Boot application is commonly packaged as an executable JAR and started with the Java runtime.
For production use, Spring Boot Actuator can provide operational information such as application health and information when those features are enabled and exposed. Access to sensitive operational endpoints should be controlled.
The key point is that Spring Boot does not replace the Spring Framework. It adds conventions, automatic setup, packaging support, external configuration, and production features around Spring. Its defaults save work, but developers can override them when requirements differ.
Why Interviewers Ask This
Interviewers ask this question to check whether the candidate understands how Spring Boot simplifies the creation and operation of Spring applications. They want to see whether the candidate can explain starters, automatic configuration, external configuration, embedded servers, executable packaging, and production features. They also check whether the candidate understands that Spring Boot uses the Spring Framework underneath and that its defaults can be changed.
Common interview mistakes
A common mistake is saying that Spring Boot replaces the Spring Framework. It does not. Spring Boot uses Spring underneath. Another mistake is saying that automatic configuration cannot be changed. Developers can provide their own configuration, change properties, or exclude specific automatic configuration when needed. Candidates also sometimes confuse starters with automatic configuration. Starters mainly help bring related dependencies into the application, while automatic configuration creates Spring configuration when its conditions match. Another mistake is assuming every Spring Boot application must be a web application or must use Tomcat. Spring Boot also supports applications without a web server, and supported server choices can be changed. Production features such as Actuator endpoints also need careful configuration and access control.
Interview tip
Start by saying that Spring Boot makes Spring applications easier to create and run by providing useful defaults and reducing manual setup. Then explain starters, automatic configuration, external configuration, embedded servers, executable JAR packaging, and production features. Finish by stating that Spring Boot uses the Spring Framework underneath and that its defaults can be overridden.
Interviewer may ask next
What happens if Spring Boot automatic configuration creates something that the application does not want?
The developer can change or replace that default behavior. Spring Boot automatic configuration is conditional. It creates configuration only when its conditions are satisfied. Many automatic configurations allow an application supplied Spring object or property to take precedence, and specific automatic configuration can also be excluded when necessary. This matters because Spring Boot can provide convenient defaults without forcing every application to use exactly the same setup.
What is the tradeoff between using Spring Boot defaults and configuring Spring manually?
Spring Boot defaults reduce setup work and make common Spring applications easier to build, package, and run. The tradeoff is that developers still need to understand what Spring Boot is configuring so they can change it safely when requirements differ. More manual Spring configuration gives explicit control but usually requires more setup and maintenance. In production, a practical approach is to use Spring Boot defaults where they fit and override only the parts that need different behavior.
67. What is garbage collection in Java?NEWLanguage SpecificEasy
i Question Details
Define garbage collection as JVM-managed reclamation of memory for objects that are no longer reachable. Explain heap allocation, reachability, GC roots, collection pauses, why collectors use different strategies, and why garbage collection does not prevent memory leaks caused by unwanted retained references or guarantee immediate cleanup of external resources.
Short Interview Answer (30-60 seconds)
Garbage collection is the JVM process that automatically reclaims heap memory from objects that are no longer reachable by the application. The JVM starts from important active references called GC roots and follows references to find objects that are still reachable. Different collectors use different strategies to balance pause time, throughput, CPU use, and memory use. Garbage collection helps manage memory, but it does not prevent leaks caused by unwanted retained references, and it does not guarantee immediate cleanup of files, sockets, or database connections.
Detailed Explanation
Java automatically frees memory that the program can no longer reach. This means developers usually do not have to manually release the memory for every object they create. While a Java program runs, it creates many objects and keeps references to the ones it still needs. When an object can no longer be reached through any active reference path, its memory may later be reused. This makes memory management easier, but it does not remove every memory problem. Programs can still keep unnecessary objects for too long, and resources such as open files still need explicit cleanup.
Useful Questions to Ask the Interviewer
Would you like me to explain how the JVM decides that an object can be collected?
Would you like me to discuss collection pauses and the tradeoffs between different garbage collectors?
How to Explain It in an Interview
Garbage collection is automatic memory reclamation performed by the JVM. Most Java objects are allocated in an area of JVM memory called the heap. As the application runs, some objects remain reachable and some eventually become unreachable.
The JVM determines reachability by starting from GC roots. GC roots are references that the JVM treats as starting points for finding live objects. Examples include references held by executing thread stacks and certain JVM maintained references. The collector follows references from these roots. If an object cannot be reached through this process, it becomes eligible for garbage collection.
Eligible does not mean that the object is removed immediately. The JVM decides when collection work should happen. Some parts of garbage collection can require application threads to pause. Different collectors use different strategies because applications have different goals. Some applications value high throughput. Others value shorter and more predictable pauses. These choices can also affect CPU use and memory use.
Garbage collection does not prevent every memory leak. If an application accidentally keeps a reference to an object that it no longer needs, that object remains reachable. The collector cannot know that the application no longer wants it, so its memory cannot be reclaimed. This is a common form of memory leak in Java.
Garbage collection also does not guarantee immediate cleanup of external resources. Files, sockets, database connections, and similar resources should be closed explicitly. In Java, try with resources is normally the correct choice for resources that implement AutoCloseable.
Why Interviewers Ask This
Interviewers ask this question to check whether the candidate understands how the JVM manages object memory at runtime. They also want to see whether the candidate understands reachability, collection pauses, memory retention, collector tradeoffs, and the important difference between automatic memory reclamation and explicit cleanup of external resources.
Common interview mistakes
A common mistake is saying that garbage collection removes an object immediately when the application stops using it. An object must first become unreachable, and the JVM still decides when collection happens. Another mistake is thinking that garbage collection prevents all memory leaks. An unwanted reference can keep an unnecessary object reachable and prevent its memory from being reclaimed. Developers also sometimes rely on garbage collection to close files, sockets, or database connections. Those resources should be closed explicitly, usually with try with resources when they implement AutoCloseable. Another mistake is assuming that all collectors behave the same. Different collectors make different tradeoffs involving pause time, throughput, CPU use, and memory use.
Interview tip
Start by saying that the JVM automatically reclaims heap memory from unreachable objects. Then explain reachability from GC roots and mention that collection can cause pauses. Finish with the two important limits: retained references can still cause memory leaks, and external resources need explicit cleanup.
Interviewer may ask next
Can an object that the application no longer needs still avoid garbage collection?
Yes. An object remains in memory if it is still reachable from a GC root, even when the application logically no longer needs it. This matters because the garbage collector judges reachability, not developer intent. An unnecessary reference stored in a collection, cache, static field, listener, or another reachable object can therefore retain memory. The tradeoff is that keeping references is often necessary for useful state or caching, but references that live longer than needed can increase memory use and eventually create memory pressure.
Why would a production Java application choose one garbage collector instead of another?
The choice depends on the application's performance goals. Different JVM garbage collectors use different strategies to balance pause time, throughput, CPU use, and memory use. This matters because a service that needs short response pauses may prefer different behavior from a batch application that mainly wants high overall throughput. The tradeoff is that improving one goal can require more CPU, more memory, or different collection behavior, so the collector should match the workload and production requirements.
68. What are GC roots and how do memory leaks happen in Java?Language SpecificHard
i Question Details
Explain GC roots, object reachability, and how long-lived references can create memory leaks.
Short Interview Answer (30-60 seconds)
GC roots are the starting points that the JVM treats as live, such as references from active thread stacks, loaded system classes, JNI global references, and other JVM managed structures. The collector traces references from those roots and keeps every reachable object. A Java memory leak happens when an object is no longer useful to the application but is still reachable through a long lived reference. Common causes include unbounded caches, static collections, listeners that are never removed, ThreadLocal values on pooled threads, growing queues, and retained class loaders.
Detailed Explanation
Java automatically reclaims objects that the running program can no longer reach. It does not reclaim an object merely because the business task has finished using it. A leak occurs when an unwanted object remains connected to something that stays alive. The JVM therefore must preserve that object because it may still be used. As more unwanted objects remain connected, the application may use more heap, spend more time collecting garbage, slow down, and eventually fail when it cannot allocate more memory.
Useful Questions to Ask the Interviewer
Should I explain the main categories of GC roots?
Should I include examples from a long running server application?
Should I explain how a heap dump reveals the retaining reference?
How to Explain It in an Interview
The practical rule is that the garbage collector can reclaim an object only when no GC root can reach it.
A GC root is a starting point used during reachability analysis. Typical root categories include system classes, JNI global references, references from active platform thread stacks, monitors, and other JVM managed structures. Application code often experiences static fields as long lived entry points because a loaded class can keep its static field values reachable.
The collector starts from the roots and follows references through the object graph. Objects reached by this traversal are strongly reachable and must remain alive. Objects that are not reached may be reclaimed. A cycle is not automatically a leak. Two objects can reference each other and still be collected when no root can reach either object.
A memory leak occurs when an object is no longer useful but a reachable reference chain still retains it. For example, suppose a static map stores request data and never removes entries. The loaded class keeps the static field reachable. The field reaches the map, and the map reaches its keys and values. The collector is working correctly, but it cannot infer that those entries have no business value.
Other common causes include caches without size or expiration limits, listeners that are never unregistered, ThreadLocal values left on pooled threads, queues that grow without a bound, JNI global references that are not released, and old class loaders retained after redeployment.
Weak references can help with specific ownership rules, but they are not a general leak fix. A production cache usually needs explicit size limits, expiration, and monitoring. Code that sets a ThreadLocal on a pooled thread should normally remove it in a finally block.
To investigate a leak, confirm that the live heap keeps growing after meaningful collection cycles. Then capture and compare heap dumps. Inspect retained size, dominator relationships, and the path from suspicious objects to GC roots. That path identifies the collection, thread, native reference, listener, or class loader that must be released or bounded.
Why Interviewers Ask This
Interviewers ask this question to check whether a candidate understands how the JVM decides which objects must stay alive. It also tests whether the candidate can separate automatic garbage collection from leak prevention, reason about long lived reference chains, recognize common retention patterns, and use heap evidence to find the reference that prevents collection.
Common interview mistakes
A common mistake is saying that Java cannot leak memory because it has garbage collection. Garbage collection reclaims unreachable objects, not reachable objects that the application no longer needs. Another mistake is blaming reference cycles. A cycle is collectible when no GC root reaches it. Developers also cause retention by using static collections or caches without bounds, forgetting to unregister listeners, leaving ThreadLocal values on pooled threads, allowing queues to grow without limits, failing to release JNI global references, or retaining obsolete class loaders. Calling System.gc only requests collection. It does not break a retaining reference and does not guarantee that any particular object will be reclaimed.
Interview tip
Start with the reachability rule. Explain that the collector keeps every object reachable from a GC root. Then define a leak as an unwanted long lived reference, give one clear example such as an unbounded static map, mention that cycles alone are collectible, and finish with heap dump analysis and the path to the retaining root.
Interviewer may ask next
Can two objects that reference each other still be garbage collected?
Yes. A reference cycle does not keep objects alive by itself. Both objects may be collected when no path from any GC root reaches either object. Java collectors use graph reachability rather than relying only on reference counts. This matters because the correct investigation is to find a path to a root, not merely to find a cycle.
How would you investigate a suspected Java memory leak in production?
I would first verify that the live object set keeps growing after meaningful collection cycles instead of looking only at temporary allocation spikes. I would then capture one or more heap dumps and inspect retained size, dominators, and paths to GC roots. The exact behavior being investigated is unwanted retention through a live reference chain. A small map, thread, listener registry, JNI reference, or class loader may retain a much larger graph. Heap dump creation can pause the process and use substantial disk and input output capacity, so it must be planned carefully on a busy service.
69. Explain the Java Memory Model and happens-before.Language SpecificHard
i Question Details
Explain the Java Memory Model, visibility, ordering, and the happens-before relationship.
Short Interview Answer (30-60 seconds)
The practical rule is that one thread should not rely on another thread's writes unless Java establishes a happens before relationship between their actions. The Java Memory Model defines the visibility, ordering, and atomicity guarantees for shared memory. Happens before can come from rules such as program order, monitor unlock and lock, volatile write and read, thread start, and thread join. Without the required relationship, conflicting accesses can form a data race, so a thread may legally observe an older value or an unexpected ordering of writes.
When several parts of a Java program run at the same time, they may read and change the same shared information. A change made by one part is not always guaranteed to be seen immediately by another part. The computer and Java runtime may also perform internal work in a different order, as long as one part alone cannot notice a difference. Java therefore defines rules that tell programmers when a change must be visible and when one action must be treated as occurring before another action.
Useful Questions to Ask the Interviewer
Should I cover atomicity and data races as well as visibility and ordering?
Would you like examples using synchronized and volatile?
Should I explain safe publication and final fields?
How to Explain It in an Interview
The Java Memory Model defines the rules for communication through memory between Java threads. Its main concerns are visibility, ordering, and atomicity.
Visibility asks whether one thread is guaranteed to see a write performed by another thread. Ordering asks which actions must appear in a defined sequence. Atomicity asks whether an operation can be observed as one indivisible action.
A happens before relationship is a formal guarantee. If action A happens before action B, the effects of A are visible to B, and A is ordered before B. It does not necessarily mean that A occurred earlier according to wall clock time.
Within one thread, an earlier action happens before a later action according to program order. Releasing a monitor happens before another thread later acquires the same monitor. A write to a volatile field happens before every later read of that field in the synchronization order. Calling Thread.start happens before actions in the started thread. Every action in a thread happens before another thread successfully returns from Thread.join for that thread.
Happens before is transitive. If A happens before B and B happens before C, then A happens before C.
Without proper ordering, conflicting accesses from different threads can create a data race. The program cannot assume that the newest value will be observed. Processor caches and instruction reordering may affect an implementation, but the Java Memory Model defines guarantees rather than requiring a particular cache design.
Reads and writes of references and primitive values other than long and double are atomic. Reads and writes of volatile long and double are also atomic. Compound operations such as count++ are not atomic.
Use synchronized or locks when several operations or fields must be protected together. Use volatile for a simple state signal that does not require a compound update. Prefer immutable objects, safe publication, atomic classes, concurrent collections, and higher level coordination utilities when they match the problem.
Interviewers ask this question to check whether a candidate can reason correctly about shared data between Java threads. They evaluate knowledge of visibility, ordering, atomicity, data races, safe publication, and synchronization. They also want to know whether the candidate can choose correctly between synchronized, volatile, locks, atomic classes, immutable objects, and higher level concurrent utilities in production code.
Common interview mistakes
A common mistake is assuming that a thread always sees the latest shared value. Another is using volatile for count++ and expecting an atomic increment. Volatile gives visibility and ordering, but it does not make a compound read modify write operation atomic. Developers may also assume that safely publishing a reference makes every later mutation of the referenced object thread safe. Other mistakes include using sleep as a communication guarantee, synchronizing accesses with different locks, publishing an incompletely constructed mutable object, forgetting to use volatile in double checked locking, and describing the Java Memory Model as if Java requires a separate physical copy of every field for every thread.
Interview tip
Start with the practical rule that shared writes need a happens before relationship to be reliably visible. Then explain visibility, ordering, and atomicity. Name concrete rules for monitors, volatile fields, thread start, and thread join. Finish by stating that volatile does not make compound updates atomic and that synchronized or atomic classes are needed when an update depends on the previous value.
Interviewer may ask next
Does volatile make count++ thread safe?
No. A volatile field provides visibility and ordering, but count++ is a compound read modify write operation. Two threads can read the same value and both write the same next value, causing a lost update. This matters because every thread may see the field while the final result is still wrong. Use AtomicInteger.incrementAndGet, synchronized, or a suitable lock when the update must be atomic.
What is the tradeoff between synchronized and volatile for shared state?
Volatile is appropriate for an independent state value when each update is a single write and correctness does not depend on a previous value. It provides visibility and ordering without mutual exclusion, but it cannot protect a group of fields or a compound state transition. Synchronized provides visibility, ordering, and mutual exclusion, so it can protect invariants across several actions. Its main tradeoff is possible blocking and contention when many threads compete for the same monitor.
70. How does garbage collection work in the JVM?Language SpecificHard
i Question Details
Explain the basic phases of garbage collection, object reachability, and how GC influences application behavior.
Short Interview Answer (30-60 seconds)
The JVM reclaims heap memory from objects that are no longer reachable from GC roots. It traces references from those roots to find live objects, then the selected collector reclaims dead space and may copy or move live objects. Some collector work can pause application threads, while other work may run concurrently. Garbage collection removes the need for manual object deallocation, but it still consumes CPU and memory, so in production I monitor allocation rate, heap occupancy, pause time, collection frequency, and retained objects.
Detailed Explanation
The JVM manages memory used by most Java objects. When the running program can no longer reach an object, the JVM may reuse that memory. The object is not necessarily removed as soon as a method finishes or a variable disappears. The JVM decides when collection is needed. During collection, the application may briefly slow down or stop. The practical goal is to keep enough free memory while meeting response time and overall work goals. Different collectors make different choices about pauses, processor use, and extra memory.
Useful Questions to Ask the Interviewer
Which JDK version and garbage collector are we discussing?
Is the main goal lower pause time or higher throughput?
What heap limit and response time target does the application have?
How to Explain It in an Interview
Garbage collection mainly manages objects in the JVM heap. The collector starts from GC roots, which are references the JVM knows are currently active. Examples include references in active thread stacks, static fields of loaded classes, Java Native Interface references, and certain JVM internal references.
The collector follows references from these roots. Every object reached through that graph is considered live. An object that cannot be reached from any GC root is eligible for collection. This rule also allows unreachable cycles to be collected. Two objects may reference each other, but both can still be reclaimed when no live path reaches them.
A collection usually performs some form of tracing and reclamation. The collector may mark live objects, copy them to another memory region, compact memory by moving them together, or reclaim regions that contain no live objects. When objects move, the JVM updates references so the program continues to see the same logical objects.
Some phases require a stop the world pause, which means application threads are paused. Modern collectors also perform substantial work concurrently with the application. The exact phases and memory layout depend on the selected collector, so young and old generations should not be described as a universal rule for every collector and configuration.
Garbage collection does not prevent logical memory leaks. A cache, static field, listener, thread local value, class loader, queue, or collection may keep objects reachable after the application no longer needs them. In production, monitor heap occupancy, allocation rate, pause duration, collection frequency, promotion when the collector uses generations, concurrent cycle behavior, and retained object paths. Fix unnecessary retention and excessive allocation before changing heap or collector settings.
Why Interviewers Ask This
Interviewers ask this question to check whether a candidate understands JVM heap management, object reachability, collector phases, application pauses, and production tradeoffs. It also tests whether the candidate can distinguish automatic memory reclamation from memory leak prevention and can reason about allocation rate, retained objects, response time, throughput, CPU use, and heap limits.
Common interview mistakes
A common mistake is saying that an object is collected as soon as a local variable leaves scope. Eligibility depends on reachability, and collection timing is not guaranteed. Another mistake is describing JVM collection as simple reference counting. JVM collectors normally trace from GC roots, so unreachable reference cycles can be reclaimed. Setting one reference to null also does not guarantee collection because another live reference may still reach the object. Calling System.gc is not a reliable memory management strategy because it is only a request. It is also incorrect to assume every collector uses the same young and old generation design. Finally, increasing the heap can hide symptoms without fixing caches, static references, listeners, thread local values, class loader retention, unbounded queues, or excessive allocation.
Interview tip
Start with reachability from GC roots. Then explain tracing, reclaiming, copying or compaction, application pauses, and concurrent work. State that collector details differ. Finish with the main production tradeoffs: response time, throughput, CPU use, memory overhead, allocation rate, and retained objects.
Interviewer may ask next
Can two objects that reference each other still be garbage collected?
Yes. Both objects can be collected when neither is reachable from any GC root. The JVM traces the object graph from active roots rather than keeping an object alive only because another unreachable object points to it. This matters because an isolated reference cycle does not create permanent retention by itself. The cycle stays live only when a reachable path still leads to one of its objects.
How does the choice of garbage collector affect production performance?
The collector changes the balance among pause time, throughput, CPU use, and memory overhead. A throughput focused collector may complete more total application work while allowing longer pauses. A low pause collector may perform more work concurrently and require additional CPU or memory to keep pauses shorter. The correct choice depends on the live data size, heap limit, allocation rate, available processors, and response time target. The main tradeoff is that reducing pauses can require more concurrent work and extra memory, so the choice must be tested with realistic load and verified with JVM metrics and garbage collection logs.
More questions load as you scroll
Disclaimer: This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.