For every Java developer, it's essential to be well-prepared with knowledge of common Java interview questions before attending an interview. Each day, countless candidates apply for jobs and face interviews, making it the interviewer's responsibility to select the best talent from the pool of job seekers. and As a job seeker, it's your responsibility to be prepared to answer most of the questions asked by the interviewer.
In this article, I am going to share some of the mostly asked Java and Spring boot interview questions for 3 years of experienced Java developers.
Java Interview Questions:
1. What is a singleton class in Java?
A singleton class is a class that can have only one instance throughout the application. It is used to ensure that a class has only one instance and provides a global point of access to it. This is typically achieved using a private constructor and a static method to get the single instance.
2. What are strings in Java?
Strings in Java are used to handle text data. They are represented by the String class, which is immutable. This means once you create a String object, its value can't be changed. For example, if you create a String with the value "Hello", and If you try to modify it to "Hello World"; So it will not modify that string, instead it will create a new String object with the value "Hello world".
3. What do you mean by dynamic binding in Java?
Dynamic binding, also known as runtime polymorphism, occurs when the method to be invoked is determined at runtime, not at compile-time. For example, if you have a method in a base class and overridden versions in derived classes, Java will decide which method to call based on the actual type of the object at runtime.
4. What is the difference between StringBuffer and StringBuilder?
Both StringBuffer and StringBuilder are used for mutable strings, but StringBuffer is synchronized (thread-safe) while StringBuilder is not. This means StringBuffer is generally slower than StringBuilder because of the synchronization overhead. So use StringBuffer if you need thread safety, otherwise, StringBuilder is preferred for better performance.
5. What are the different ways of creating a thread in Java?
You can create a thread in Java in two main ways:
By extending the Thread class: Create a new class that extends Thread and override its run() method. Then, create an instance of your class and call start() to begin execution.
By implementing the Runnable interface: Create a class that implements Runnable and override its run() method. You then pass an instance of your class to a Thread object and call start() on the Thread.
6. What are the different thread states?
Threads in Java can be in one of several states:
New: The thread is created but not yet started.
Runnable: The thread is eligible for running but not necessarily running.
Blocked: The thread is waiting for a monitor lock to enter a synchronized block/method.
Waiting: The thread is waiting indefinitely for another thread to perform a particular action.
Timed Waiting: The thread is waiting for a specified period of time.
Terminated: The thread has completed its execution.
7. What is HashMap in Java?
HashMap is a class in Java that implements the Map interface. It stores key-value pairs and allows for efficient retrieval of values based on keys. It uses a hash table internally, which provides fast performance for most operations, like adding, removing, and finding elements.
8. When should I use a normal HashMap and when should I use ConcurrentHashMap?
Use a normal HashMap if your application is single-threaded or if thread safety is not a concern. Use ConcurrentHashMap in a multi-threaded environment where you need thread-safe operations on the map without locking the entire map.
9. What is bucketing in HashMap?
Bucketing in HashMap refers to how HashMap organizes or stores its entries. When a key-value pair is added, HashMap calculates a hash code for the key and determines which bucket (or slot) to place the entry in. If multiple entries have the same hash code, they are stored in a linked list or tree within that bucket to handle collisions.
10. What is the difference between equals() and == in Java?
equals() is a method used to compare the contents of two objects, while == is an operator used to compare the references (memory addresses) of two objects. For instance, str1.equals(str2) checks if the contents of str1 and str2 are the same, whereas str1 == str2 checks if str1 and str2 refer to the same object in memory.
11. What is a static keyword in Java?
The static keyword is used to indicate that a particular field, method, or block belongs to the class itself rather than to instances of the class. This means you can access a static member without creating an instance of the class. For example, Math.PI is a static field, so you can use it directly via the class Math without creating a Math object.
12. What is method overloading and method overriding?
Method Overloading: This occurs when multiple methods in the same class have the same name but different parameters (type, number, or both). Overloading allows methods to perform similar tasks with different inputs.
Method Overriding: This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The overridden method must have the same name, return type, and parameters as the method in the superclass.
13. What are try, catch, finally, and throw used for in exception handling?
try: Used to enclose code that may throw an exception.
catch: Used to handle exceptions thrown by the try block.
finally: Used to execute code after the try and catch blocks, regardless of whether an exception was thrown or not. It's often used for cleanup operations.
throw: Used to explicitly throw an exception from a method or block of code.
14. What is the difference between an ArrayList and a LinkedList in Java?
ArrayList: It internally implements a resizable array, which means, like an array, it uses an index to store and access elements. It provides fast access to elements due to indexing but slows down insertion and deletion operations because elements need to be shifted.
LinkedList: It internally implements a doubly linked list. So it provides fast insertion and deletion operations because, unlike ArrayList here, no shifting is required. However, it slows down access to elements compared to `ArrayList`.
15. What is a HashSet and how is it different from a TreeSet?
HashSet: Implements the Set interface and uses a hash table for storage. It does not maintain any order for its elements and provides constant-time performance for basic operations.
TreeSet: Implements the Set interface and uses a red-black tree. It maintains elements in a sorted order and provides logarithmic time performance for basic operations.
16. What is an abstract class in Java?
17. What is an interface in Java?
An interface in Java is like a class but it doesn't contain a method body. That means it contains only method signatures (names and parameters). The class that implements the interface should provide the body of those methods in its own way, which makes the code loosely coupled.
18. What is the difference between ArrayList and Vector in Java?
19. What is garbage collection?
Garbage collection in Java is a process where the Java Virtual Machine (JVM) automatically removes objects that are no longer in use from memory. This helps manage memory efficiently and prevents memory leaks. For Example, if we create an object but no longer have any references to it, garbage collection will eventually clean it up.
20. What are synchronized methods and blocks in Java?
Synchronized Methods: Methods that are marked with the synchronized keyword, ensuring that only one thread can execute them at a time for a given object.
Synchronized Blocks: Portions of code within a method that are marked with the synchronized keyword, allowing for more fine-grained control over synchronization compared to synchronized methods.
21. What is instanceof operator in Java?
The instanceof operator is used to check whether an object is an instance of a specific class or interface. It returns true if the object is an instance of the class or implements the interface; otherwise, it returns false.
22. What is Java Reflection?
Java Reflection is a feature that allows you to inspect and manipulate classes, methods, and fields at runtime. It provides capabilities to analyze the structure of classes and objects dynamically, such as getting class names, invoking methods, and accessing fields.
23. What is a constructor in Java?
A constructor is a special method in a class that is called when an object is instantiated. It initializes the new object and can be used to set default values or perform setup operations. Constructors have the same name as the class and no return type.
24. What is a volatile keyword in Java?
The volatile keyword is used to declare a variable that can be accessed and modified by multiple threads. It ensures that the most recent value of the variable is always visible to all threads, preventing issues with caching.
25. What is the transient keyword in Java?
The transient keyword is used to indicate that a field should not be serialized. When an object is serialized, transient fields are skipped, and their values are not saved to the output stream.
26. What is the default keyword in Java interfaces?
The default keyword allows you to provide a default implementation for methods in an interface. This means that implementing classes do not need to override these methods unless they want to provide their own implementation.
27. What is the difference between throw and throws in Java?
throw: Used to explicitly throw an exception from a method or block of code.
throws: Used in a method signature to indicate that a method may throw certain exceptions. It tells the caller of the method to handle these exceptions.
28. What is the purpose of super keyword in Java?
The super keyword is used to refer to the immediate parent class of the current object. It can be used to call parent class methods, constructors, or access parent class fields.
29. What is the difference between public, protected, private, and default access modifiers?
public: The member is accessible from any other class.
protected: The member is accessible within its own package and by subclasses even if they are in different packages.
private: The member is accessible only within its own class.
Default (no modifier): The member is accessible only within its own package.
30. What are wrapper classes in Java?
Wrapper classes are used to convert primitive data types into objects. They provide methods to manipulate and convert these types. For example, Integer, Double, Character, and Boolean are wrapper classes for int, double, char, and boolean, respectively.
Spring Boot Interview Questions:
1. How do you connect to the database from my Spring Boot application?
We can connect to a database in Spring Boot application by configuring the data source in the application.properties or application.yml file. You need to specify properties like the URL, username, password, and driver class name.
For example:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2. What will be the flow of a Spring Boot application while retrieving data from a database?
The flow of a spring boot application while retrieving data from database contains following steps:
Controller: Receives the HTTP request and calls a service method.
Service: Contains the business logic and calls a repository method.
Repository: Interacts with the database using JPA or JDBC.
Database: The actual database where data is stored and retrieved from.
3. How to monitor a Spring Boot application?
Spring Boot provides the actuator to monitor an application. We can use Spring Boot Actuator to expose management endpoints that provide insights into the application's health, metrics, and environment.
4. What is @SpringBootApplication annotation used for?
The @SpringBootApplication annotation is a combination of three annotations called @Configuration, @EnableAutoConfiguration, and @ComponentScan. It is used to mark the main class of a spring boot application as a configuration class.
5. How does Spring Boot auto-configuration work?
Spring Boot auto-configuration works by analyzing the classpath and existing beans to automatically configure beans and settings. It uses @EnableAutoConfiguration to enable this feature and makes use of configuration classes and properties to adjust settings.
6. What is a Spring Boot Starter?
A Spring Boot Starter is a dependency descriptor that simplifies the inclusion of common libraries that are required to develop an application. For example, spring-boot-starter-web includes dependencies for building web applications, spring-boot-starter-data-jpa Includes dependencies for working with JPA (Java Persistence API) and to integrate our spring boot application with databases, and There are many more starter dependencies that simplifies the development process by providing a common set of functionalities.
7. What is the @Entity annotation used for in Spring Boot?
The @Entity annotation is used to mark a class as a JPA entity. This means the class will be mapped to a database table.
8. What is the purpose of @Repository annotation in Spring Boot?
The @Repository annotation indicates that a class is a data repository and is responsible for encapsulating storage, retrieval, and search behavior. It is a specialization of the @Component annotation.
9. What is Spring Boot DevTools?
Spring Boot DevTools is a set of tools to improve the development experience. It includes features like automatic restarts, live reload, and configurations for improved debugging.
10. What is Spring Boot CLI?
The Spring Boot CLI (Command Line Interface) allows you to run and test Spring Boot applications from the command line. It supports Groovy-based scripts and is useful for rapid development and prototyping.
11. How can you configure logging in a Spring Boot application?
You can configure logging in a Spring Boot application using application.properties or application.yml.
For example:
logging.level.org.springframework=DEBUG
logging.file.name=app.log
12. What are Spring Profiles?
Spring Profiles allow you to define different configurations for different environments, such as development, testing, and production. You can activate a profile using spring.profiles.active in application.properties.
13. How can you handle exceptions in a Spring Boot application?
You can handle exceptions in Spring Boot using @ControllerAdvice and @ExceptionHandler annotations to define global exception handling logic.
14. What is the role of @Autowired annotation in Spring Boot?
The @Autowired annotation is used for automatic dependency injection. It allows Spring to automatically inject the required beans into your classes.
15. What is @ComponentScan and how is it used in Spring Boot?
@ComponentScan is used to specify the base packages to scan for annotated components (like @Component, @Service, and @Repository). In Spring Boot, this is typically configured in the main application class with @SpringBootApplication.
16. What is the @Value annotation used for?
The @Value annotation is used to inject values from properties files into Spring-managed beans.
For example:
First we need to create an application.properties file and define a app name as follows: app.name=MyApp Now we can fetch this app name value in our class field using SpEL(Spring Expression Language) in spring boot code as follows:
@Value("${app.name}")
private String appName;
No comments:
Post a Comment
Share your thoughts or ask questions below!...👇