0% found this document useful (0 votes)
13 views

Daily Iq Spring Boot Mic

The document provides a comprehensive overview of Java concepts, including constructors, object-oriented programming principles, and exception handling. It explains key topics such as constructor chaining, the importance of overriding hashCode and equals methods, and the differences between abstraction and encapsulation. Additionally, it covers Java frameworks, logging practices, and security mechanisms for REST APIs, including JWT integration in Spring Boot applications.

Uploaded by

Rakesh Mirchi
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)
13 views

Daily Iq Spring Boot Mic

The document provides a comprehensive overview of Java concepts, including constructors, object-oriented programming principles, and exception handling. It explains key topics such as constructor chaining, the importance of overriding hashCode and equals methods, and the differences between abstraction and encapsulation. Additionally, it covers Java frameworks, logging practices, and security mechanisms for REST APIs, including JWT integration in Spring Boot applications.

Uploaded by

Rakesh Mirchi
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/ 33

INTERVIEW 1:

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?

A constructor is preferred over regular methods for initializing objects because it is


automatically called when an object is created, ensuring that the object is initialized
properly at the time of instantiation. This eliminates the need to call a separate
initialization method manually, improving code reliability and reducing errors.

3. What is constructor chaining? How can it be achieved?

Constructor chaining is the process of calling one constructor from another within the same
class or from a parent class in a hierarchical order.

How it can be achieved:

1. Within the same class: Use the this() keyword to call another constructor in the
same class.

2. In a parent-child relationship: Use the super() keyword to call a parent class


constructor.

Purpose: It reduces code duplication and ensures consistent initialization.

4. What happens if you provide a return type to a constructor?

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.

5. Can we make a constructor final? Why or why not?

No, we cannot make a constructor final in Java.

Reason:

1. Constructors cannot be inherited –

o The final keyword is used to prevent method overriding in subclasses.

o Since constructors are not inherited, there is no need to prevent overriding, making
final redundant.

2. Final applies to methods and variables, not constructors –

o The final keyword is meant to restrict modifications to methods (prevent overriding)


and variables (make them constant).

o A constructor’s role is to initialize an object, not to be overridden, so Java does not allow
final constructors.

Object-Oriented Programming (OOP)


6. Why is it important to override both hashCode and equals methods when creating a custom
class?

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.

Why Should You Override Both?


1. Consistency in Hash-Based Collections

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.

2. Ensuring Logical Equality

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.

3. Preventing Duplicate Entries in Hash-Based Collections

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?

1. Enables Faster Lookup in HashMap and HashSet

 When an object is added to a HashMap or HashSet, its hashCode() is used to determine


the bucket (index) where it should be stored.

 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.

Why Does This Happen?

1. hashCode() only generates an integer and does not guarantee uniqueness.

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?

Feature Abstraction Encapsulation


Definition Hides implementation details and Hides internal data by restricting direct
Feature Abstraction Encapsulation
access and provides controlled access via
exposes only the required
methods.
functionality.

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

11. Explain runtime polymorphism with an example.

Runtime polymorphism in Java is achieved through method overriding, where a subclass


provides a specific implementation of a method that is already defined in its parent class. The
method to be executed is determined at runtime based on the object's actual type, not the
reference type.

Key Points:

 Achieved using method overriding.

 Uses dynamic method dispatch (method binding happens at runtime).

 Enables loose coupling and enhances maintainability.

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.

Use Inheritance When:

 There is a strict "is-a" relationship between the base and derived classes.

 You want to reuse common behavior and enforce a hierarchical structure.

 The child class is fundamentally a specialized version of the parent class.

 The behavior remains largely unchanged across different vehicle types.

Use Composition When:


 There is a "has-a" relationship rather than an "is-a" relationship.

 You want more flexibility and avoid deep inheritance hierarchies.

 You need to dynamically change components (e.g., switch engines, GPS systems).

 Behavior can be shared across multiple classes without forcing a hierarchy.

13. What is the difference between aggregation, composition, and association?

Aggregation (Weak Composition (Strong


Feature Association (General)
Ownership) Ownership)

Type "Uses-a" "Has-a" "Part-of"

Objects exist Parent has child, but child Child cannot exist
Dependency
independently can exist alone without parent

Coupling Loose Moderate Tight

Example Student ↔ College Department → Professors Car → Engine

Child can exist after parent Child is deleted if


Lifespan No dependency
deletion parent is deleted

✅ When to Use What?

 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?

Autoboxing is the automatic conversion of primitive types to their corresponding wrapper


class objects by the Java compiler.
In Java, primitive types (like int, char, double, etc.) and their corresponding wrapper classes
(like Integer, Character, Double, etc.) are different types. Autoboxing allows seamless
conversion between these two, so you don't have to manually wrap primitives into objects or
unbox them back.

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.

Contract of hashCode and equals:

1. equals:

o Reflexive: x.equals(x) should return true.

o Symmetric: If x.equals(y) is true, then y.equals(x) should also be true.

o Transitive: If x.equals(y) and y.equals(z) are true, then x.equals(z) should also be
true.

o Consistent: Repeated calls to x.equals(y) should consistently return the same


result.

o null: x.equals(null) should return false.

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.

Steps to Design Custom hashCode and equals:

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?

Purpose of Exception Handling in Java:

 To manage runtime errors, preventing program crashes.

 Ensures the normal flow of the application by handling unexpected situations.

 Allows cleaner error management by separating error-handling code from normal logic.

 Improves program robustness and maintainability.

17. What is @ControllerAdvice and @RestControllerAdvice? How are they used?

@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:

 It is a specialized version of @ControllerAdvice, specifically for @RestController.

 Automatically applies @ResponseBody to methods, making it suitable for RESTful APIs.

Usage:

 @ControllerAdvice: Define global exception handling or shared logic for controllers.

 @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:

1. Create a custom exception class (optional):

public class CustomException extends RuntimeException {

public CustomException(String message) {

super(message);

2. Create a response structure:

public class ErrorResponse {

private String message;

private String details;

private int status;

// Getters and Setters

3. Global exception handler using @ControllerAdvice:


@RestControllerAdvice

public class GlobalExceptionHandler {

@ExceptionHandler(CustomException.class)

public ResponseEntity<ErrorResponse> handleCustomException(CustomException ex) {

ErrorResponse errorResponse = new ErrorResponse();

errorResponse.setMessage(ex.getMessage());

errorResponse.setDetails("Custom exception occurred");

errorResponse.setStatus(HttpStatus.BAD_REQUEST.value());

return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);

@ExceptionHandler(Exception.class)

public ResponseEntity<ErrorResponse> handleException(Exception ex) {

ErrorResponse errorResponse = new ErrorResponse();

errorResponse.setMessage(ex.getMessage());

errorResponse.setDetails("An error occurred");

errorResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());

return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);

This way, you can customize the HTTP response structure, including the message, status, and
additional details for different exceptions.

19. How would you handle specific exceptions like EntityNotFoundException or


ConstraintViolationException with customized responses?
To handle specific exceptions like EntityNotFoundException or ConstraintViolationException with
customized responses in Spring Boot, use @RestControllerAdvice with @ExceptionHandler.
Here's how:

1. Define a Common Error Response Structure


2. Create a Global Exception Handler
3. Throw Exceptions in Service Layer

This ensures that EntityNotFoundException and ConstraintViolationException return


structured JSON responses with meaningful messages and appropriate HTTP status codes.

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:

 SLF4J with Logback – Standard logging framework for Spring Boot.

 Log4j2 – Alternative for Logback with better performance and features.

 Spring Boot Actuator Logs – Provides endpoints to monitor logs.

2. Log Visualization Tools:

 ELK Stack (Elasticsearch, Logstash, Kibana) – Centralized logging and visualization.

 Graylog – Used for real-time log analysis and searching.

 Splunk – Enterprise-level log monitoring and analytics.

3. Logging Best Practices:

 Structured Logging (JSON format) – Helps in parsing logs easily.

 Log Levels (INFO, DEBUG, ERROR, WARN) – For better log management.

 Correlation IDs – Useful for tracking requests across microservices.

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?

To secure REST APIs, I use the following mechanisms:

1. Authentication:

 JWT (JSON Web Token) – Stateless authentication using token-based security.

 OAuth2 with Spring Security – Secure APIs with token-based authentication (Auth0,
Keycloak).
 Basic Authentication – For simple use cases, but less secure.

2. Authorization:

 Role-Based Access Control (RBAC) – Restricts access based on user roles.

 Spring Security Annotations – @PreAuthorize, @PostAuthorize, @Secured, and


@RolesAllowed.

3. Other Security Measures:

 HTTPS (SSL/TLS) – Encrypts data during transmission.

 CORS (Cross-Origin Resource Sharing) Control – Prevents unauthorized cross-origin


requests.

 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?

How JWT Works:

1. User Authentication – The client sends credentials (username/password) to the authentication


server.

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.

Integration in Spring Boot:

 Add Dependencies:
<dependency>

<groupId>io.jsonwebtoken</groupId>

<artifactId>jjwt</artifactId>

<version>0.11.5</version>

</dependency>
 Generate JWT Token:

String token = Jwts.builder()

.setSubject(username)

.setIssuedAt(new Date())

.setExpiration(new Date(System.currentTimeMillis() + 3600000))

.signWith(SignatureAlgorithm.HS256, SECRET_KEY)

.compact();

 Validate JWT in a Filter:

Claims claims = Jwts.parser()

.setSigningKey(SECRET_KEY)

.parseClaimsJws(token)

.getBody();

String username = claims.getSubject();

 Secure APIs using Spring Security:

@Bean

public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

http.csrf().disable()

.authorizeHttpRequests(auth -> auth

.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:

1. @RestController – Combines @Controller and @ResponseBody to handle REST APIs.

2. @RestController

3. @RequestMapping("/api")

4. public class UserController {

5. @GetMapping("/users")

6. public List<User> getUsers() {

7. return userService.getAllUsers();

8. }

9. }

10. @Service – Marks a class as a service component in the business layer.

11. @Service

12. public class UserService {

13. public List<User> getAllUsers() { return userRepository.findAll(); }

14. }

15. @Repository – Indicates a DAO layer for database operations.

16. @Repository

17. public interface UserRepository extends JpaRepository<User, Long> { }

18. @Autowired – Injects dependencies automatically.

19. @Service

20. public class UserService {

21. @Autowired

22. private UserRepository userRepository;

23. }

24. @SpringBootApplication – Enables Spring Boot auto-configuration, component scanning, and


configuration.

25. @SpringBootApplication

26. public class Application {

27. public static void main(String[] args) {


28. SpringApplication.run(Application.class, args);

29. }

30. }

24. What is the difference between @Service and @Repository annotations? Can they be
replaced?

25.Difference Between @Service and @Repository:

Annotation Purpose Key Features


Marks a service
layer
@Service component Used for implementing business logic.
handling
business logic.
Marks a DAO
(Data Access Provides exception translation for database errors via
@Repository Object) for Spring’s
database PersistenceExceptionTranslationPostProcessor.
interactions.

Can They Be Replaced?


Yes, technically they can be interchanged since both are meta-annotated with
@Component, allowing Spring to detect them as beans. However, using them correctly
improves code readability and intent clarity.

26. What is the purpose of the @RestController annotation?

@RestController Annotation Purpose

@RestController is a Spring Boot annotation that combines @Controller and @ResponseBody. It


is used to create RESTful web services by returning JSON or XML responses directly.

Key Features:

 Eliminates the need for @ResponseBody on each method.

 Automatically serializes Java objects into JSON/XML.

 Typically used in microservices to expose APIs.

Example:

java
@RestController

@RequestMapping("/api")

public class BookController {

@GetMapping("/books")

public List<Book> getBooks() {

return List.of(new Book(1, "Spring Boot"), new Book(2, "Microservices"));

Here, the getBooks() method directly returns a JSON list of books.

27. How do you write custom queries in Spring Data JPA?

Custom Queries in Spring Data JPA

Spring Data JPA allows writing custom queries using JPQL, native SQL, or @Query

28.1. Using @Query Annotation (JPQL)


29.public interface BookRepository extends JpaRepository<Book, Long> {
30.
31. @Query("SELECT b FROM Book b WHERE b.title = :title")
32. List<Book> findByTitle(@Param("title") String title);
33.}
34.2. Using Native Query
35.@Query(value = "SELECT * FROM books WHERE title = :title", nativeQuery
= true)
36.List<Book> findByTitleNative(@Param("title") String title);
37.3. Using Derived Query Methods
38.List<Book> findByAuthor(String author);
39. Spring Data automatically generates the SQL query based on the method name.

Spring Boot API Testing


27. Have you written test cases for APIs? Which tools or frameworks have you used?

28. What version of JUnit do you use, and why?

29. How do you achieve code coverage in your tests?


Databases
30. Would you use Hibernate or JDBC for database operations? Why?

31. What is the difference between HQL and JPQL?

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?

Development Tools and Processes

34. What is the purpose of the .m2 folder in Maven?

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?

37. What is the purpose of the git cherry-pick command?

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.*;

public class FixedThreadPoolExample {


public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i = 1; i <= 5; i++) {


final int taskId = i;
executor.execute(() -> System.out.println("Executing Task " + taskId + " by " +
Thread.currentThread().getName()));
}

executor.shutdown(); // Gracefully shut down the executor


}
}
🔹 Use Case: Useful when a fixed number of threads is required, preventing excessive thread
creation.

2️ Explain TreeSet and TreeMap.


 TreeSet: A sorted set that maintains elements in ascending order (Red-Black Tree).
 TreeMap: A sorted map that maintains key-value pairs in ascending key order (Red-
Black Tree).
✅ Example:
TreeSet<Integer> treeSet = new TreeSet<>(Arrays.asList(5, 3, 8, 1));
System.out.println(treeSet); // Output: [1, 3, 5, 8]

TreeMap<Integer, String> treeMap = new TreeMap<>();


treeMap.put(2, "B");
treeMap.put(1, "A");
System.out.println(treeMap); // Output: {1=A, 2=B}

3️ Internal Data Structure of TreeSet and TreeMap


Both use Red-Black Tree, a self-balancing binary search tree:
🔹 TreeSet → Stores elements in a sorted tree structure.
🔹 TreeMap → Stores key-value pairs with keys sorted using Red-Black Tree.
🔹 Operations like insert, delete, and search run in O(log n) time.

4️ Explain microservices communication asynchronously.


Microservices communicate asynchronously using message brokers like Kafka, RabbitMQ, or
JMS.
✅ Example with Kafka:
 Producer sends messages to a Kafka topic.
 Consumer listens to the topic and processes messages.
🔹 Advantages: Decoupling, scalability, fault tolerance.

5️ How do we implement Spring Security?


Spring Security is implemented by configuring authentication and authorization using filters
or security configurations.
✅ Basic Implementation:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
.formLogin().and().httpBasic();
return http.build();
}
}
🔹 Spring Boot provides built-in security by default requiring authentication.

6️ Difference between Authentication and Authorization in Security

Feature Authentication Authorization

Definition Verifies who you are Verifies what you can access

Focus Login credentials (username, password) Permissions (roles, access control)

Example Login with credentials Checking if user can access admin panel

7️ How do we implement caching in Java?


✅ Using Spring Boot with @Cacheable:
@Cacheable("products")
public Product getProductById(Long id) {
return productRepository.findById(id).orElse(null);
}
🔹 Backends: EhCache, Redis, Hazelcast, Caffeine.

8️ What are views in databases?


A view is a virtual table based on an SQL query. It does not store data but simplifies complex
queries.
✅ Example:
CREATE VIEW employee_view AS
SELECT id, name, salary FROM Employee WHERE salary > 50000;

9️ Limitations of Views in Databases


 Cannot have indexes.
 Cannot perform INSERT, UPDATE, DELETE on complex views.
 Performance overhead if used inefficiently.

🔟 How to Create a View in SQL?


CREATE VIEW high_salary_employees AS
SELECT name, salary FROM Employee WHERE salary > 60000;

11 How to Modify a View in SQL?


CREATE OR REPLACE VIEW high_salary_employees AS
SELECT name, salary, department FROM Employee WHERE salary > 70000;

1️2️Types of Views in Databases


1. Simple View → Based on a single table.
2. Complex View → Based on multiple tables with joins.
3. Materialized View → Stores actual data for faster queries.

1️3️Difference between a View and a Materialized View

Feature View Materialized View

Storage Virtual (no data stored) Physically stores data

Performance Slower (query runs each time) Faster (precomputed results)

Use Case Simplify queries Optimize read-heavy operations

1️4️When Would You Use Views in SQL?


 Simplify complex queries.
 Restrict access to specific columns.
 Provide a layer of abstraction for underlying tables.

1️5️Kafka Followers and Observers


 Followers → Replicate data from a leader partition but can become leaders.
 Observers → Read-only replicas used for scaling, cannot become leaders.

1️6️ Explain Consumer Groups in Kafka


A consumer group allows multiple consumers to read from the same topic, distributing
partitions among them.
✅ Example: If a topic has 3 partitions and 3 consumers in a group, each consumer reads from
one partition.

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️8️ How Do You Implement Kafka in a System?


1. Producer sends messages to a Kafka topic.
2. Broker stores messages in partitions.
3. Consumer reads messages from partitions.
4. Consumer groups ensure scalability.
✅ Spring Boot Kafka Example:
@KafkaListener(topics = "orders", groupId = "order-group")
public void consume(String message) {
System.out.println("Received: " + message);
}

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.

2️0️What is the AutoCloseable Interface in Java?


AutoCloseable allows objects to be closed automatically when used inside a try-with-
resources block.
✅ Example:
class Resource implements AutoCloseable {
public void use() { System.out.println("Using resource"); }
public void close() { System.out.println("Resource closed"); }
}

public class Test {


public static void main(String[] args) {
try (Resource r = new Resource()) {
r.use();
}
}
}
Output:
Using resource
Resource closed
🔹 Ensures automatic resource cleanup.

2️1️Methods in the AutoCloseable Interface


void close() throws Exception;
🔹 Only one method, close(), which is called when the resource is closed.

Java Core Concepts

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.

2. What happens if you override equals without overriding hashCode in a HashMap?


If hashCode() is not overridden while equals() is changed, HashMap may place logically
equal keys in different buckets, causing:
 Duplicate entries for what should be the same key.
 Unexpected retrieval failures due to mismatched hash codes.
@Override
public int hashCode() {
return name.hashCode();
}
3. What is the Singleton design pattern, and where have you used it?
The Singleton pattern ensures a class has only one instance and provides a global access
point to it.
✅ Use Cases:
 Database connection pools
 Logging frameworks
 Caching mechanisms
 Spring Beans (@Service, @Repository)
✅ Example (Eager Initialization):
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {} // Private constructor prevents instantiation
public static Singleton getInstance() { return INSTANCE; }
}

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.

5. How can we create a Singleton class in a thread-safe manner?


To make a Singleton thread-safe, use Double-Checked Locking or Bill Pugh’s method.

✅ Double-Checked Locking (Thread-Safe Singleton):


public class Singleton {
private static volatile Singleton instance;

private Singleton() {}

public static Singleton getInstance() {


if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
✅ Bill Pugh’s Singleton (Recommended):
public class Singleton {
private Singleton() {}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}

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?

No, volatile does NOT guarantee atomicity.

🔹 volatile ensures visibility, but does not prevent race conditions.


🔹 Multiple threads can read the same value, increment it, and overwrite each other’s
changes.

✅ Incorrect Approach:

private volatile int count = 0;


public void increment() { count++; } // Not atomic!

✅ Correct Approach (Use AtomicInteger or Synchronization):

private AtomicInteger count = new AtomicInteger(0);


public void increment() { count.incrementAndGet(); } // Thread-safe

8. What is the difference between HashMap and ConcurrentHashMap?

Feature HashMap ConcurrentHashMap


Thread-Safety 🚫 Not thread-safe ✅ Thread-safe
✅ Fast (Single-
Performance 🚀 Optimized for multi-threading
threaded)
Uses segment-based locking (bucket-
Locking Mechanism No locks
level)
Allows null
✅ Yes 🚫 No
keys/values?

✅ Example:

java
CopyEdit
Map<String, String> map = new ConcurrentHashMap<>();
map.put("key1", "value1");

🔹 ConcurrentHashMap avoids full map locking, making it faster in multi-threaded


environments.

9. Can switching to ConcurrentHashMap from HashMap solve a


ConcurrentModificationException?
✅ Yes, in most cases!

🔹 HashMap fails if a thread modifies it while another thread iterates, leading to


ConcurrentModificationException.
🔹 ConcurrentHashMap allows modifications during iteration without exceptions.

✅ Example (Failing with HashMap)

Map<String, String> map = new HashMap<>();


map.put("A", "1");
for (String key : map.keySet()) {
map.put("B", "2"); // Throws ConcurrentModificationException
}

✅ Solution using ConcurrentHashMap

Map<String, String> map = new ConcurrentHashMap<>();


map.put("A", "1");
for (String key : map.keySet()) {
map.put("B", "2"); // No exception
}

🔹 However, ConcurrentHashMap does not allow structural modifications like resizing


while iterating.

Multithreading & Concurrency


10. How does the Java garbage collection mechanism work?
11. If an application suffers from frequent GC pauses, how would you optimize it?
12. What are functional interfaces in Java?
13. What is the difference between Runnable and Callable interfaces?
14. Which interface (Runnable or Callable) would you use if a task needs to return a result
or throw an exception?
15. What is the BiFunction interface, and where can it be used?

Spring Boot & Microservices


16. What are five best practices to follow when creating REST APIs?
17. How do you perform API versioning in RESTful web services?
18. What should be the HTTP status code for successfully deleting data from an API?
19. How would you implement Spring Security in an application?
20. How do you prevent CSRF attacks and ensure only authorized users can access certain
endpoints?
21. How do you handle logging in microservices?
22. How do you track a single request across multiple microservices?
23. How do you configure and connect multiple databases in a Spring Boot application?
24. What techniques do you use to improve query performance in JPA?
25. How do you implement caching in Spring Boot?
26. How do you use Spring Boot Actuator for monitoring?
27. How do you create a custom health indicator for monitoring third-party APIs?
28. What is Spring Boot Auto-Configuration, and how does it work?
29. How can you disable a specific auto-configuration in Spring Boot?
30. How do you implement global exception handling in a Spring Boot REST API?
31. What are the different scopes of Spring Beans?
32. When would you use request scope over singleton scope?
33. How do you optimize a Spring Boot application?

Database & SQL


34. What are views in SQL, and how do you create one?
35. What are the limitations of using views?
36. How do you modify a view in SQL?
37. What is the difference between a view and a materialized view?
38. How would you retrieve the third-highest salary from an Employee table?

Kafka & Messaging


39. What are Kafka followers and observers?
40. Explain consumer groups in Kafka.
41. If there are four consumers in a consumer group and three partitions, what happens?
42. How do you implement Kafka in a system?

DevOps & CI/CD


43. What is the .m2 folder in Maven?
44. What is the difference between Maven and Gradle?
45. What is your Git branching strategy in your project?
46. How do you resolve merge conflicts in Git?

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?

You might also like