Daily Iq Spring Boot Mic
Daily Iq Spring Boot Mic
Java Basics
1. What is a constructor in Java, and why is its name similar to the class name?
A constructor in Java is a special method used to initialize objects. Its name is the same as the
class name to indicate it belongs to that class and to allow the Java compiler to automatically
invoke it when an object is created using the new keyword. It does not have a return type.
2. Why would you use a constructor over regular methods to initialize objects?
Constructor chaining is the process of calling one constructor from another within the same
class or from a parent class in a hierarchical order.
1. Within the same class: Use the this() keyword to call another constructor in the
same class.
If you provide a return type (even void) to a constructor in Java, it is treated as a regular method,
not a constructor. The compiler will no longer recognize it as a constructor, and the object
initialization will not occur automatically during object creation.
Result: The default constructor will be invoked instead, and the Student method must be
explicitly called.
Reason:
o Since constructors are not inherited, there is no need to prevent overriding, making
final redundant.
o A constructor’s role is to initialize an object, not to be overridden, so Java does not allow
final constructors.
Overriding both hashCode() and equals() is important when creating a custom class because
they work together to ensure correct behavior in collections like HashMap, HashSet, and
HashTable.
o HashMap, HashSet, and HashTable use hashCode() to determine the bucket where an
object should be stored.
o They then use equals() to check for object equality inside that bucket.
o If hashCode() is not overridden but equals() is, two equal objects may end up in different
hash buckets, leading to unexpected behavior.
o By default, equals() uses reference equality (==), but in real-world applications, we often
need logical equality (e.g., comparing objects based on their attributes).
o Overriding equals() ensures that objects with the same data are treated as equal.
o Without overriding hashCode(), HashSet may allow duplicates because different hash
codes will place logically equal objects in different locations.
o Example: If Person("Rakesh", 25) and another Person("Rakesh", 25) have different hash
codes, HashSet will store them as two different objects, violating the uniqueness
constraint.
7. What problems arise if you override only the equals method but not hashCode in a HashMap
key class?
Without overriding hashCode(), HashSet may allow duplicates because different hash codes will
place logically equal objects in different locations
8. How does hashCode improve the performance of collections like HashMap and HashSet?
This allows the collection to avoid searching the entire list of elements and instead directly
jump to the correct bucket.
Without hashCode(), a linear search (O(n)) would be needed, but with hashCode(), the
lookup is reduced to O(1) (constant time) in an ideal case.
Key Takeaways
✅ Faster lookups (O(1) in ideal cases) because objects are placed in specific
buckets
✅ Minimizes equals() calls by reducing hash collisions
✅ Optimizes rehashing and resizing for better memory efficiency
9. Can two objects have the same hashCode but not be equal? Explain with an example.
Yes, two objects can have the same hashCode() but not be equal. This situation is known as a
hash collision.
2. Different objects can have the same hashCode() due to limited integer values.
3. equals() checks content equality, while hashCode() is only used for bucketing in
collections like HashMap.
10. What is the difference between abstraction and encapsulation? How are they implemented in
Java?
Purpose Focuses on what an object does Protects data integrity and restricts
rather than how it does it. unauthorized access.
Achieved using abstract classes and Achieved using private variables with
Implementation
interfaces. public getter and setter methods.
An interface defining a draw() A class with private fields like
method for different shapes without accountBalance, accessible only via
Example
specifying how each shape is drawn. getBalance() and setBalance()
methods.
Implementation in Java
Key Points:
12. In designing a vehicle control system, when would you choose inheritance over composition?
When designing a Vehicle Control System, choosing between inheritance and composition
depends on the nature of the relationship between components.
There is a strict "is-a" relationship between the base and derived classes.
You need to dynamically change components (e.g., switch engines, GPS systems).
Objects exist Parent has child, but child Child cannot exist
Dependency
independently can exist alone without parent
Use Association → When objects interact but don’t depend on each other (e.g., User and
Bank).
Use Aggregation → When an object "has" another, but the child can exist separately (e.g.,
Team and Players).
Use Composition → When objects are fully dependent on each other (e.g., House and Rooms)
Java Features
14. What is autoboxing in Java?
15. How would you design a custom implementation of hashCode and equals for a class with
multiple fields like username, email, and date of birth?
To implement hashCode and equals properly, we need to follow the general contract provided by
the Object class in Java. These methods ensure that objects can be correctly compared for
equality and efficiently used in collections like HashMap and HashSet.
1. equals:
o Transitive: If x.equals(y) and y.equals(z) are true, then x.equals(z) should also be
true.
2. hashCode:
o If two objects are equal according to the equals method, they must have the
same hashCode.
o A good hashCode should distribute objects uniformly across the hash buckets to
minimize collisions.
1. equals Implementation:
o We should compare all fields that determine equality for the object. For the
username, email, and dateOfBirth fields, we need to check if they are equal.
2. hashCode Implementation:
o We need to generate a hash code that reflects the values of the fields. A
common approach is to use the Objects.hash() method or combine hash
codes of each field with a prime multiplier for better distribution.
Java Frameworks
16. What is the purpose of exception handling in Java?
Allows cleaner error management by separating error-handling code from normal logic.
@ControllerAdvice:
It is used for global exception handling, model attributes, and binding enhancements in
Spring MVC.
Applies to all controllers and is typically used to handle exceptions across multiple
@Controller classes.
@RestControllerAdvice:
Usage:
@RestControllerAdvice: Define global exception handling or shared logic for REST APIs.
18. How do you customize the HTTP response structure for exceptions in Spring Boot?
To customize the HTTP response structure for exceptions in Spring Boot, you can use
@ControllerAdvice or @RestControllerAdvice along with @ExceptionHandler. Here's how:
super(message);
@ExceptionHandler(CustomException.class)
errorResponse.setMessage(ex.getMessage());
errorResponse.setStatus(HttpStatus.BAD_REQUEST.value());
@ExceptionHandler(Exception.class)
errorResponse.setMessage(ex.getMessage());
errorResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
This way, you can customize the HTTP response structure, including the message, status, and
additional details for different exceptions.
20. What tools or methods have you used for logging and visualizing logs in your application?
For logging and visualizing logs in my application, I have used the following tools and methods:
1. Logging Tools:
Log Levels (INFO, DEBUG, ERROR, WARN) – For better log management.
These tools and practices ensure efficient debugging, monitoring, and troubleshooting in
distributed microservices architectures.
21. How do you secure your REST APIs? What mechanisms do you use for authentication and
authorization?
1. Authentication:
OAuth2 with Spring Security – Secure APIs with token-based authentication (Auth0,
Keycloak).
Basic Authentication – For simple use cases, but less secure.
2. Authorization:
Rate Limiting & Throttling – Limits API calls per user/IP to prevent abuse (Spring Cloud
Gateway, API Gateway).
Input Validation & Sanitization – Prevents SQL Injection and XSS attacks.
22. How does JWT (JSON Web Token) work, and how is it integrated into a Spring Boot
application?
2. Token Generation – On successful authentication, the server generates a JWT containing user
details and signs it with a secret key.
3. Token Transmission – The JWT is sent to the client, usually in the Authorization header as a
Bearer Token.
4. Token Validation – For each request, the client sends the token, and the server verifies its
signature and extracts user details.
5. Access Granted – If valid, the request is processed; otherwise, a 401 Unauthorized response is
returned.
Add Dependencies:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.11.5</version>
</dependency>
Generate JWT Token:
.setSubject(username)
.setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody();
@Bean
http.csrf().disable()
.requestMatchers("/login").permitAll()
.anyRequest().authenticated())
.addFilterBefore(new JwtAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
return http.build();
This ensures authentication and authorization using JWT in a Spring Boot application.
Spring Boot
23. What are five Spring Boot annotations you frequently use?
Five Frequently Used Spring Boot Annotations:
2. @RestController
3. @RequestMapping("/api")
5. @GetMapping("/users")
7. return userService.getAllUsers();
8. }
9. }
11. @Service
14. }
16. @Repository
19. @Service
21. @Autowired
23. }
25. @SpringBootApplication
29. }
30. }
24. What is the difference between @Service and @Repository annotations? Can they be
replaced?
Key Features:
Example:
java
@RestController
@RequestMapping("/api")
@GetMapping("/books")
Spring Data JPA allows writing custom queries using JPQL, native SQL, or @Query
32. Have you worked with indexing in JPA? How does it improve query performance?
Messaging Systems
33. Have you used any messaging systems? Which ones, and for what purpose?
35. What is the difference between mvn clean, mvn install, and mvn deploy commands in Maven?
36. What is your branching strategy in Git? How do you handle conflicts?
38. What is the difference between git merge and git rebase?
Caching
39. Have you used caching in your project? How does it improve performance?
Miscellaneous
40. How do you handle asynchronous methods? Have you written exception handling for
asynchronous methods?
41. What are some differences between synchronous and asynchronous methods?
42. What tools or strategies do you use to track and visualize logs in your application?
EPAM
1. What is the Saga pattern?
2. Which Java version do you use in your current project?
3. Can you tell me some new features of Java 11 which are not there in older versions?
4. Can you tell me about singleton classes?
5. How can we create singleton classes?
6. Are these threads safe?
7. How will you create a thread-safe singleton in Java using double check locking?
8. Why is the main method public and static?
9. Can we override the main method?
10. Do you know about serialized data?
11. Why shouldn't we serialize data into a text file?
12. What happens if your serializable class contains a member that is not serializable and
how will you fix it?
13. What is transient?
14. How does garbage collection work in Java?
15. Does finalize keyword have any role in garbage collection?
16. What algorithm does JVM use for garbage collection?
17. How can memory leaks occur in Java even when we have automatic garbage
collection?
18. Can you tell me the difference between Young Generation and old generation memory
spaces?
19. How do you ensure the quality and maintainability of your code in your project?
20. If you observe that a Spring Boot application performs slower in the production
environment compared to the development setup, what steps would you take to
address this issue?
21. Can you tell me how do you integrate a relational database like MySQL with a Spring
Boot application?
22. How would you modify an existing Spring Boot application to convert it into a
serverless architecture?
23. Can you tell me how does Spring Boot make the decision on which server to use?
24. How would you handle exceptions in a Spring Boot REST application?
25. How can we handle multiple beans of the same type?
26. Can you tell me what is aspect-oriented programming in the Spring framework?
Delloite ROUND 2:
Here are concise and impactful answers for your L2 interview preparation:
1️ How to create a fixed thread pool in multithreading?
A fixed thread pool creates a pool of a fixed number of worker threads to execute tasks.
✅ Implementation using Executors.newFixedThreadPool():
import java.util.concurrent.*;
Definition Verifies who you are Verifies what you can access
Example Login with credentials Checking if user can access admin panel
1️7️ If There Are Four Consumers in a Consumer Group and Three Partitions, What Happens?
Kafka distributes partitions among consumers.
3 consumers get 1 partition each, the 4th consumer remains idle (since there are no
extra partitions).
1️9️ How to Get the Third-Highest Salary from the Employee Table in SQL?
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
🔹 OFFSET 2 skips the top 2 salaries, fetching the third-highest.
1. What is the importance of the equals method while adding keys to a HashMap?
In a HashMap, the equals method is used to determine key uniqueness. When inserting
a key-value pair, HashMap:
1. Computes the key's hashCode to find the bucket.
2. Iterates through the bucket’s linked list (in case of collisions) and uses equals() to
check if the key already exists.
3. If equals() returns true, the value is updated instead of inserting a new key.
If equals() is not properly implemented, duplicate keys may exist, leading to unexpected
behavior.
4. What is the difference between a Singleton class and the Singleton design pattern?
A Singleton class is any class with only one instance at a time.
The Singleton pattern is a design pattern that provides a structured way to enforce a
single instance in an application.
✅ Example:
Runtime.getRuntime() in Java follows the Singleton pattern but is not a Singleton class
because multiple runtimes can exist in some environments.
private Singleton() {}
6. What is the volatile keyword, and how does it ensure visibility across threads?
The volatile keyword prevents thread caching of variables and ensures visibility across
threads by always reading from main memory instead of CPU caches.
Without volatile, one thread’s changes may not be visible to another immediately due
to CPU-level caching.
7. If two threads increment a shared volatile counter variable, will it guarantee
correctness? Why?
✅ Incorrect Approach:
✅ Example:
java
CopyEdit
Map<String, String> map = new ConcurrentHashMap<>();
map.put("key1", "value1");
Why are we still using Java 8 apart from the latest versions?
Why only Java 8 apart from Java 17?
Any major blockers you found while moving from Java 8 to Java 11?
Deprecated features comparing Java 8 to Java 11?
What are the Java 11 upgrades?
What are the garbage collector upgrades?
Performance metrics between API and microservices?
What is JMeter?
When you checked performance in Java 8, was there any metric difference over Java 11?
Did you customize load balancing in the API?
Difference between Factory Design Pattern and Abstract Factory?
Structural differences between Factory and Abstract Factory?
Is a single product interface used for Factory Pattern?
Write an SQL query to group employees by department based on experience.
Write an SQL query to group employees by department based on experience, with the highest
experience at the top.
Why are we grouping by department ID in the SQL query?
Write an SQL query to get emp_id, emp_name, experience, and department name.
Write a Hibernate-based query for the employee and department relation.
If an entity model class has parameters like createdBy and updatedBy, is it possible to manage
them automatically?
What is AngularJS?
What is Angular?
What are decorators in Angular?
What are observers in Angular?
How do you detect any changes and recompile/redeploy locally?
What is lazy loading in Angular?
What are zones in Angular?
What is state management in Angular?
Write Java code to find the maximum number of subarrays possible from an array [1,2,3,4].
Another way to find the maximum number of subarrays?
Modify the Java code to print all subarrays.
Modify the Java code to print all subarrays with more numbers.
How can we get only subarrays containing 1 and 7?