Top 50 Most Frequent Java Interview Questions & Answer
Top 50 Most Frequent Java Interview Questions & Answer
Questions
This comprehensive guide presents the top 50 most frequently asked questions in Java
interviews, curated from various online resources and expert opinions. Whether you're a fresher
just starting your career or an experienced developer aiming for a senior role, this compilation
will equip you with the knowledge and confidence to excel in your next Java interview.
Basic Concepts
Core Concepts
1. What is Java? Java is a high-level, object-oriented programming language known for its
platform independence, security, and robustness. It's widely used for developing various
applications, including web, mobile, and enterprise solutions.
2. What is Java's 'write once, run anywhere' philosophy? This philosophy refers to Java's
ability to run on any platform with a Java Virtual Machine (JVM) without needing any code
modifications. This is achieved through Java's bytecode, which can be executed on any
system with a JVM.
4. What is a JIT compiler? A JIT (Just-In-Time) compiler improves the performance of Java
programs by compiling bytecode into native machine code at runtime. This allows frequently
executed code to run faster, as it doesn't need to be interpreted repeatedly.
Object-Oriented Principles
5. What are the key features of Java?
Platform independence: Java code can run on any platform with a Java Virtual Machine
(JVM), thanks to its "write once, run anywhere" principle.
○ Object-oriented: Java follows the principles of OOP, including encapsulation,
inheritance, and polymorphism, promoting modularity and code reusability.
○ Robust: Java has strong memory management and exception handling mechanisms,
reducing errors and enhancing reliability.
○ Secure: Java's security features protect against malicious code and unauthorized
access.
7. Why is Java not a "pure" object-oriented language? Java is not considered pure
object-oriented because it uses primitive data types (like int, float, char) which are not
objects.
9. What is method overloading? Method overloading allows multiple methods with the
same name but different parameters in the same class. The methods must have the same
name but different parameter lists, which can vary by Number of parameters, Data types of
parameters & Order of parameters.
public class Calculator {
// Method with two int parameters
public int add(int a, int b) {
return a + b;
}
The return type alone cannot be used to differentiate overloaded methods.This won't work:
public int add(int a, int b) { return a + b; }
public double add(int a, int b) { return a + b; } // Compilation error
Java uses the parameter list to determine which method to call at compile time. For
example:
Calculator calc = new Calculator();
calc.add(5, 3); // Calls the first method
calc.add(5, 3, 2); // Calls the second method
calc.add(5.5, 3.5); // Calls the third method
10. What is method overriding? Method overriding occurs when a subclass provides a
specific implementation for a method that is already defined in its superclass. This allows
subclasses to customize the behavior of inherited methods.
// Parent class
public class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}
// Child class
public class Dog extends Animal {
@Override // This annotation is recommended but optional
public void makeSound() {
System.out.println("Woof! Woof!");
}
}
// Child class
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
Animal myDog = new Dog();
myDog.makeSound(); // Outputs: "Woof! Woof!"
Access Control
14. What are access modifiers in Java? Access modifiers control the visibility of classes,
methods, and variables. They include: - public: Accessible from any class. - protected:
Accessible within the same package and subclasses. - default: Accessible only within the
same package. - private: Accessible only within the same class. For example, using private
access modifiers for sensitive data members ensures that they can only be accessed and
modified within the class itself, enhancing data security and encapsulation.
15. What is the purpose of the static keyword in Java? The static keyword is used to define
members (methods or variables) that belong to the class itself rather than instances of the
class. Static methods can be called without creating an object of the class.
16. What is the purpose of the final keyword in Java? The final keyword can be applied to
variables, methods, and classes: - Variable: Makes the variable a constant, its value cannot
be changed. - Method: Prevents the method from being overridden in subclasses. - Class:
Prevents the class from being inherited.
17. What is an interface? An interface defines a contract that classes can implement. It
specifies a set of methods that implementing classes must provide.
18. What is an abstract class? An abstract class cannot be instantiated and may contain
abstract methods (methods without implementation). It serves as a blueprint for subclasses.
21. What is a package in Java? A package is a way to organize related classes and
interfaces into a namespace, preventing naming conflicts and improving code
maintainability.
22. What is the difference between the program and the process?
○ A program is a set of instructions written in a programming language, like Java. It is a
static entity.
○ A process is an instance of a program that is being executed. It is a dynamic entity with
its own memory space and resources.
Collections Framework
23. What are Java Collections? The Java Collections Framework provides a set of interfaces
and classes for storing and manipulating groups of objects. It offers various data structures
like lists, sets, and maps, each with its own characteristics and performance considerations.
27. How does HashSet work internally in Java? HashSet internally uses a HashMap to
store its elements. Each element is stored as a key in the HashMap, with a dummy object
as its value.
28. How do you sort a collection in Java? Collections can be sorted using the
Collections.sort() method for lists and the TreeSet class for sets. The sort() method can take
a comparator as an argument to customize the sorting order.
29. How do you print an array in Java? Arrays can be printed using the Arrays.toString()
method, which converts the array to a string representation.
Exception Handling
31. What is an exception? An exception is an abnormal event that disrupts the normal flow of
a program. Exceptions can be caused by various factors, such as invalid user input,
network issues, or resource limitations.
34. What is the purpose of the finally block? The finally block is used to execute code
regardless of whether an exception is thrown or caught. It's often used to release resources,
such as closing files or database connections, to prevent resource leaks.
36. How do you create a thread in Java? Threads can be created by: - Extending the Thread
class and overriding its run() method. - Implementing the Runnable interface and providing
a run() method implementation.
// Usage:
MyThread thread = new MyThread();
thread.start(); // Starts the thread
// Usage:
Thread thread = new Thread(new MyRunnable());
thread.start();
38. What is synchronization? Synchronization ensures that only one thread can access a
shared resource at a time, preventing data inconsistency. This is typically achieved using
synchronized blocks or methods, which use locks to control access to the shared resource.
39. What is a deadlock? A deadlock occurs when two or more threads are blocked forever,
each waiting for the other to release a resource. For example, if thread A holds lock 1 and is
waiting for lock 2, while thread B holds lock 2 and is waiting for lock 1, a deadlock occurs.
40. What is a race condition? A race condition occurs when the behavior of a program
depends on the unpredictable order of execution of multiple threads. This can lead to
unexpected and erroneous results.
41. What is thread starvation? Thread starvation occurs when a thread is unable to gain
regular access to shared resources and is therefore unable to make progress. This can
happen if other threads have higher priority or hold the required resources for extended
periods.
42. What is the ExecutorService interface and how does it work? The ExecutorService
interface provides a mechanism for managing a pool of threads and submitting tasks for
execution. It simplifies thread management and improves efficiency by reusing threads
instead of creating new ones for each task.
43. How will you create a daemon thread in Java? A daemon thread is a low-priority thread
that runs in the background and provides services to user threads. To create a daemon
thread, you can use the setDaemon(true) method on a thread object before starting it.
44. What is time slicing? Time slicing is a technique used by operating systems to allocate
CPU time to different threads. Each thread gets a small slice of CPU time, and the CPU
switches between threads rapidly, giving the illusion of parallel execution.
45. What is a thread schedule? A thread scheduler is a component of the operating system
that determines which thread should run next. It uses various algorithms to prioritize threads
and ensure fair allocation of CPU time.
Advanced Concepts
47. What is the difference between fail-fast and fail-safe iterators?
○ Fail-fast: Throw an exception (ConcurrentModificationException) if a collection is
modified while iterating. This helps to detect concurrent modifications and prevent data
inconsistency.
○ Fail-safe: Create a copy of the collection for iteration, allowing modifications to the
original collection without affecting the iterator. This provides a more robust iteration
mechanism but may have higher memory overhead.
48. What is serialization? Serialization is the process of converting an object into a byte
stream, which can be stored in a file or transmitted over a network. This allows objects to be
persisted and reconstructed later.
49. What is the purpose of the transient keyword? The transient keyword prevents a
variable from being serialized. This is useful for fields that should not be persisted, such as
sensitive data or temporary variables.
50. What is reflection? Reflection allows inspection and manipulation of classes, methods,
and fields at runtime. This can be used for tasks like dynamically loading classes, invoking
methods, and accessing private members.
51. What are Java annotations? Annotations provide metadata about code. They can be
used for documentation, compile-time checks, and runtime processing. Examples include
@Override and @Deprecated.
53. What are Java Streams? Streams provide a functional approach to processing collections
of data. They allow operations like filtering, mapping, and reducing to be performed
efficiently. Streams can improve code readability and performance, especially for large
datasets.
54. What is the Optional class? The Optional class helps to avoid null pointer exceptions by
providing a container for optional values. It encourages developers to explicitly handle the
case where a value might be absent.
55. What is a functional interface? A functional interface is an interface with exactly one
abstract method. It can be used with lambda expressions. Examples include Runnable and
Comparator.
58. What is the difference between Heap and Stack Memory in Java?
○ Heap: Stores objects and their instance variables. It is a shared memory area used by all
parts of the application.
○ Stack: Stores method calls and local variables. Each thread has its own stack. Java
utilizes heap memory for dynamic memory allocation of objects, while stack memory is
used for managing method execution and local variables within each thread.
59. What is a marker interface? A marker interface is an empty interface that provides
metadata about a class. It does not have any methods. Examples include Serializable and
Cloneable.
60. What is the JDBC API? JDBC (Java Database Connectivity) is an API for connecting to
and interacting with databases. It allows Java applications to execute SQL queries, retrieve
data, and update databases.
61. What is the purpose of the volatile keyword? The volatile keyword ensures that a
variable is read from and written to main memory, preventing caching issues in
multithreaded environments. This is important for variables that are shared between
multiple threads.
62. Why would it be pointless for a static or final method to use dynamic binding?
Dynamic binding (also known as late binding) is a mechanism where the method to be
called is determined at runtime. However, static and final methods are resolved at compile
time, so dynamic binding wouldn't apply to them.
63. How is a code point related to a code unit in Unicode? In Unicode, a code point is a
unique numeric value that represents a character. A code unit is a bit sequence used to
encode code points. Different encoding schemes (like UTF-8 and UTF-16) use different
code unit sizes.
64. Can you tell us which three steps you would use to simulate a static class in Java?
Here are the three steps to simulate a static class in Java
Usage example:
// This works:
66. What are the ways to detect memory leaks in an application? Memory leaks occur
when objects are no longer needed but are still reachable, preventing garbage collection.
Tools like profilers and heap analyzers can be used to detect memory leaks by identifying
objects that are consuming excessive memory.
Top 50 Spring Boot Interview Questions
and Answers
Spring Boot has revolutionized the way Java developers build and deploy applications. Its
popularity has made it a common topic in technical interviews, especially for those seeking roles
involving Java and backend development. This article presents a comprehensive list of the top
50 most frequently asked Spring Boot interview questions, categorized by experience level and
covering a wide range of essential concepts. Whether you're a fresher just starting your journey
or an experienced developer looking to brush up on your knowledge, this guide will equip you
with the insights needed to ace your next Spring Boot interview.
10. What is the difference between @RestController and @Controller in Spring Boot?
○ @Controller is used for traditional Spring MVC applications where you return a view
name.
○ @RestController is a specialized version of @Controller that combines @Controller and
@ResponseBody, making it suitable for building RESTful web services that return data
directly.
17. How to enable Actuator in Spring boot application? Add the spring-boot-starter-actuator
dependency to your project's pom.xml or build.gradle file.
Dependency Injection
These questions test your understanding of dependency injection in Spring Boot:
18. What is Dependency Injection in Spring Boot?
Dependency Injection (DI) is a design pattern where objects are not responsible for creating
their own dependencies. Instead, dependencies are "injected" into objects by a container
(Spring IoC container). This promotes loose coupling and makes code more testable and
maintainable.
Data Access
These questions cover Spring Boot's data access features:
21. How does Spring Boot support database operations?
Spring Boot provides excellent support for database operations through Spring Data JPA,
which simplifies database interactions and reduces boilerplate code. To connect to a
database using Spring Data JPA, you need to:
○ Add the spring-boot-starter-data-jpa dependency to your project.
○ Configure the database connection details in your application.properties or
application.yml file.
○ Define JPA entities and repositories to interact with your database.
Templating Engines
This section explores templating engines used in Spring Boot applications:
23. What is Thymeleaf? How do you use it in a Spring Boot application?
Thymeleaf is a popular server-side Java template engine for web and standalone
environments. To use Thymeleaf in a Spring Boot application, you should include the
spring-boot-starter-thymeleaf dependency in your project. This will automatically configure
Thymeleaf and make it ready to use for creating dynamic web pages.
26. Have you implemented REST API versioning? What was the need, and how did you
implement it? What are the possible ways to implement versioning in a Spring Boot
application?
API versioning is important for maintaining backward compatibility while evolving your API.
There are several ways to implement versioning in Spring Boot, such as using URL path
versioning (e.g., /v1/users), request parameter versioning (e.g., /users?version=1), or
header versioning (e.g., Accept: application/vnd.myapp.v1+json).
Exception Handling
These questions assess your knowledge of exception handling in Spring Boot:
27. How do you handle exceptions in Spring Boot?
Spring Boot provides several ways to handle exceptions:
○ Using @ControllerAdvice to define global exception handlers.
○ Using @ExceptionHandler to handle specific exceptions in controllers.
○ Using ResponseEntityExceptionHandler to customize the response for standard Spring
exceptions.
Logging
This question covers Spring Boot's logging capabilities:
29. How does Spring Boot support logging?
Spring Boot uses Commons Logging for internal logging and provides default configurations
for popular logging libraries like Logback, Log4j2, and Java Util Logging. You can configure
logging levels, output formats, and appenders in external configuration files.
Embedded Servers
This question delves into Spring Boot's embedded server support:
30. What is Spring Boot's embedded server, and how do you configure it?
Spring Boot includes embedded servers like Tomcat, Jetty, and Undertow. You can
configure the server by setting properties in application.properties or application.yml, such
as the server port (server.port). The default port number for a Spring Boot application is
8080, but it can be changed in the application's configuration file (e.g.,
application.properties or application.yml) using the property server.port11. Embedded
servers eliminate the need to set up and manage external application servers, simplifying
development and testing.
32. What are the most common Spring Boot CLI commands?
Some common CLI commands include:
○ init: Creates a new Spring Boot project.
○ run: Runs a Spring Boot application.
○ test: Runs tests for a Spring Boot application.
Spring Initializr
This question covers the role of Spring Initializr in bootstrapping Spring Boot projects:
33. What is Spring Initializr?
Spring Initializr is a web-based tool and API that simplifies the creation of Spring Boot
projects. It allows you to select dependencies, project metadata, and generate a project
structure.
Miscellaneous
These questions cover various other aspects of Spring Boot:
34. What are the different scopes available in Spring Boot?
Spring beans can have different scopes:
○ singleton: A single instance of the bean is created per application context.
○ prototype: A new instance of the bean is created each time it is injected.
○ request: A new instance of the bean is created for each HTTP request.
○ session: A new instance of the bean is created for each user session.
○ application: A single instance of the bean is created per ServletContext.
35. How to get the list of all the beans in your Spring boot application?
You can use the listBeans() method of the ApplicationContext to get a list of all beans
defined in your Spring Boot application.
36. Can we disable the default web server in the Spring Boot application?
Yes, you can disable the default web server by setting webApplicationType to NONE in the
@SpringBootApplication annotation.
40. What is the procedure for creating a non-web application in Spring Boot?
To create a non-web application, exclude the spring-boot-starter-web dependency and use
appropriate dependencies for your application type (e.g., spring-boot-starter-batch for batch
processing).
43. State the differences between Spring MVC and Spring Boot.
Spring MVC is a framework for building web applications, while Spring Boot builds on top of
Spring MVC to provide a more streamlined and opinionated approach to development.
45. What are conditional annotations? Have you used any such annotations?
Conditional annotations allow you to conditionally enable or disable components or
configurations based on certain conditions. Examples include @ConditionalOnProperty,
@ConditionalOnBean, and @ConditionalOnMissingBean.
46. What is the use of @EnableAutoConfiguartion annotation in spring boot? How does
spring boot achieve auto configuration?
@EnableAutoConfiguration triggers Spring Boot's auto-configuration mechanism, which
automatically configures beans based on the classpath and other application settings.
47. If we do not want a dependency to be auto-configured by AutoConfiguration, what
steps do we need to take?
You can exclude specific auto-configuration classes using the exclude attribute of
@EnableAutoConfiguration or by defining your own configuration that overrides the
auto-configured beans.
48. How do you monitor your spring boot application in production? Which dependency
you use?
You can monitor Spring Boot applications using tools like Spring Boot Actuator, Micrometer,
and Prometheus. The spring-boot-starter-actuator dependency provides basic monitoring
endpoints.
49. What are the ways to secure Apis? Which all starter dependencies you have used in
application?
You can secure APIs using Spring Security, which provides authentication, authorization,
and other security features. The spring-boot-starter-security dependency is used to
integrate Spring Security.
51. What are interceptors and How are you using it in your spring boot application?
Explain life cycle of interceptors (different phases involved)
Interceptors intercept requests before and after they reach the controller. They can be used
for tasks like logging, security checks, and modifying request/response data. Interceptors
have three main phases: preHandle (before the handler method is invoked), postHandle
(after the handler method completes), and afterCompletion (after the complete request is
finished).
Remember to demonstrate your problem-solving skills, your ability to apply Spring Boot
concepts to real-world scenarios, and your passion for continuous learning. Good luck!