0% found this document useful (0 votes)
6 views10 pages

Q&A JAVA (1)

The document provides a comprehensive list of Java and Spring Boot interview questions and answers, covering topics such as core Java concepts, garbage collection, Java collections, multithreading, and the Spring framework. It includes detailed explanations of various Java features, types of garbage collectors, and Spring components, along with practical coding scenarios. This resource is aimed at helping candidates prepare for technical interviews in Java and Spring Boot development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views10 pages

Q&A JAVA (1)

The document provides a comprehensive list of Java and Spring Boot interview questions and answers, covering topics such as core Java concepts, garbage collection, Java collections, multithreading, and the Spring framework. It includes detailed explanations of various Java features, types of garbage collectors, and Spring components, along with practical coding scenarios. This resource is aimed at helping candidates prepare for technical interviews in Java and Spring Boot development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Java and Spring Boot Interview Questions

Common Glassdoor Java Interview Questions and Answers


Core Java Questions
1. What is Java? Answer: Java is a high-level, class-based, object-oriented
programming language designed to have as few implementation dependencies
as possible. It is used for building platform-independent applications.

2. What are the main features of Java? Answer: Key features include
portability, object-oriented, robust, secure, architecture-neutral, and high
performance.

3. What is the difference between JDK, JRE, and JVM? Answer:

1. JVM (Java Virtual Machine): Runs Java bytecode and provides a


runtime environment.

2. JRE (Java Runtime Environment): Includes JVM and standard libraries


needed to run Java applications.

3. JDK (Java Development Kit): Includes JRE and development tools


such as the compiler.

4. Explain the concept of Java bytecode. Answer: Java bytecode is the


intermediate representation of Java code, compiled by the Java compiler. It is
executed by the JVM, allowing Java applications to run on any platform.

5. What is the purpose of the main method in Java? Answer: The main
method is the entry point of a Java application. It is where the program starts
its execution.

Java Heap and Garbage Collection


1. What is Java Heap? Answer: Java Heap is a part of memory used for
dynamic memory allocation. It is where Java objects are allocated and
managed.

2. What is garbage collection in Java? Answer: Garbage collection is the


process of automatically identifying and disposing of unused objects to free up
memory and prevent memory leaks.

3. Explain the different types of garbage collectors in Java. Answer:


Common types include:

1. Serial GC: A simple garbage collector that uses a single thread.

2. Parallel GC: Uses multiple threads for garbage collection.

3. Concurrent Mark-Sweep (CMS) GC: Minimizes pause times by


performing most of the work concurrently.

4. G1 GC (Garbage-First): Aims to provide high throughput and low


pause times by dividing the heap into regions.

Different Types of Garbage Collectors in Java

1. Serial Garbage Collector


o Description: The Serial Garbage Collector is the simplest and oldest
GC implementation in Java. It uses a single thread for garbage
collection and is best suited for applications with small heaps and a
single processor.

o Characteristics:

 Single-threaded: Performs garbage collection using only one


thread.

 Pause Times: Can cause significant pauses since it halts all


application threads during garbage collection.

 Usage: Ideal for small applications or environments with


limited resources where simplicity and low overhead are
desirable.

2. Parallel Garbage Collector (Throughput Collector)

o Description: The Parallel Garbage Collector is designed to maximize


overall throughput by using multiple threads to perform garbage
collection tasks. It aims to reduce the time spent on garbage
collection relative to the application’s runtime.

o Characteristics:

 Multi-threaded: Utilizes multiple threads for both minor and


major garbage collection.

 Pause Times: Reduces pause times compared to the Serial


GC by parallelizing the work.

 Usage: Suitable for applications where high throughput is a


priority, and the system has multiple CPU cores.

3. Concurrent Mark-Sweep (CMS) Garbage Collector

o Description: The CMS Garbage Collector minimizes pause times by


performing most of its work concurrently with the application’s
execution. It focuses on reducing the duration of GC pauses.

o Characteristics:

 Concurrent Phases: Includes initial marking, concurrent


marking, remark, and cleanup phases, most of which run
concurrently with application threads.

 Pause Times: Aims for low pause times but may still
experience some pauses during the remark phase.

 Usage: Best for applications that require low latency and


cannot tolerate long pause times.

4. Garbage-First (G1) Garbage Collector

o Description: The G1 Garbage Collector is designed for applications


with large heaps and aims to provide a balance between low pause
times and high throughput. It divides the heap into regions and
performs incremental garbage collection.

o Characteristics:
 Region-based: Divides the heap into fixed-size regions and
manages garbage collection within these regions.

 Configurable Pauses: Allows configuration of maximum


pause times and adjusts collection behavior accordingly.

 Usage: Ideal for applications with large heaps that need


predictable pause times and a balance between throughput
and pause duration.

5. ZGC (Z Garbage Collector)

o Description: ZGC is a low-latency garbage collector introduced in


Java 11, designed to handle large heaps with minimal pause times,
typically in the range of milliseconds.

o Characteristics:

 Short Pauses: Provides extremely short pause times, aiming


for pause times as low as possible.

 Concurrent Work: Performs most of the garbage collection


work concurrently with the application’s execution.

 Usage: Suitable for applications requiring very low latency


and large heap sizes.

6. Shenandoah Garbage Collector

o Description: Shenandoah is another low-latency garbage collector


introduced in Java 12, focusing on reducing pause times to a few
milliseconds. It operates similarly to ZGC but with different
implementation details.

o Characteristics:

 Low Pause Times: Targets low pause times with a goal of


keeping pauses short and predictable.

 Concurrent Collection: Uses concurrent approaches to


manage memory and reduce pause durations.

 Usage: Suitable for applications that need consistent low-


latency performance with large memory heaps.

Each garbage collector has its own strengths and is suited for different types of
applications and environments. Choosing the right garbage collector depends on
the specific needs of the application, such as latency requirements, throughput
needs, and heap size.

4. What is a memory leak in Java? Answer: A memory leak occurs when


objects are no longer needed but are not garbage collected due to remaining
references.

5. How do you analyze memory leaks in Java? Answer: Use profiling tools
like VisualVM, Eclipse Memory Analyzer (MAT), or Java Mission Control to detect
and analyze memory leaks.

Java Collections
1. What is the difference between ArrayList and LinkedList? Answer:
1. ArrayList: Backed by a dynamic array, providing fast random access
but slower insertions and deletions.

2. LinkedList: Uses a doubly-linked list, offering faster insertions and


deletions but slower random access.

2. What is a HashMap in Java? Answer: A HashMap is a map implementation that


stores key-value pairs and allows fast retrieval based on hash codes.

3. What is the difference between HashMap and Hashtable? Answer:

1. HashMap: Not synchronized, allows null keys and values.

2. Hashtable: Synchronized, does not allow null keys or values.

4. What is a Set in Java? Answer: A Set is a collection that does not allow
duplicate elements. Common implementations include HashSet and TreeSet.

5. Explain the TreeMap class. Answer: TreeMap is a NavigableMap implementation


that stores keys in a sorted order, based on their natural ordering or a specified
comparator.

Multithreading in Java
1. What is the difference between synchronized and volatile? Answer:

1. Synchronized: Ensures exclusive access to a method or block of code


by multiple threads.

2. Volatile: Ensures visibility of changes to variables across threads


without locking.

2. What is the Thread class in Java? Answer: The Thread class represents a
thread of execution in a program. It provides methods to start, run, and
manage threads.

3. How do you create a thread in Java? Answer: You can create a thread by
extending the Thread class or implementing the Runnable interface and passing
it to a Thread object.

4. What is a Deadlock in Java? Answer: A deadlock occurs when two or more


threads are blocked forever, each waiting for the other to release a lock.

5. How can you prevent deadlock? Answer: Prevent deadlock by avoiding


nested locks, using a timeout for acquiring locks, or implementing a lock
ordering strategy.

Spring Framework Questions and Answers


1. What is Spring Framework? Answer: Spring Framework is a comprehensive
framework for enterprise Java development that provides features like
dependency injection (DI), aspect-oriented programming (AOP), and
transaction management.

2. What are the main features of Spring? Answer: Key features include
Dependency Injection (DI), Aspect-Oriented Programming (AOP), Transaction
Management, MVC Framework, and Data Access Integration.

3. What is Dependency Injection? Answer: Dependency Injection is a design


pattern used to achieve Inversion of Control (IoC) by injecting dependencies
into objects rather than allowing objects to create or manage their
dependencies themselves.
4. What are the different types of Dependency Injection? Answer:

1. Constructor Injection: Dependencies are provided through the


constructor.

2. Setter Injection: Dependencies are provided through setter methods.

3. Field Injection: Dependencies are injected directly into fields (less


recommended).

5. What is Inversion of Control (IoC)? Answer: IoC is a design principle where


the control of object creation and dependency management is inverted from
the object itself to a framework or container.

6. What is a Spring Bean? Answer: A Spring Bean is an object that is


instantiated, configured, and managed by the Spring IoC container.

7. What is the Spring IoC Container? Answer: The Spring IoC Container is
responsible for managing the lifecycle and configuration of application objects
(beans). It is configured using XML, annotations, or Java configuration.

8. What are the different types of Spring IoC Containers? Answer:

1. BeanFactory: The simplest container, providing basic support for


dependency injection.

2. ApplicationContext: A more advanced container that includes


additional features like event propagation, declarative mechanisms, and
various means to look up.

9. What are the different scopes of Spring Beans? Answer:

1. Singleton: One instance per Spring container (default scope).

2. Prototype: A new instance is created each time the bean is requested.

3. Request: A new instance is created for each HTTP request (only in web
applications).

4. Session: A new instance is created for each HTTP session (only in web
applications).

5. GlobalSession: A new instance is created for each global HTTP session


(only in portlet-based web applications).

10. What is the @Component annotation? Answer: @Component is a generic


stereotype annotation used to mark a class as a Spring-managed component. It
is a base annotation for other specialized annotations like @Service,
@Repository, and @Controller.

11. What is the difference between @Component, @Service, @Repository, and


@Controller? Answer: They are specialized versions of @Component:

1. @Service: Used for service layer components.

2. @Repository: Used for data access layer components and provides


additional support for exception translation.

3. @Controller: Used for presentation layer components in web


applications.

12. What is Aspect-Oriented Programming (AOP)? Answer: AOP is a


programming paradigm that provides a way to modularize cross-cutting
concerns (e.g., logging, transaction management) by separating them from the
business logic.

13. What are the main concepts in AOP? Answer:

1. Aspect: A module that defines a cross-cutting concern.

2. Join Point: A point in the execution of the application (e.g., method


execution).

3. Advice: The action to be taken at a join point (e.g., before, after, or


around method execution).

4. Pointcut: An expression that specifies the join points where advice


should be applied.

5. Weaving: The process of integrating aspects into the application.

14. What is the difference between @Before, @After, and @Around advice?
Answer:

1. @Before: Executes before the join point (e.g., method execution).

2. @After: Executes after the join point, regardless of its outcome.

3. @Around: Wraps the join point and can control when the join point is
executed (before, after, or not at all).

15. What is Spring MVC? Answer: Spring MVC is a web framework that provides
a model-view-controller architecture for building web applications. It separates
the application into model, view, and controller layers.

16. What are the main components of Spring MVC? Answer:

1. Model: Represents the data and business logic.

2. View: Represents the user interface (e.g., JSP, Thymeleaf).

3. Controller: Handles user requests and interacts with the model to


generate responses.

17. How does Spring Boot differ from the Spring Framework? Answer:
Spring Boot is a project built on top of the Spring Framework that simplifies the
setup and development of Spring applications by providing production-ready
features, auto-configuration, and a convention-over-configuration approach.

18. What is auto-configuration in Spring Boot? Answer: Auto-configuration


automatically configures Spring application components based on the
dependencies present on the classpath and the application’s properties.

19. What is the purpose of @SpringBootApplication annotation? Answer: It is


a convenience annotation that combines @Configuration,
@EnableAutoConfiguration, and @ComponentScan to simplify configuration and
setup.

20. How do you configure a Spring Boot application? Answer: Configuration


can be done using application properties or YAML files, environment variables,
and command-line arguments. Configuration properties can be defined in
application.properties or application.yml.

21. What is the purpose of application.properties or application.yml in


Spring Boot? Answer: These files are used to externalize configuration
settings, such as database connection properties, server settings, and
application-specific parameters.

22. What is a Spring Boot Starter? Answer: A Spring Boot Starter is a


dependency descriptor that aggregates a set of related dependencies,
simplifying the inclusion of common libraries for a specific functionality (e.g.,
spring-boot-starter-web, spring-boot-starter-data-jpa).

23. What is @ConfigurationProperties in Spring Boot? Answer:


@ConfigurationProperties is used to bind configuration properties from external
configuration files to a Java bean, allowing for easy management of application
settings.

24. How do you create a RESTful API with Spring Boot? Answer: Create a
RESTful API by using @RestController to define endpoints, @RequestMapping to
map requests to methods, and return responses in JSON format.

25. What is Actuator in Spring Boot? Answer: Spring Boot Actuator provides
production-ready features such as monitoring, metrics, and health checks. It
exposes endpoints to manage and monitor the application.

26. How do you handle exceptions in Spring Boot? Answer: Handle


exceptions using @ControllerAdvice for global exception handling or
@ExceptionHandler to handle specific exceptions within a controller.

27. What is Spring Boot DevTools? Answer: It is a set of tools to improve the
development experience, including features like automatic restarts, live reload,
and configuration properties management.

28. How do you create a scheduled task in Spring Boot? Answer: Use the
@Scheduled annotation on a method to define scheduled tasks, and enable
scheduling with @EnableScheduling.

29. What is the @Configuration annotation used for? Answer: It is used to


define a class as a source of bean definitions and configuration in a Spring
context.

30. What are Spring Boot’s embedded servers? Answer: Spring Boot
provides embedded servers like Tomcat, Jetty, and Undertow, allowing
applications to run as standalone Java applications without needing an external
server.

31. How do you configure multiple data sources in Spring Boot? Answer:
Define multiple DataSource beans and configure them using @Primary for the
default DataSource and @Qualifier for others.

32. What is @Value annotation used for? Answer: It is used to inject values into
fields from configuration files or environment variables.

33. How do you override default Spring Boot configurations? Answer:


Override default configurations by providing your own configurations in
application.properties or application.yml, or by creating custom
@Configuration classes.

34. What is @SpringBootTest used for? Answer: It is used for integration testing
of Spring Boot applications, providing a complete Spring application context for
testing.

35. How do you create a Spring Boot application with embedded Jetty?
Answer: Include spring-boot-starter-jetty dependency and exclude Tomcat
from spring-boot-starter-web.
36. What is @EnableAutoConfiguration used for? Answer: It enables Spring
Boot’s auto-configuration feature to automatically configure application
components based on the dependencies present.

37. How do you secure a Spring Boot application? Answer: Use Spring
Security to configure authentication, authorization, and protection mechanisms
in your application.

38. What is the role of @ComponentScan? Answer: It is used to specify the


packages to scan for Spring-managed components and beans.

39. How do you configure logging in Spring Boot? Answer: Configure logging
through application.properties or application.yml, and use logging
frameworks like Logback, Log4j2, or Java Util Logging.

40. What is a Spring Boot Banner? Answer: It is a banner displayed in the


console when a Spring Boot application starts. It can be customized or disabled
via properties.

41. What is @ConditionalOnProperty? Answer: It is used to conditionally enable or


disable beans based on the presence and value of specific properties.

42. How do you define a REST API with Spring Boot? Answer: Use
@RestController to define a controller, and map HTTP requests to methods
using @RequestMapping, @GetMapping, @PostMapping, etc.

43. What is @Profile annotation used for? Answer: It is used to define different
beans and configurations for different environments or profiles (e.g.,
development, production).

44. How do you test a Spring Boot application? Answer: Use testing
frameworks like JUnit and Spring Test for unit and integration testing. Utilize
@SpringBootTest for context loading and end-to-end tests.

45. What is @DataJpaTest annotation? Answer: It is used for testing JPA


components, configuring an in-memory database and scanning for JPA entities
and repositories.

46. How do you manage application properties for different environments


in Spring Boot? Answer: Use profile-specific configuration files, such as
application-dev.properties and application-prod.properties, and specify the
active profile with spring.profiles.active.

47. What is the role of Spring Boot Initializr? Answer: It is an online tool that
generates a Spring Boot project structure with dependencies, configurations,
and boilerplate code based on user inputs.

48. How do you handle CORS (Cross-Origin Resource Sharing) in Spring


Boot? Answer: Configure CORS by using @CrossOrigin annotation on
controllers or global CORS configuration through WebMvcConfigurer.

49. What is the @Bean annotation used for? Answer: It is used to define a bean
in a @Configuration class and manage its lifecycle in the Spring context.

50. What is the purpose of @Autowired annotation? Answer: It is used for


automatic dependency injection, allowing Spring to resolve and inject
collaborating beans into a class.

51. How do you manage transactions in Spring Boot? Answer: Use


@Transactional annotation to define transaction boundaries and manage
transactions declaratively.
52. What is the @RequestMapping annotation used for? Answer: It is used to
map HTTP requests to handler methods in controllers, specifying URL patterns,
HTTP methods, and other request attributes.

53. How do you use @ResponseStatus annotation in Spring Boot? Answer: It is


used to define the HTTP status code returned from a controller method or
exception handler.

54. What is @EntityScan used for? Answer: It is used to specify the packages to
scan for JPA entities, especially when entities are in different packages from the
main application.

55. How do you handle HTTP sessions in Spring Boot? Answer: Use
HttpSession to manage user sessions and @SessionAttributes to store session
attributes.

56. What is the Spring Boot CLI? Answer: It is a command-line tool for
developing and testing Spring Boot applications using Groovy or Java.

57. What is @Component annotation used for? Answer: It is used to mark a class
as a Spring-managed component, making it eligible for component scanning
and dependency injection.

58. How do you create a custom error page in Spring Boot? Answer: Create
an HTML page named error.html or configure error pages through
application.properties using server.error.whitelabel.enabled=false.

59. What is @RequestBody annotation used for? Answer: It is used to bind the
HTTP request body to a method parameter in a controller, usually for handling
JSON or XML data.

60. What is @PathVariable annotation used for? Answer: It is used to extract


values from URI templates and bind them to method parameters in a controller.

61. How do you enable and configure caching in Spring Boot? Answer: Use
@EnableCaching annotation to enable caching and configure caching behavior
using CacheManager and Cache implementations.

62. How do you define a REST API with Spring Boot? Answer: Use
@RestController to define a controller, and map HTTP requests to methods
using @RequestMapping, @GetMapping, @PostMapping, etc.

63. What is @Profile annotation used for? Answer: It is used to define different
beans and configurations for different environments or profiles (e.g.,
development, production).

64. How do you test a Spring Boot application? Answer: Use testing
frameworks like JUnit and Spring Test for unit and integration testing. Utilize
@SpringBootTest for context loading and end-to-end tests.

65. What is @DataJpaTest annotation? Answer: It is used for testing JPA


components, configuring an in-memory database and scanning for JPA entities
and repositories.

66. How do you manage application properties for different environments


in Spring Boot? Answer: Use profile-specific configuration files, such as
application-dev.properties and application-prod.properties, and specify the
active profile with spring.profiles.active.

67. What is the role of Spring Boot Initializr? Answer: It is an online tool that
generates a Spring Boot project structure with dependencies, configurations,
and boilerplate code based on user inputs.
68. How do you handle CORS (Cross-Origin Resource Sharing) in Spring
Boot? Answer: Configure CORS by using @CrossOrigin annotation on
controllers or global CORS configuration through WebMvcConfigurer.

69. What is the @Bean annotation used for? Answer: It is used to define a bean
in a @Configuration class and manage its lifecycle in the Spring context.

70. What is the purpose of @Autowired annotation? Answer: It is used for


automatic dependency injection, allowing Spring to resolve and inject
collaborating beans into a class.

71. How do you manage transactions in Spring Boot? Answer: Use


@Transactional annotation to define transaction boundaries and manage
transactions declaratively.

72. What is the @RequestMapping annotation used for? Answer: It is used to


map HTTP requests to handler methods in controllers, specifying URL patterns,
HTTP methods, and other request attributes.

73. How do you use @ResponseStatus annotation in Spring Boot? Answer: It is


used to define the HTTP status code returned from a controller method or
exception handler.

74. What is @EntityScan used for? Answer: It is used to specify the packages to
scan for JPA entities, especially when entities are in different packages from the
main application.

75. How do you handle HTTP sessions in Spring Boot? Answer: Use
HttpSession to manage user sessions and @SessionAttributes to store session
attributes.

76. What is the Spring Boot CLI? Answer: It is a command-line tool for
developing and testing Spring Boot applications using Groovy or Java.

77. What is @Component annotation used for? Answer: It is used to mark a class
as a Spring-managed component, making it eligible for component scanning
and dependency injection.

78. How do you create a custom error page in Spring Boot? Answer: Create
an HTML page named error.html or configure error pages through
application.properties using server.error.whitelabel.enabled=false.

79. What is @RequestBody annotation used for? Answer: It is used to bind the
HTTP request body to a method parameter in a controller, usually for handling
JSON or XML data.

80. What is @PathVariable annotation used for? Answer: It is used to extract


values from URI templates and bind them to method parameters in a controller.

81. How do you enable and configure caching in Spring Boot? Answer: Use
@EnableCaching annotation to enable caching and configure caching behavior
using CacheManager and Cache implementations.

You might also like