Core Java - Company Based Int Qus

Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 177

# Technical Round

1. **Explain your recent project.**


- *Provide details about your recent project, including the technology stack, your
role, the objectives, challenges faced, and how you overcame those challenges.*

2. **What are the new features in Java 8?**


- *Java 8 introduced several new features, including:*
- *Lambda expressions*
- *Functional interfaces*
- *Stream API*
- *New Date and Time API (java.time)*
- *Default methods in interfaces*
- *Method references*
- *Optional class*

3. **What is a static method in Java?**


- *A static method belongs to the class rather than instances of the class. It can
be called without creating an instance of the class.*

4. **How can we use static methods in an interface?**


- *Static methods in interfaces can be used to provide utility methods that are
related to the interface but do not need an instance. They are called using the
interface name.*

5. **How can we call a static method?**


- *Static methods can be called using the class name or the interface name if
defined in an interface, e.g., `ClassName.staticMethod()` or
`InterfaceName.staticMethod()`.*

6. **How many ways can we call static methods?**


- *Static methods can be called in two ways:*
- *Using the class name (e.g., `Math.sqrt(4)` for `Math.sqrt`)*
- *Directly if in the same class (e.g., `staticMethod()`)*

7. **What is a default method in Java?**


- *Default methods are methods in interfaces that have a body. They provide a
default implementation that can be used by implementing classes.*

8. **What is the use of default methods in interfaces?**


- *Default methods allow interfaces to evolve without breaking existing
implementations. They enable the addition of new methods with default behavior.*

9. **What is a method reference in Java?**


- *Method references are a shorthand notation for calling a method. They provide
a way to refer to methods without invoking them.*

10. **How many ways can we create method references?**


- *Method references can be created in the following ways:*
- *Reference to a static method*
- *Reference to an instance method of a specific object*
- *Reference to an instance method of an arbitrary object*
- *Reference to a constructor*

11. **Provide a customized example of a method reference with full code and
explanation.**

```java
import java.util.Arrays;
import java.util.List;

public class MethodReferenceExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Using method reference to call static method


names.forEach(MethodReferenceExample::printName);

// Using method reference to call instance method


MethodReferenceExample instance = new MethodReferenceExample();
names.forEach(instance::printNameInstance);
}

// Static method
public static void printName(String name) {
System.out.println(name);
}

// Instance method
public void printNameInstance(String name) {
System.out.println(name);
}
}
```

12. **What is a stream in Java?**


- *A stream in Java is a sequence of elements supporting sequential and parallel
aggregate operations. It is used for processing collections of objects in a functional
style.*

13. **What is a parallel stream?**


- *A parallel stream is a type of stream that enables parallel processing of data
by splitting the data into multiple chunks and processing them concurrently.*

14. **What is the difference between a stream and a parallel stream?**


- *A stream processes data sequentially, while a parallel stream divides the data
into multiple chunks and processes them concurrently using multiple threads.*

15. **How does the internal process work in parallel streams?**


- *Parallel streams use the ForkJoinPool to split the data into smaller chunks,
process them concurrently in multiple threads, and then merge the results.*
16. **How many ways can we create a thread in Java?**
- *Threads can be created in two main ways:*
- *By implementing the `Runnable` interface*
- *By extending the `Thread` class*

17. **Provide example code for implementing the `Runnable` interface and explain
how to use it.**

```java
public class RunnableExample implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}

public static void main(String[] args) {


RunnableExample runnable = new RunnableExample();
Thread thread = new Thread(runnable);
thread.start();
}
}
```

18. **If `MyThread` implements `Runnable`, and I create a thread like this: `Thread t
= new Thread(new MyThread())`, how is this different from extending the `Thread`
class?**
- *Implementing `Runnable` allows you to use composition and separate the
thread's job from its execution. Extending `Thread` tightly couples the thread's job
with its execution, limiting flexibility.*

19. **What is `ExecutorService` in threads?**


- *`ExecutorService` is a high-level replacement for managing and controlling
thread execution. It provides methods for managing a pool of threads and scheduling
tasks.*

20. **How many ways can we create an `ExecutorService`?**


- *`ExecutorService` can be created using:*
- *`Executors.newFixedThreadPool(int nThreads)`*
- *`Executors.newSingleThreadExecutor()`*
- *`Executors.newCachedThreadPool()`*
- *`Executors.newScheduledThreadPool(int corePoolSize)`*

21. **What is autowiring in Spring?**


- *Autowiring is a feature in Spring that allows the framework to automatically
inject dependencies into a bean.*

22. **How many modes of autowiring are there?**


- *Autowiring modes include:*
- *`@Autowired` (by type)*
- *`@Qualifier` (by name)*
- *`@Resource` (by name)*
- *`@Inject` (by type)*

24. **Explain `@Qualifier` and `@Inject`.**


- *`@Qualifier` is used to provide specific beans when multiple candidates are
available. `@Inject` is a Java standard annotation used to inject dependencies.*

25. **What is the difference between `@Autowired` and `@Qualifier`?**


- *`@Autowired` is used for automatic injection by type, while `@Qualifier` is
used in conjunction with `@Autowired` to specify which bean to inject when multiple
beans are available.*

26. **Can we use `@Autowired` in place of `@Qualifier`?**


- *`@Autowired` alone cannot specify which bean to inject if there are multiple
candidates. `@Qualifier` is needed to resolve such ambiguities.*

27. **What are the limitations of autowiring?**


- *Limitations include:*
- *Ambiguity when multiple beans of the same type are available.*
- *Difficulty in identifying dependencies at runtime.*
- *Inability to inject beans based on dynamic conditions.*

28. **What is Spring Security?**


- *Spring Security is a framework that provides comprehensive security services
for Java applications, including authentication, authorization, and protection against
various security threats.*

29. **How do you configure Spring Security?**


- *Spring Security can be configured using:*
- *Java configuration with `@EnableWebSecurity` and `SecurityConfig`
classes.*
- *XML configuration (less common in recent versions).*

30. **What is JWT token-based authentication?**


- *JWT (JSON Web Token) token-based authentication is a method where
authentication information is transmitted as a JSON object and is used to verify the
identity of users.*

31. **How many ways can you configure custom security?**


- *Custom security can be configured using:*
- *Java-based configuration with `SecurityConfigurerAdapter`*
- *Custom filters and handlers*
- *Spring Security extensions*

32. **What is an API gateway?**


- *An API gateway is a server that acts as an API front-end, receiving API
requests, enforcing throttling, routing requests, and aggregating results.*

33. **How to implement an API gateway? Which dependency is needed?**


- *To implement an API gateway, you can use tools like Spring Cloud Gateway or
Netflix Zuul. Dependencies needed include:*
- *`spring-cloud-starter-gateway` for Spring Cloud Gateway*
- *`zuul` for Netflix Zuul*

34. **What is load balancing?**


- *Load balancing distributes incoming network traffic across multiple servers to
ensure no single server becomes overwhelmed, enhancing reliability and
performance.*

35. **How do you implement load balancing in microservices?**


- *Load balancing in microservices can be implemented using:*
- *Client-side load balancing with libraries like Ribbon*
- *Server-side load balancing with tools like Nginx or HAProxy*

36. **What is fault tolerance?**


- *Fault tolerance refers to the ability of a system to continue operating properly
in the event of a failure of some of its components.*

37. **How do you handle fault tolerance?**


- *Fault tolerance can be handled using:*
- *Redundancy and failover strategies*
- *Circuit breakers (e.g., using Resilience4j)*
- *Retry mechanisms and fallback methods*

38. **What is a circuit breaker

?**
- *A circuit breaker is a design pattern that prevents a system from making calls
to a failing service, allowing it to recover and preventing cascading failures.*

39. **How do you implement a circuit breaker?**


- *A circuit breaker can be implemented using libraries like:*
- *Resilience4j*
- *Hystrix*

40. **What is the design pattern for a circuit breaker?**


- *The circuit breaker pattern consists of three states:*
- *Closed (normal operation)*
- *Open (service is failing)*
- *Half-Open (test if the service has recovered)*

41. **How do you handle limits in a circuit breaker?**


- *Limits in a circuit breaker can be handled by:*
- *Setting thresholds for failure rates*
- *Defining timeout durations for service calls*
- *Configuring retry and fallback mechanisms*

42. **What are the features of RESTful web services?**


- *Features include:*
- *Stateless communication*
- *Resource-based URLs*
- *Standard HTTP methods (GET, POST, PUT, DELETE)*
- *JSON or XML responses*
- *HTTP status codes for responses*

43. **What are the available HTTP status codes, and why are they important?**
- *Common HTTP status codes include:*
- *200 OK*
- *201 Created*
- *204 No Content*
- *400 Bad Request*
- *401 Unauthorized*
- *404 Not Found*
- *500 Internal Server Error*
- *They are important for indicating the result of an HTTP request and guiding
client-side behavior.*

44. **Which database are you using?**


- *Provide the name of the database you are using (e.g., MySQL, PostgreSQL,
MongoDB) and any relevant details about its configuration and usage.*

45. **Write a query to get the username when the name starts with 'A' and ends with
'E'.**

```sql
SELECT username
FROM users
WHERE name LIKE 'A%E';
```

46. **Write an SQL query to find the 2nd maximum salary.**

```sql
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
```

47. **Write an SQL query to find the 10th maximum salary.**

```sql
SELECT salary
FROM (
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 10
) AS temp
ORDER BY salary ASC
LIMIT 1;
```

48. **What is the difference between the `WHERE` and `HAVING` clauses?**
- *The `WHERE` clause filters rows before any groupings are made, while the
`HAVING` clause filters groups after the `GROUP BY` operation.*

49. **Give an example of using the `HAVING` clause.**

```sql
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
```

50. **Can you use grouping in the `WHERE` clause?**


- *No, grouping and aggregation functions must be used with the `HAVING`
clause, not the `WHERE` clause.*

51. **Write a Java code snippet to find names starting with 'A' using streams.**

```java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Andrew", "Amanda",
"George");

List<String> result = names.stream()


.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());

System.out.println(result); // Output: [Alice, Andrew, Amanda]


}
}
```

52. **Given the number 6178, how many iterations are required to reach 1629 and
99? Write the code logic to solve this.**
Solution Explanation:
8716 - 6178 = 2538
8352 - 2538 = 5814
5814 - 4185 = 1629
9261 - 1629 = 7632
7632 - 2367 = 5265
5625 - 5265 = 0360
0360 - 0036 = 0324
0423 - 0324 = 0495
5490 - 0495 = 4995
5994 - 4995 = 099

```java
import java.util.Arrays;

public class KaprekarRoutine {


public static void main(String[] args) {
int number = 6178;
int iterations = 0;

while (number != 6174 && number != 99) {


number = performKaprekarIteration(number);
System.out.println("Current number: " + number);
iterations++;
}

System.out.println("Total iterations: " + iterations);


}

private static int performKaprekarIteration(int number) {


String numStr = String.format("%04d", number); // Pad with zeros if
necessary
char[] numChars = numStr.toCharArray();

Arrays.sort(numChars); // Ascending order


int smallNum = Integer.parseInt(new String(numChars));

// Reverse the order for descending


String largeStr = new StringBuilder(new
String(numChars)).reverse().toString();
int largeNum = Integer.parseInt(largeStr);

return largeNum - smallNum;


}
}
```

# Client Round

# PayPal client interview (L1):

---

### 1. **Self-introduction about your project:**


- Briefly describe your project, its objective, technologies used (e.g., Java, Spring
Boot, ReactJS), and your role (backend developer, full stack developer). Mention any
key features, challenges faced, and how you solved them.
### 2. **Do you know SQL?**
- Yes, SQL is a standard language used to manage and manipulate relational
databases. I have experience with queries like `SELECT`, `INSERT`, `UPDATE`,
`DELETE`, and handling joins, indexes, and stored procedures.

### 3. **Do you know Data Structures and Algorithms (LinkedList)?**


- Yes, LinkedList is a data structure where each element (node) contains data and
a reference (or pointer) to the next node. There are two types: singly linked and
doubly linked lists.

### 4. **Do you know OOP concepts? Can you explain what they are?**
- OOP (Object-Oriented Programming) concepts include:
1. **Encapsulation:** Wrapping data (variables) and code (methods) together.
2. **Abstraction:** Hiding complexity by providing a simplified interface.
3. **Inheritance:** Deriving new classes from existing ones.
4. **Polymorphism:** The ability to use the same function in different forms.

### 5. **What is polymorphism?**


- Polymorphism allows one interface to be used for different data types. In Java, it
can be achieved through method overloading and method overriding.

### 6. **What is method overloading, and what is method overriding?**


- **Method Overloading:** Multiple methods with the same name but different
parameters (within the same class).
- **Method Overriding:** A subclass provides a specific implementation of a
method already defined in its parent class.

### 7. **How can you declare your override?**


- By using the `@Override` annotation before the method in the subclass.

### 8. **What are access modifiers?**


- Access modifiers define the scope of access to classes, variables, and methods:
- `private`: Accessible only within the same class.
- `protected`: Accessible within the same package and subclasses.
- `public`: Accessible everywhere.
- (default): Accessible within the same package.

### 9. **Why use `private`?**


- To restrict access to the class members and maintain encapsulation, ensuring
controlled access through getters and setters.

### 10. **If you provide a variable as `private`, what happens? How can you set and
get the value of that private variable?**
- The variable will be inaccessible from outside the class. You can set and get the
value using public getter and setter methods.

### 11. **Which OOP concept can achieve private variables?**


- **Encapsulation** ensures private variables can be controlled through public
methods like getters and setters.
### 12. **Do you know about `String`? Can you explain?**
- A `String` in Java is an immutable sequence of characters. It is stored in the
string pool for memory efficiency.

### 13. **What is the difference between `String`, `StringBuilder`, and `StringBuffer`?
**
- `String`: Immutable.
- `StringBuilder`: Mutable and not thread-safe.
- `StringBuffer`: Mutable and thread-safe (synchronized).

### 14. **What is the string constant pool?**


- It's a special memory area in the Java heap where `String` literals are stored to
optimize memory usage and avoid duplicate string objects.

### 15. **Given the pseudo-code `String str1="abc"`, `String str2="abc"`, `str1 ==
str2`, what will be the output?**
- The output will be `true` because both `str1` and `str2` point to the same literal in
the string constant pool.

### 16. **What is an inner class, and why is it useful?**


- An inner class is a class defined within another class. It’s useful to logically
group classes, improve encapsulation, and access outer class members.

### 17. **What is an anonymous class, and why is it used?**


- An anonymous class is a class without a name, often used to instantiate a one-
time object. It’s useful for event handling or passing functionality without creating
separate named classes.

### 18. **Have you worked with multithreading?**


- Yes, multithreading allows concurrent execution of two or more threads,
improving the performance of tasks like I/O, database calls, etc.

### 19. **How many ways are there to create a thread?**


- Two ways:
1. By extending the `Thread` class.
2. By implementing the `Runnable` interface.

### 20. **Have you used the `Future` class?**


- Yes, the `Future` class in Java represents the result of an asynchronous
computation, allowing you to check if the task is complete, retrieve the result, or
cancel the task.

### 21. **Have you used `Callable`?**


- Yes, `Callable` is an interface similar to `Runnable`, but it returns a result and
can throw a checked exception.

### 22. **Which collections have you used?**


- I've used various collections like `ArrayList`, `HashSet`, `HashMap`, `LinkedList`,
and `TreeMap`.
### 23. **What is the retrieval time complexity of `HashMap`?**
- The average time complexity for retrieving an element in a `HashMap` is O(1),
assuming good hash function distribution.

### 24. **How does `HashMap` work internally?**


- `HashMap` uses an array of buckets where each bucket is a linked list. The
key's hashcode determines the bucket, and keys with the same hashcode are
handled via linked lists (or trees in case of hash collision).

### 25. **What is hash collision?**


- Hash collision occurs when two different keys generate the same hashcode.
Java resolves this through linked lists or balanced trees inside the bucket.

### 26. **What is `final`, and how does it work with variables, methods, and classes?
**
- `final` prevents modification:
- **Variable**: Value cannot be changed after initialization.
- **Method**: Cannot be overridden.
- **Class**: Cannot be extended.

### 27. **How can you handle exceptions? Have you used custom exceptions?**
- Exceptions are handled using `try-catch` blocks. Yes, I have used custom
exceptions to create application-specific error messages by extending the
`Exception` class.

### 28. **Give me mostly used Spring Boot exceptions.**


- Common exceptions include `DataIntegrityViolationException`,
`HttpClientErrorException`, `HttpServerErrorException`, `EntityNotFoundException`.

### 29. **What is the difference between `throw` and `throws`?**


- `throw`: Used to explicitly throw an exception.
- `throws`: Declares that a method can throw one or more exceptions.

### 30. **What is the difference between checked and unchecked exceptions?**
- **Checked exceptions** must be handled at compile-time (e.g., `IOException`).
- **Unchecked exceptions** occur at runtime (e.g., `NullPointerException`).

### 31. **What are `try`, `catch`, and `finally`? When do we use them?**
- `try` defines the code block to monitor for exceptions.
- `catch` handles the exception.
- `finally` executes code after `try-catch`, regardless of an exception.

### 32. **If `try` contains multiple catch blocks, which catch block will execute? If
there is a `finally` block, what will be the output?**
- The first matching `catch` block will execute. The `finally` block will always
execute after the `catch` block, regardless of the exception.

### 33. **If a single `catch` can handle multiple exceptions, which exception will it
handle?**
- It will handle whichever exception occurs that is listed in the `catch` block. Java
allows multi-catch blocks using `|`.

### 34. **Have you worked with Java 8?**


- Yes, I have used features like Lambdas, Streams, Optional, and the Date-Time
API.

### 35. **What are the Java 9 features?**


- Key features include JShell (REPL), Module System, Factory Methods for
Collections, Stream API improvements, and Private Interface Methods.

### 36. **If I provide the string "leetcode" and the character "e", can you find how
many times "e" occurs using streams?**
```java
long count = "leetcode".chars().filter(ch -> ch == 'e').count();
```

### 37. **Which data structure are you familiar with?**


- I am familiar with LinkedList, ArrayList, HashMap, Stack, Queue, etc.

### 38. **Select any data structure: LinkedList, Stack, or Queue.**


- Let's take LinkedList, which stores elements as nodes where each node points
to the next node.

### 39. **Write code logic: If I provide the head of a linked list, determine if it is a
cycle linked list or not.**
```java
public boolean hasCycle(ListNode head) {
if (head == null) return false;
ListNode slow = head, fast =

head.next;
while (slow != fast) {
if (fast == null || fast.next == null) return false;
slow = slow.next;
fast = fast.next.next;
}
return true;
}
```

### 40. **What is the time complexity and space complexity of the code to detect a
cycle in a linked list?**
- **Time complexity:** O(n) - We traverse the linked list only once, making the
time complexity linear.
- **Space complexity:** O(1) - We use a constant amount of extra space (two
pointers).

### 41. **What is the `Optional` class?**


- The `Optional` class in Java is used to avoid `null` pointer exceptions by
representing a value that may or may not be present. It provides methods like
`isPresent()`, `get()`, `orElse()`, and `ifPresent()` to handle the value safely.

### 42. **What is a functional interface?**


- A functional interface in Java is an interface that contains exactly one abstract
method. It can have multiple default or static methods. Functional interfaces can be
implemented using lambda expressions. Example: `Runnable`, `Callable`,
`Comparator`.

### 43. **What are the built-in functional interfaces available in Java?**
- Some of the built-in functional interfaces in Java are:
- `Function<T, R>`: Takes one argument and returns a result.
- `Consumer<T>`: Takes one argument and returns no result.
- `Supplier<T>`: Takes no argument and returns a result.
- `Predicate<T>`: Takes one argument and returns a boolean.
- `BiFunction<T, U, R>`, `BiConsumer<T, U>`, `BiPredicate<T, U>`: Same as the
above but with two arguments.

### 44. **How can we write methods in a functional interface, and how can we utilize
those methods?**
- You define a functional interface by declaring one abstract method, then
implement it using a lambda expression. For example:
```java
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}

public class Main {


public static void main(String[] args) {
MathOperation addition = (a, b) -> a + b;
System.out.println("Result: " + addition.operate(5, 3));
}
}
```

### 45. **Do you know `CompletableFuture`?**


- Yes, `CompletableFuture` is a feature of Java 8 that is used to handle
asynchronous programming. It allows you to run tasks asynchronously and chain
multiple stages of computations. It supports combining multiple asynchronous
computations and handling exceptions.

### 46. **Have you worked with Spring Boot?**


- Yes, I have worked with Spring Boot extensively. It simplifies building stand-
alone, production-grade Spring-based applications. It provides default configurations
and a wide range of annotations to reduce boilerplate code.

### 47. **What is configuration and auto-configuration in Spring Boot?**


- **Configuration** refers to the settings and beans required to run the Spring
Boot application.
- **Auto-configuration** is a feature in Spring Boot that automatically configures
your application based on the dependencies in the classpath. It reduces the need for
manual configuration.

### 48. **What is `@Component`?**


- `@Component` is a Spring annotation used to indicate that a class is a Spring-
managed bean. The Spring container automatically detects and registers beans
marked with `@Component` for dependency injection.

### 49. **Can you explain `@Controller`, `@Service`, and `@Repository`?**


- **`@Controller`**: Marks a class as a Spring MVC controller, typically used to
handle web requests.
- **`@Service`**: Indicates a service layer class that contains business logic. It is
used for business operations and service orchestration.
- **`@Repository`**: Marks a data access layer class that interacts with the
database, translating exceptions into Spring’s DataAccessException.

### 50. **Do you know MVC?**


- Yes, MVC (Model-View-Controller) is a software architectural pattern that
separates an application into three main logical components:
- **Model**: Manages the data and business logic.
- **View**: Responsible for rendering the UI.
- **Controller**: Handles user input and controls the flow of data between the
Model and View.

### 51. **Can you explain the MVC architecture?**


- In the MVC architecture:
- **Model**: Represents the data and the business logic of the application.
- **View**: Renders the UI, based on the data provided by the Model.
- **Controller**: Handles the input from the user, updates the Model, and selects
the View to display.

### 52. **What is the difference between SOAP and RESTful services?**
- **SOAP** (Simple Object Access Protocol) is a protocol used for exchanging
structured information in web services. It uses XML as its message format and
operates over various protocols like HTTP, SMTP, etc.
- **REST** (Representational State Transfer) is an architectural style for building
web services, using standard HTTP methods (GET, POST, PUT, DELETE) and
typically communicates using JSON or XML.

### 53. **What are the features of RESTful services?**


- RESTful services are:
- Stateless: Each request from the client must contain all the information
required for the server to understand and process the request.
- Cacheable: Responses can be marked as cacheable to improve performance.
- Scalable: REST is designed to handle high-load scenarios efficiently.
- Layered: RESTful systems allow layering of services.

### 54. **You mentioned you worked on microservices, so give me an example API
you worked on (e.g., notification services). How does it work? How would you create
it in code?**
- Example: A notification service in a microservice architecture can be responsible
for sending notifications (email, SMS, etc.) to users.
1. **Controller**: The user triggers a notification request.
2. **Service**: Business logic determines the notification type and message.
3. **Repository**: Interacts with the database to fetch necessary data (like user
preferences, templates).
4. **External API**: Calls the external notification provider (e.g., email or SMS
API).

Here's an example Spring Boot API for sending email notifications:


```java
@RestController
@RequestMapping("/api/notification")
public class NotificationController {
@Autowired
private NotificationService notificationService;

@PostMapping("/send")
public ResponseEntity<String> sendNotification(@RequestBody
NotificationRequest request) {
notificationService.sendNotification(request);
return ResponseEntity.ok("Notification sent successfully");
}
}

@Service
public class NotificationService {
public void sendNotification(NotificationRequest request) {
// Logic to send notification (e.g., email, SMS)
}
}
```
---

# PayPal client interview (L2):

### 1. Self-introduction based on project


I have been working on a [your project name] for [duration], focusing on full-stack
development with technologies like ReactJS on the front end and Spring Boot on the
backend. The project involves creating customer registration services, handling
transactions, and managing user data. I am responsible for developing APIs,
integrating third-party services, and ensuring smooth user experiences. I've also
worked on cloud deployments, particularly with GCP, where I implemented features
such as auto-scaling and cloud storage integration.

### 2. Which GCP concepts have you used?


- Compute Engine for virtual machine management.
- Google Cloud Storage for object storage.
- Pub/Sub for messaging between services.
- Cloud SQL for managed relational databases.
- Cloud Load Balancing for distributing traffic.
- Stackdriver for monitoring and logging.

### 3. Are you compatible with Java 8 streams?


Yes, I am proficient with Java 8 streams. I use them for operations like filtering,
mapping, reducing, and collecting data, which allows for a more functional
programming approach.

### 4. You have one list; can you find how many times a given string occurs using
streams?
```java
List<String> list = Arrays.asList("apple", "banana", "apple", "orange", "apple");
long count = list.stream().filter(s -> s.equals("apple")).count();
System.out.println(count); // Output: 3
```

### 5. You have a list of strings; find the occurrence of each string using streams.
```java
List<String> list = Arrays.asList("apple", "banana", "apple", "orange", "banana");
Map<String, Long> result = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(result); // Output: {banana=2, orange=1, apple=2}
```

### 6. What is the difference between HashMap vs LinkedHashMap?


- **HashMap**: Does not maintain insertion order.
- **LinkedHashMap**: Maintains insertion order or access order.

### 7. You have `String s1="hello"` and `String s2="hellow"`. What happens when
using `==` and `.equals()`?
- `==`: Compares reference, so `s1 == s2` returns `false` because they point to
different objects.
- `.equals()`: Compares value, so `s1.equals(s2)` returns `false` because their
content is different.

### 8. What are exceptions, and can you give types of exceptions?
Exceptions are events that disrupt normal program execution.
- **Checked Exceptions**: Must be handled or declared, e.g., `IOException`.
- **Unchecked Exceptions**: Include runtime exceptions like `NullPointerException`,
`ArithmeticException`.

### 9. What is a checked exception and unchecked exception? Give an example.


- **Checked Exception**: Needs explicit handling.
```java
try {
FileReader file = new FileReader("file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
```
- **Unchecked Exception**: Occurs at runtime.
```java
int a = 10 / 0; // ArithmeticException
```

### 10. How strong are you in Java theory and programming? Give a rating out of
10.
I would rate myself 8 out of 10.

### 11. Which data structures are you familiar with?


Arrays, Lists, Maps, Sets, Stacks, Queues, and Trees.

### 12. What is the difference between Stack and Queue?


- **Stack**: Follows LIFO (Last In First Out).
- **Queue**: Follows FIFO (First In First Out).

### 13. Have you used try-with-resources? Give an example code.


```java
try (FileReader reader = new FileReader("file.txt")) {
// Use the reader
} catch (IOException e) {
e.printStackTrace();
}
```

### 14. When does a finally block never execute?


- When `System.exit()` is called.
- If a fatal JVM error occurs.

### 15. Given the code:


```java
int division(int a, int b) {
try {
return a / b;
} finally {
System.out.print("finally");
}
}
```
**Output**: It prints "finally" and returns `5` (for inputs `10, 2`).

### 16. How to create a custom exception? Give example code.


```java
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
```

### 17. What is a static method?


A method that belongs to the class rather than any specific instance. It can be called
without creating an object of the class.

### 18. If you have a class with a static method, is it possible to override it in a
subclass?
No, static methods cannot be overridden, but they can be hidden in a subclass.

### 19. What is the diamond problem?


Occurs in languages that allow multiple inheritance, causing ambiguity. Java avoids
this through interfaces with default methods.

### 20. What is the difference between a Java 7 interface and a Java 8 interface?
- **Java 7 Interface**: Only abstract methods.
- **Java 8 Interface**: Can have default and static methods.

### 21. You have an array `arr[]={2,4,6,8,9}`; how can you efficiently find the index of
element 6? Write code logic and explain.
```java
import java.util.Arrays;

public class BinarySearchExample {


public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 9};
int target = 6;

int index = Arrays.binarySearch(arr, target);

if (index >= 0) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
}

```

### 22. If you have a Java-based logic to fetch data from a database and use a join
query to get data, which one is faster?
Fetching data using a join query in SQL is generally faster because the database
engine is optimized for such operations.

### 23. How do you get data from the database in Spring Boot?
Using Spring Data JPA repositories:
```java
@Autowired
private UserRepository userRepository;
List<User> users = userRepository.findAll();
```

### 24. When you have a list containing data and want to remove data in the middle,
which collection is best?
`LinkedList` is better because it allows faster insertions and deletions in the middle.

### 25. If you have one list and it's iteration time, can you remove an element?
Yes, using `Iterator.remove()` to avoid `ConcurrentModificationException`.

### 26. If you create a list using `List.of()` method, can you add data additionally?
No, `List.of()` creates an immutable list.

### 27. Do you know design patterns?


Yes, I am familiar with Singleton, Factory, Observer, and other design patterns.

### 28. What is the Singleton design pattern?


A design pattern that ensures a class has only one instance and provides global
access to it.

### 29. Write a code logic for the Singleton design pattern.
```java
public class Singleton {
private static Singleton instance;

private Singleton() {}

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```

### 30. What is the default Spring Boot design pattern?


The default design pattern in Spring Boot is the **Dependency Injection** pattern.

### 31. If you have multiple catch blocks, how do you handle which exception? Give
an example.
```java
try {
// code
} catch (IOException e) {
// handle IOException
} catch (Exception e) {
// handle all other exceptions
}
```

### 32. If I catch a general exception and then catch an arithmetic exception, what
will happen? Write code and explain.
The more specific exception (ArithmeticException) should be caught first.
```java
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception");
} catch (Exception e) {
System.out.println("General Exception");
}
```
Output: "Arithmetic Exception".

### 33. How familiar are you with SQL queries?


I am quite familiar and can write complex queries with joins, subqueries, and
aggregate functions.

### 34. What are the joins available in SQL?


- Inner Join
- Left Join (Left Outer Join)
- Right Join (Right Outer Join)
- Full Join (Full Outer Join)

### 35. Explain briefly about all SQL joins.


- **Inner Join**: Returns records that have matching values in both tables.
- **Left Join**: Returns all records from the left table and matched records from the
right table.
- **Right Join**: Returns all records from the right table and matched records from
the left table.
- **Full Join**: Returns all records when there is a match in either left or right table.

### 36. Why is the main method static?


The `main` method is static because it allows the JVM to invoke it without
instantiating the class.

### 37. What is polymorphism?


Polymorphism allows one interface to be used for different data types, typically
achieved through method overloading or overriding.

### 38. What is method overloading and method overriding? Give example code.
- **Method Overloading**: Same method name, different parameters.
- **Method Overriding**: Subclass redefines a method from the parent class.

Overloading:
```java
class Example {
void print(int a) {}
void print(String a

) {}
}
```

Overriding:
```java
class Parent {
void show() {}
}

class Child extends Parent {


@Override
void show() {}
}
```

### 39. Based on the tables `menu -> mid, itemid`, `order -> oid, cid, orderdate`,
`customer -> cid, cname, address`, find order ID based on customer name.
```sql
SELECT order.oid
FROM order
INNER JOIN customer ON order.cid = customer.cid
WHERE customer.cname = 'customer_name';
```

### 40. Given employee data with id=1, sal=1000; id=2, sal=2000; id=3, sal=10000,
find the second maximum salary.
```sql
SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary)
FROM employees);
```

### 41. What is dependency injection? Give an example.


Dependency Injection is a design pattern where an object's dependencies are
provided rather than hard-coded within the object.
```java
@Service
public class MyService {
private final MyRepository repository;

@Autowired
public MyService(MyRepository repository) {
this.repository = repository;
}
}
```

### 42. How many ways can dependency injection be done?


- Constructor Injection
- Setter Injection
- Field Injection (not recommended)

# HR
--package, self

### 1. **What are the key features introduced in Java 8?**

**Answer:**
- **Lambda Expressions**: Allows for concise representation of instances of single-
method interfaces (functional interfaces).
- **Stream API**: Provides a new abstraction for processing sequences of elements,
supporting operations like map, filter, and reduce.
- **Optional Class**: A container object which may or may not contain a value, used
to avoid null references.
- **Default Methods**: Interfaces can now have methods with a body, allowing for
backward compatibility.
- **Method References**: Shortcuts to call methods using the syntax
`ClassName::methodName`.
- **New Date and Time API**: A new, comprehensive API for handling dates and
times (`java.time` package).

### 2. **What are the built-in functional interfaces available in Java 8?**

**Answer:**
- **`Predicate<T>`**: Represents a boolean-valued function of one argument.
- **`Function<T, R>`**: Represents a function that takes an argument of type `T` and
returns a result of type `R`.
- **`Consumer<T>`**: Represents an operation that accepts a single input argument
and returns no result.
- **`Supplier<T>`**: Represents a supplier of results, providing instances of type `T`.
- **`UnaryOperator<T>`**: A specialized form of `Function` that takes a single
argument and returns a result of the same type.
- **`BinaryOperator<T>`**: A specialized form of `Function` that takes two arguments
of the same type and returns a result of the same type.

### 3. **What is a profile in Spring Boot, and how do you use it?**

**Answer:**
- **Profile**: A feature that allows for the segregation of application configuration
based on different environments (e.g., development, testing, production).
- **Usage**: Define profiles using the `@Profile` annotation in Spring components or
specify them in `application.properties` or `application.yml`. Activate profiles via
command-line arguments or environment variables (e.g., `--
spring.profiles.active=dev`).

### 4. **What configurations can be managed within a Spring Boot profile?**

**Answer:**
- **Data Source Configurations**: Define different database configurations for
various environments.
- **Service Endpoints**: Configure different API endpoints or service URLs based on
the active profile.
- **Logging Levels**: Set different logging levels or loggers for different
environments.
- **Security Settings**: Adjust security configurations such as authentication
mechanisms or access controls.

### 5. **What are the advantages of using microservices architecture?**

**Answer:**
- **Scalability**: Individual components can be scaled independently.
- **Flexibility**: Different services can be developed, deployed, and maintained
separately.
- **Resilience**: Failure in one service does not necessarily impact others.
- **Technology Agnostic**: Different services can use different technologies or
frameworks.
- **Faster Time to Market**: Smaller teams can develop and deploy services more
quickly.

### 6. **How do you integrate microservices in a project?**

**Answer:**
- **API Gateway**: Use an API gateway to handle requests and route them to the
appropriate microservices.
- **Service Registry**: Use tools like Eureka for service discovery and registration.
- **Inter-Service Communication**: Implement communication between services
using REST APIs, messaging queues, or gRPC.
- **Configuration Management**: Use tools like Spring Cloud Config to manage
configuration centrally.
- **Monitoring and Logging**: Implement centralized logging and monitoring using
tools like ELK stack or Prometheus.

### 7. **What is a Eureka Server, and how is it used in microservices?**

**Answer:**
- **Eureka Server**: A service discovery tool provided by Netflix, part of the Spring
Cloud ecosystem.
- **Usage**: Services register themselves with the Eureka Server, and other services
can discover and communicate with them using the server's registry. It helps in
managing service instances and load balancing.

### 8. **Can you explain the internal working of a HashMap in Java?**


**Answer:**
- **HashMap** stores key-value pairs. Internally, it uses an array of buckets, where
each bucket is a linked list or a tree (if many entries hash to the same bucket).
- **Hashing**: Keys are hashed to determine their bucket location.
- **Collision Resolution**: If multiple keys hash to the same bucket, they are stored in
a linked list or tree structure within that bucket.
- **Resizing**: When the number of entries exceeds a threshold, the HashMap
resizes and rehashes all entries.

### 9. **Given a list of integers [1, 2, 4, 6, 8, 9], with the numbers 3, 5, and 7
missing, how would you print the missing numbers using Java Streams?**

**Answer:**
```java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class MissingNumbers {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 4, 6, 8, 9);
int min = 1;
int max = 9;

List<Integer> missingNumbers = IntStream.rangeClosed(min, max)


.filter(n -> !numbers.contains(n))
.boxed()
.collect(Collectors.toList());

System.out.println("Missing numbers: " + missingNumbers);


}
}
```

### 10. **Given a list of strings ["blue", "green", "red", "pink"], how would you find the
longest string and print its length using Java Streams?**

**Answer:**
```java
import java.util.Arrays;
import java.util.List;
import java.util.Comparator;

public class LongestStringLength {


public static void main(String[] args) {
List<String> strings = Arrays.asList("blue", "green", "red", "pink");

int maxLength = strings.stream()


.sorted(Comparator.comparingInt(String::length).reversed())
.findFirst()
.map(String::length)
.orElse(0);

System.out.println("Length of the longest string: " + maxLength);


}
}
```

# Altimetrix Company

1. **Briefly explain the project you are currently working on.**


- I am currently working on a microservices-based banking application that
handles user registration and transaction data. The project uses Spring Boot for the
backend, ReactJS for the frontend, and JPA for database interactions. We also
implement security using Spring Security and JWT for authentication.

2. **What is Jenkins, and how do you use it in your project?**


- Jenkins is a continuous integration/continuous deployment (CI/CD) tool used to
automate the build and deployment process. In my project, Jenkins is configured to
build the application automatically whenever there is a new commit to the Git
repository. It also runs unit tests, integration tests, and deploys the application to the
staging/production environment.

3. **Which tools do you use for monitoring purposes in Spring Boot?**


- We use tools like **Prometheus** and **Grafana** for monitoring metrics,
**Spring Boot Actuator** for exposing health and metrics endpoints, and **ELK Stack
(Elasticsearch, Logstash, Kibana)** for logging and real-time monitoring.

4. **What Git commands do you commonly use in your project?**


- Common Git commands include:
- `git clone`: Clone a repository
- `git pull`: Fetch and merge changes from the remote repository
- `git push`: Push local changes to the remote repository
- `git branch`: Create, list, or switch branches
- `git checkout`: Switch between branches or restore files
- `git merge`: Merge branches
- `git commit -m "message"`: Commit changes with a message
- `git stash`: Temporarily save changes not ready to commit

5. **What is Agile methodology? Explain your experience working in Agile.**


- Agile methodology is an iterative approach to software development where
requirements and solutions evolve through collaboration between cross-functional
teams. I have experience working in Agile, specifically using **Scrum**. We follow
sprints, conduct daily standups, sprint planning, and retrospective meetings. This
approach allows us to quickly adapt to changes and deliver incremental updates.

6. **What is the difference between shallow copy and deep copy?**


- **Shallow Copy**: Creates a new object, but copies the references to the same
memory addresses of the objects inside. Changes to the internal objects affect both
copies.
- **Deep Copy**: Creates a new object and recursively copies all objects within it,
meaning both the original and copied objects are independent of each other.

7. **How many ways can you create an object in Java?**


- There are several ways to create an object in Java:
1. Using the `new` keyword.
2. Using reflection (`Class.newInstance()` or `Constructor.newInstance()`).
3. Using **clone()** (if the class implements `Cloneable`).
4. Using **serialization** and **deserialization**.
5. Using the `Factory` or `Builder` design pattern.

8. **Why is the main method in Java static?**


- The main method is static because it can be called without creating an instance
of the class. This allows the JVM to call it directly to start the program.

9. **What is a deadlock in Java?**


- A deadlock occurs when two or more threads are blocked forever, waiting for
each other to release a lock they need to proceed. Each thread holds a resource the
other thread requires, leading to a cycle of dependency.

10. **How can we avoid deadlock in Java?**


- To avoid deadlock:
1. Always acquire locks in a consistent order.
2. Use a **timeout** for acquiring locks.
3. Use fewer synchronized blocks or locks, and keep them as short as
possible.
4. Use **lock hierarchy** or **deadlock detection algorithms**.

11. **Do you know any design patterns?**


- Yes, I am familiar with several design patterns like **Singleton**, **Factory**,
**Builder**, **Observer**, **Strategy**, and **Decorator**.

12. **What is the Factory Design Pattern?**


- The **Factory Design Pattern** is a creational pattern that provides an interface
for creating objects in a super class, but allows subclasses to alter the type of
objects that will be created. It promotes loose coupling and is used when the object
creation process involves some logic.

13. **Check if a given string containing brackets is balanced.**


- Approach: Use a stack to track the open brackets and check for matching
closing brackets.
```java
public boolean isBalanced(String str) {
Stack<Character> stack = new Stack<>();
for (char ch : str.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else if (ch == ')' && (stack.isEmpty() || stack.pop() != '(')) {
return false;
} else if (ch == '}' && (stack.isEmpty() || stack.pop() != '{')) {
return false;
} else if (ch == ']' && (stack.isEmpty() || stack.pop() != '[')) {
return false;
}
}
return stack.isEmpty();
}
```

14. **Find the most repeated IP address.**


- Approach: Use a HashMap to count the occurrences of each IP.
```java
public String findMostRepeatedIP(List<String> logs) {
Map<String, Integer> ipCount = new HashMap<>();
for (String log : logs) {
String ip = log.split(" ")[0];
ipCount.put(ip, ipCount.getOrDefault(ip, 0) + 1);
}
return Collections.max(ipCount.entrySet(),
Map.Entry.comparingByValue()).getKey();
}
```

15. **How do you communicate between two microservices?**


- Communication between microservices can be done using **REST APIs**
(synchronous) or **message brokers** like RabbitMQ or Kafka (asynchronous).
REST APIs use HTTP requests, while message brokers allow communication
through event-driven architecture.

16. **How do you secure communication between microservices?**


- You can secure communication using:
1. **JWT** (JSON Web Tokens) for authentication and authorization.
2. **OAuth2** for secure access delegation.
3. **SSL/TLS** for encrypted communication.
4. **API Gateway** with security filters to control traffic and access.

17. **Have you worked with JPA (Java Persistence API)?**


- Yes, I have used JPA in my projects for managing database entities,
relationships, and queries using **Hibernate** as the JPA provider. I also work with
annotations like `@Entity`, `@OneToMany`, `@ManyToOne`, and `@Query`.

18. **What is the N+1 select problem in JPA, and how do you handle it?**
- The **N+1 select problem** occurs when a query retrieves an entity, but
subsequent queries are made to load related entities one by one. It can be handled
using:
- **FetchType.LAZY** or **FetchType.EAGER**.
- Using **JOIN FETCH** queries to load related entities in a single query.

19. **Have you worked on writing unit test cases? How do you approach it?**
- Yes, I write unit test cases using **JUnit** and **Mockito**. My approach is to
test individual methods, mock external dependencies, and ensure high code
coverage by writing tests for both positive and negative scenarios.

20. **How do you mock private methods in unit testing?**


- Private methods can be mocked using **PowerMock** along with Mockito,
which allows for mocking private, static, and final methods.

# Altimetrix Client L1
___soon

---

### **1. What is a hash collision?**


- **Answer:** A hash collision occurs when two different keys in a hash-based
collection, such as a `HashMap`, produce the same hash code and thus are placed
in the same bucket. This can lead to performance degradation as multiple keys have
to be stored and managed in the same location.

### **2. When does a collision error occur in hash-based collections?**


- **Answer:** A collision error occurs in hash-based collections when multiple keys
are mapped to the same hash code, causing them to be stored in the same bucket.
This results in a need for the collection to handle the collision, usually through
chaining (linked list) or open addressing (probing).

### **3. What are the key differences between `Runnable` and `Callable` in Java?**
- **Answer:**
- **`Runnable`:** Does not return a result and cannot throw a checked exception.
- **`Callable`:** Returns a result (`T`) and can throw checked exceptions.
- `Runnable` is executed by `Thread` or `Executor`, while `Callable` is executed by
`ExecutorService`.

### **4. What is the difference between `map` and `flatMap` in Java Streams?**
- **Answer:**
- **`map`:** Transforms each element in the stream into another form, producing a
stream of the same structure.
- **`flatMap`:** Flattens multiple streams into a single stream by applying a one-to-
many transformation function to each element and then flattening the resulting
streams into one.

### **5. How does `flatMap` work internally?**


- **Answer:** Internally, `flatMap` applies a function that returns a stream for each
element of the original stream. It then flattens these streams into a single stream,
effectively concatenating them. This is achieved through a combination of the `map`
operation and the `Stream.flatMap` method, which merges the nested streams.

---

### **6. Find and Insert Target in a Sorted Array:**

- **Question:** You are given an unsorted array of integers. You need to find the
index of a target value within this array. If the target value is not present in the array,
insert it into the array such that the array remains sorted after insertion, and return
the index where the target value would be if it were inserted.

**Example:**
- **Input 1:**
- Array: `[4, 1, 7, 2]`
- Target: `4`
- **Output:** `0`
- **Input 2:**
- Array: `[4, 1, 7, 2]`
- Target: `5`
- **Output:** `3` (because the array becomes `[1, 2, 4, 5, 7]` and `5` is at index `3`)

- **Answer (Java Code):**


```java
import java.util.Arrays;

public class InsertAndFindIndex {


public static int insertAndFindIndex(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
Arrays.sort(arr);
int index = Arrays.binarySearch(arr, target);
if (index >= 0) {
return index;
}
return -(index + 1);
}

public static void main(String[] args) {


int[] arr1 = {4, 1, 7, 2};
int target1 = 4;
System.out.println(insertAndFindIndex(arr1, target1)); // Output: 0

int[] arr2 = {4, 1, 7, 2};


int target2 = 5;
System.out.println(insertAndFindIndex(arr2, target2)); // Output: 3
}
}
```

---

### **7. Capitalize and Count Words in a List Using Streams:**

- **Question:** You are given a list of lowercase strings. Write a Java program that:
- Capitalizes the first letter of each word.
- Counts the occurrences of each word after capitalization.

**Example:**
- **Input:**
- List: `["hello", "world", "this", "hello"]`
- **Output:**
- Capitalized List: `["Hello", "World", "This", "Hello"]`
- Word Counts:
- `Hello`: 2
- `World`: 1
- `This`: 1

- **Answer (Java Code):**


```java
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CapitalizeWords {


public static void main(String[] args) {
List<String> words = Arrays.asList("hello", "world", "this", "hello");

List<String> capitalizedWords = words.stream()


.map(word -> word.isEmpty() ? word :
Character.toUpperCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.toList());

System.out.println("Capitalized List: " + capitalizedWords);

Map<String, Long> wordCounts = words.stream()


.map(word -> word.isEmpty() ? word :
Character.toUpperCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

wordCounts.forEach((word, count) -> System.out.println(word + ": " +


count));
}
}
```

# L1 Interview Questions
## Java Questions

1. **Briefly describe your project experience and the versions of languages you
used.**
- I have 3 years of experience in full-stack development using Java 8 and
ReactJS. I've worked on customer registration services and transaction data
handling in a bank application. For backend development, I utilized Spring Boot,
Hibernate, and JPA. Additionally, I've worked on implementing unit tests using JUnit
and Mockito.

2. **What are the features of Java 8?**


- Java 8 introduced several key features, including lambda expressions, the
Stream API, default methods in interfaces, the new java.time API for date and time,
Optional class, and improvements in the Collections API.

3. **What is a lambda expression?**


- A lambda expression is a concise way to represent a method interface using an
expression. It provides a clear and concise way to write inline implementations of
functional interfaces.

4. **What is a functional interface?**


- A functional interface is an interface with exactly one abstract method. It can
have multiple default or static methods. Functional interfaces are used as the types
for lambda expressions and method references.

5. **What is a normal interface?**


- A normal interface can have multiple abstract methods. It serves as a contract
for implementing classes to provide specific behaviors.

6. **What is the difference between a functional interface and a normal interface?**


- A functional interface has only one abstract method, making it suitable for
lambda expressions, while a normal interface can have multiple abstract methods.

7. **Can I use lambda expressions in normal methods?**


- Yes, lambda expressions can be used in any context where a functional
interface is expected, including in normal methods.

8. **What is the difference between HashMap and ConcurrentHashMap?**


- HashMap is not thread-safe and can have performance issues in a concurrent
environment. ConcurrentHashMap is thread-safe, allowing concurrent read and write
operations without blocking.

9. **Can multiple threads access ConcurrentHashMap?**


- Yes, ConcurrentHashMap allows multiple threads to read and write
simultaneously without locking the entire map.

10. **If I use ConcurrentHashMap and perform get and put operations at the same
time, will it work?**
- Yes, ConcurrentHashMap is designed to handle concurrent read and write
operations safely and efficiently.

11. **How does HashMap work internally?**


- HashMap uses an array of buckets, where each bucket is a linked list or tree. It
calculates the hash code of the key, determines the index of the bucket, and stores
the key-value pair in the appropriate bucket.

12. **What is a bucket in HashMap?**


- A bucket is a slot in the HashMap's internal array, used to store key-value pairs
that have the same hash code.

13. **What is the difference between map and flatMap?**


- `map` transforms each element in the stream, while `flatMap` transforms each
element to a stream and flattens the resulting streams into a single stream.

14. **What is the difference between throw and throws?**


- `throw` is used to explicitly throw an exception in the code, while `throws` is
used in the method signature to declare that the method can throw certain
exceptions.

15. **What is the ternary operator in Java?**


- The ternary operator is a concise way to express conditional logic. It takes the
form `condition ? ifTrue : ifFalse`.

16. **Write a code to find the 3rd non-repeated character in the string "hi am
Bharath".**
```java
import java.util.LinkedHashMap;
import java.util.Map;

public class NonRepeatedCharacter {


public static void main(String[] args) {
String str = "hi am Bharath";
System.out.println(getThirdNonRepeatedCharacter(str));
}

public static Character getThirdNonRepeatedCharacter(String str) {


Map<Character, Integer> charCount = new LinkedHashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}

int count = 0;
for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
if (entry.getValue() == 1) {
count++;
if (count == 3) {
return entry.getKey();
}
}
}
return null; // or throw an exception if you prefer
}
}
```

17. **Write a code to count every characters in the string "hi am Bharath".**
```java
import java.util.HashMap;
import java.util.Map;

public class CharacterCount {


public static void main(String[] args) {
String str = "hi am Bharath";
Map<Character, Integer> charCount = countCharacters(str);
charCount.forEach((k, v) -> System.out.println(k + ": " + v));
}

public static Map<Character, Integer> countCharacters(String str) {


Map<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
return charCount;
}
}
```

18. **Given list1 = [1,2,4,6,7] and list2 = [3,5,4,6], print elements from list1 that are
not present in list2.**
```java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ListDifference {


public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 4, 6, 7);
List<Integer> list2 = Arrays.asList(3, 5, 4, 6);
List<Integer> result = list1.stream()
.filter(e -> !list2.contains(e))
.collect(Collectors.toList());

System.out.println(result);
}
}
```

19. **What is the Lombok dependency?**


- Lombok is a Java library that helps reduce boilerplate code. It provides
annotations to automatically generate getters, setters, constructors, equals,
hashCode, toString, and other methods.

20. **What is a no-argument constructor in Lombok?**


- In Lombok, the `@NoArgsConstructor` annotation generates a no-argument
constructor for the class.

21. **What is serialization and where have you used it?**


- Serialization is the process of converting an object into a byte stream for
storage or transmission. I have used serialization in a bank project to serialize
transaction statements for storage and retrieval.

22. **What is a serialization ID?**


- A serialization ID (serialVersionUID) is a unique identifier for a Serializable
class. It is used during deserialization to verify that the sender and receiver of a
serialized object maintain compatibility.

23. **If two objects have the same serialization ID, what happens when calling
another microservice with both serialized objects?**
- If two objects have the same serialization ID, they are considered compatible
for deserialization. However, it is crucial that their class definitions are compatible to
avoid `InvalidClassException`.

24. **What is a String?**


- A `String` is an immutable sequence of characters in Java. It is an instance of
the `java.lang.String` class.

25. **What is a String pool?**


- The String pool is a special memory region where Java stores interned strings.
When a string is created, the JVM checks the pool first to see if the string already
exists. If it does, the reference to the existing string is returned; otherwise, a new
string is added to the pool.

26. **What does the @Qualifier annotation mean?**


- The `@Qualifier` annotation is used to resolve ambiguity in Spring's
dependency injection when multiple beans of the same type are present. It specifies
which bean should be injected.
27. **Give an example of @Qualifier in real-time.**
```java
@Service
public class NotificationService {
private final MessageService messageService;

@Autowired
public NotificationService(@Qualifier("emailService") MessageService
messageService) {
this.messageService = messageService;
}

public void sendNotification(String message) {


messageService.sendMessage(message);
}
}

@Service("emailService")
public class EmailService implements MessageService {
@Override
public void sendMessage(String message) {
System.out.println("Sending email: " + message);
}
}

@Service("smsService")
public class SMSService implements MessageService {
@Override
public void sendMessage(String message) {
System.out.println("Sending SMS: " + message);
}
}
```

28. **What is @Primary and give a real-time example.**


- The `@Primary` annotation indicates which bean should be preferred when
multiple candidates qualify for autowiring.

```java
@Configuration
public class AppConfig {

@Bean
@Primary
public MessageService primaryMessageService() {
return new EmailService();
}

@Bean
public MessageService secondaryMessageService() {
return new SMSService();
}
}
```

29. **What are collections in Java?**


- Collections in Java are frameworks that provide an architecture to store and
manipulate a group of objects. They include interfaces like List, Set, and Map, and
classes like ArrayList, HashSet, and HashMap.

30. **Is Set an interface or a class?**


- `Set` is an interface in Java.

31. **Is LinkedList an interface or a class?**


- `LinkedList` is a class in Java.

## Spring Boot Questions

32. **What is the difference between Spring and Spring Boot?**


- Spring is a comprehensive framework for enterprise Java development. Spring
Boot simplifies the setup and development of new Spring applications with default
configurations, embedded servers, and minimal configuration.

33. **Why use Spring Boot?**


- Spring Boot is used for its ease of setup, embedded servers, reduced
boilerplate code, auto-configuration, and rapid development capabilities.

34. **What is AOP in Spring Boot?**


- AOP (Aspect-Oriented Programming) in Spring Boot is a programming
paradigm that aims to increase modularity by allowing the separation of cross-cutting
concerns, such as logging, transaction management, and security.

35. **Explain microservices architecture.**


- Microservices architecture is a design approach where an application is
composed of small, loosely coupled, and independently deployable services. Each
service handles a specific business function and communicates with other services
through APIs.

36. **What is @Autowired?**


- `@Autowired` is a Spring annotation used for automatic dependency injection.
It can be applied to constructors, fields, and setter methods to inject the required
beans.

37. **What is the difference between @PathVariable and @RequestParam?**


- `@PathVariable` is used to extract values from the URI path, while
`@RequestParam` is used to extract query parameters from the request.

38. **What is the difference between POST and PUT?**


- POST is used to create new resources, while PUT is used to update existing
resources or create a resource if it does not exist.
39. **Which HTTP method do we use for creating resources?**
- The POST method is used for creating resources.

40. **Can we use PUT for creating resources?**


- Yes, PUT can be used to create resources if the resource does not already
exist.

41. **What are HTTP status codes?**


- HTTP status codes are standard response codes given by web servers on the
internet. They indicate the result of the client's request, such as 200 (OK), 404 (Not
Found), and 500 (Internal Server Error).

42. **What is fail-safe and fail-fast?**


- Fail-safe iterators allow modifications to the collection while iterating without
throwing an exception. Fail-fast iterators throw a `ConcurrentModificationException`
if the collection is modified during iteration.

43. **Explain JWT token-based authentication.**


- JWT (JSON Web Token) is a compact, URL-safe means of representing claims
to be transferred between two parties. It is used for stateless authentication by
encoding user information in a token, which is then used to verify the user's identity.

44. **What is the @Transactional annotation?**


- `@Transactional` is used to manage transaction boundaries in Spring. It
ensures that a method or a block of code is executed within a transaction, providing
rollback and commit mechanisms.

## SQL Questions

45. **Write an SQL query to find the Nth maximum salary.**


```sql
SELECT DISTINCT salary
FROM employee
ORDER BY salary DESC
LIMIT 1 OFFSET N-1;
```

For example, to find the 3rd maximum salary:


```sql
SELECT DISTINCT salary
FROM employee
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
```

# L2 Interview Questions

1. **Self introduction based on project.**


Answer: " about your project"

2. **Which Java version are you using?**

Answer: "Before, I was using Java 8, which introduced several important features
such as lambda expressions, the Stream API, the new Date-Time API, and the
Optional class. These features significantly improved the way we write Java code.
Currently, I am using Java 17. Java 17 includes several new features such as pattern
matching for switch expressions, sealed classes, records, and the new Date-Time
API enhancements. These features provide more concise and expressive syntax,
better performance, and enhanced security."

3. **Where did you generate the JWT token?**

Answer: "In my current project, we generate the JWT token during the user
authentication process. The token is generated in the backend service using a
secure secret key and is then sent to the client. The client includes this token in the
Authorization header of subsequent requests to access protected resources."

4. **How do you provide JWT security in Spring Boot?**

Answer: "In Spring Boot, we provide JWT security by using Spring Security along
with a custom filter that validates the JWT token. The filter intercepts incoming
requests, extracts the token from the Authorization header, and validates it. If the
token is valid, the filter sets the authentication in the security context, allowing the
request to proceed. Additionally, we configure the security settings to protect specific
endpoints and ensure only authenticated users can access them."

# Given Code
```java
class Employee {
private String name;
private int id;
private String department;
private double salary;

public Employee(String name, int id, String department, double salary) {


this.name = name;
this.id = id;
this.department = department;
this.salary = salary;
}

public String getName() {


return name;
}

public int getId() {


return id;
}
public String getDepartment() {
return department;
}

public double getSalary() {


return salary;
}

@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + ", department='" +
department + "', salary=" + salary + "}";
}
}

ArrayList<Employee> employees = new ArrayList<>();


employees.add(new Employee("Alice", 101, "HR", 50000));
employees.add(new Employee("Bob", 102, "Engineering", 60000));
employees.add(new Employee("Charlie", 103, "Finance", 55000));
employees.add(new Employee("Diana", 104, "Engineering", 62000));

```
5. **How do you override the hashCode and equals methods in Java?**
```java
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee employee = (Employee) obj;
return id == employee.id &&
Double.compare(employee.salary, salary) == 0 &&
Objects.equals(name, employee.name) &&
Objects.equals(department, employee.department);
}

@Override
public int hashCode() {
return Objects.hash(name, id, department, salary);
}
```
6. **Find department-wise names using streams.**

```java
Map<String, List<String>> departmentWiseNames = employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.mapping(Employee::getName, Collectors.toList())
));

departmentWiseNames.forEach((department, names) -> {


System.out.println("Department: " + department);
System.out.println("Names: " + names);
});
```

7. **Find the second highest salary employee using streams.**

```java
Employee secondHighestSalaryEmployee = employees.stream()
.sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
.skip(1)
.findFirst()
.orElse(null);
System.out.println("Second Highest Salary Employee: " +
secondHighestSalaryEmployee);
```

## String Comparison
8. **What will be the output of the following code?**

```java
public class Test {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");

System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
}
}
```
Answer:
- `System.out.println(s1 == s2); ` - This is true because `s1` and `s2` refer to the
same string literal in the string pool.
- `System.out.println(s1 == s3); ` - This is false because `s3` is created using the
`new` keyword, resulting in a different object in memory.
- `System.out.println(s1.equals(s3));` - This is true because `equals` compares
the content of the strings, which are the same.

9. **What will be the output of the following code?**

```java
public class Test {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = s3.intern();

System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
System.out.println(s1 == s4);
}
}
```

Answer:
- `System.out.println(s1 == s2); ` - This is true because `s1` and `s2` refer to the
same string literal in the string pool.
- `System.out.println(s1 == s3); ` - This is false because `s3` is created using the
`new` keyword, resulting in a different object in memory.
- `System.out.println(s1.equals(s3)); ` - This is true because `equals` compares
the content of the strings, which are the same.
- `System.out.println(s1 == s4); ` - This is true because `s4` is the interned version
of `s3`, which points to the string literal in the string pool, the same as `s1`.
- ` System.out.println(s3 == s4)` This is false because `s3` is a new String object
created with `new String()`, while `s4` is a reference to the string literal in the pool.
Therefore, they are different objects.

# Manager Round Interview Questions


1.**Can you briefly describe your current project and walk me through your daily
responsibilities and tasks?**

2.**Question** Imagine you are tasked with enhancing a microservice for a library
system that allows users to check out books. The new feature involves handling the
scenario where multiple users attempt to check out the last copy of a particular book
simultaneously.

You are provided with the following basic structure for the Checkout entity:

java
Copy code
public class Checkout {
private Long id;
private Long bookId;
private String checkedOutBy; // This could be a user ID or username
private LocalDateTime checkedOutOn;
// getters and setters
}
Please address the following requirements in your solution:
Develop an API endpoint to facilitate book checkout.
Ensure that the checkout operation is atomic and thread-safe, preventing the last
copy of a book from being checked out by multiple users at the same time.
If the checkout is successful, the response should include checkout details and an
HTTP status code indicating success.
If all copies of the book are already checked out, the service should return an
appropriate error message and HTTP status code.
Propose an approach for handling and logging exceptions that may occur during the
checkout process, considering different types of failures that could happen (e.g.,
database errors, network issues).
Describe how you would structure the API responses to provide a consistent client
experience, regardless of success or error conditions.

- **Answer**
```java
@RestController
@RequestMapping("/api/checkout")
public class CheckoutController {

@Autowired
private CheckoutService checkoutService;

@PostMapping("/{bookId}")
public ResponseEntity<?> checkoutBook(@PathVariable Long bookId,
@RequestParam String userId) {
try {
Checkout checkout = checkoutService.checkoutBook(bookId, userId);
return ResponseEntity.status(HttpStatus.OK).body(checkout);
} catch (BookUnavailableException e) {
return
ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
} catch (Exception e) {
return
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error
occurred during checkout.");
}
}
}

@Service
public class CheckoutService {

@Autowired
private CheckoutRepository checkoutRepository;

@Autowired
private BookRepository bookRepository;

@Transactional
public Checkout checkoutBook(Long bookId, String userId) throws
BookUnavailableException {
synchronized (bookId) {
int availableCopies = bookRepository.getAvailableCopies(bookId);
if (availableCopies <= 0) {
throw new BookUnavailableException("No copies of the book are
currently available.");
}

// Reduce the available copies by 1


bookRepository.decrementAvailableCopies(bookId);

// Create and save the checkout record


Checkout checkout = new Checkout();
checkout.setBookId(bookId);
checkout.setCheckedOutBy(userId);
checkout.setCheckedOutOn(LocalDateTime.now());
return checkoutRepository.save(checkout);
}
}
}

@Repository
public interface CheckoutRepository extends JpaRepository<Checkout, Long> {
}

@Repository
public interface BookRepository {

@Query("SELECT b.availableCopies FROM Book b WHERE b.id = :bookId")


int getAvailableCopies(@Param("bookId") Long bookId);

@Modifying
@Query("UPDATE Book b SET b.availableCopies = b.availableCopies - 1
WHERE b.id = :bookId AND b.availableCopies > 0")
int decrementAvailableCopies(@Param("bookId") Long bookId);
}

@ResponseStatus(HttpStatus.CONFLICT)
public class BookUnavailableException extends RuntimeException {
public BookUnavailableException(String message) {
super(message);
}
}
```
# HR
# Axis L1
### 1. What are streams in Java, and how are they used?

**Answer:**

Java Streams are part of the `java.util.stream` package and were introduced in Java
8. They provide a high-level abstraction for processing sequences of elements, such
as collections, in a functional and declarative way.

- **Key Features:**
- **Functional Operations:** Streams support operations like `filter`, `map`,
`reduce`, `collect`, and `forEach` that can be chained together.
- **Lazy Evaluation:** Intermediate operations are lazily evaluated, meaning
computations are deferred until a terminal operation is invoked.
- **Parallel Processing:** Streams can be processed in parallel to leverage multi-
core processors.

**Example Usage:**

```java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {


public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
List<String> filteredWords = words.stream()
.filter(word -> word.startsWith("b"))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(filteredWords); // Output: [BANANA]
}
}
```

### 2. Explain lambda expressions in Java with an example.

**Answer:**

Lambda expressions in Java provide a concise way to express instances of


functional interfaces (interfaces with a single abstract method). They consist of a
parameter list, an arrow (`->`), and a body.

**Syntax:**

```java
(parameters) -> expression
```
**Example:**

```java
import java.util.Arrays;
import java.util.List;

public class LambdaExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

names.forEach(name -> System.out.println(name)); // Output: Alice Bob


Charlie
}
}
```

In this example, `name -> System.out.println(name)` is a lambda expression that


prints each name in the list.

### 3. What is reactive programming, and where is it used?

**Answer:**

Reactive programming is a programming paradigm that deals with asynchronous


data streams and the propagation of changes. It allows systems to react to data
changes or events in a non-blocking and efficient manner.

**Use Cases:**
- **Real-Time Systems:** Handling real-time data streams, such as stock market
data or sensor data.
- **User Interfaces:** Building responsive UIs that react to user inputs or data
changes.
- **Microservices:** Managing asynchronous communication between services and
handling high-load data processing.

**Key Libraries/Frameworks:**
- **RxJava:** A library for composing asynchronous and event-based programs using
observable sequences.
- **Project Reactor:** A reactive programming library for building non-blocking
applications on the JVM.

### 4. Describe the architecture of microservices and how services communicate


with each other.

**Answer:**

**Architecture:**
- **Microservices Architecture** involves breaking down a monolithic application into
small, independent services that focus on specific business functions. Each service
is developed, deployed, and scaled independently.
**Communication Methods:**
- **HTTP/REST:** Services expose RESTful APIs over HTTP for communication.
- **gRPC:** A high-performance, language-agnostic RPC framework.
- **Message Brokers:** Services communicate asynchronously through message
brokers like Kafka, RabbitMQ, or ActiveMQ.
- **Service Discovery:** Tools like Eureka or Consul are used for locating services
dynamically.

**Example Diagram:**
```
+-------------------+ +-------------------+
| Service A | ---> | Service B |
| (REST API) | | (Message Queue) |
+-------------------+ +-------------------+
```

### 5. Explain the architecture of the Spring Framework and the role of the IoC
container.

**Answer:**

**Architecture:**
- **Core Container:** Provides the foundation for dependency injection (DI) and bean
lifecycle management.
- **AOP (Aspect-Oriented Programming):** Supports cross-cutting concerns like
logging and transactions.
- **Data Access/Integration:** Simplifies data access with JDBC and ORM support.
- **Web:** Provides support for building web applications, including RESTful APIs.

**IoC Container:**
- **Role:** Manages the lifecycle and configuration of application objects (beans). It
uses Dependency Injection (DI) to decouple the creation of objects from their usage.
- **Types of IoC Containers:** `BeanFactory` (basic container) and
`ApplicationContext` (more advanced container).

**Example:**
```java
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {


public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = context.getBean(MyService.class);
myService.performAction();
}
}
```
### 6. What is Docker, and how does it relate to Kubernetes?

**Answer:**

**Docker:**
- **Definition:** Docker is a platform for developing, shipping, and running
applications in containers. Containers are lightweight, portable, and include
everything needed to run an application.

**Kubernetes:**
- **Relation:** Kubernetes is an orchestration platform that manages the deployment,
scaling, and operation of containerized applications across a cluster of machines. It
provides automated scheduling, scaling, and management of Docker containers.

**Example Workflow:**
1. **Develop:** Write application code and Dockerize it.
2. **Deploy:** Use Kubernetes to deploy and manage the Docker containers.

### 7. Explain the architecture of a Kafka cluster.

**Answer:**

**Architecture:**
- **Brokers:** Kafka brokers store and manage data. Each broker handles a subset
of partitions and replicas.
- **Topics:** Data is organized into topics. Each topic can be divided into multiple
partitions for parallel processing.
- **Producers:** Publish messages to topics.
- **Consumers:** Subscribe to topics and consume messages.
- **Zookeeper:** Manages broker metadata, leader elections, and configuration.

**Diagram:**
```
+-----------------+ +-----------------+ +-----------------+
| Kafka Broker | | Kafka Broker | | Kafka Broker |
+-----------------+ +-----------------+ +-----------------+
| | |
| | |
+-----------------+ +-----------------+ +-----------------+
| Producer | | Consumer | | Zookeeper |
+-----------------+ +-----------------+ +-----------------+
```

### 8. What is a Security Context in Spring Security, and how does it work?

**Answer:**

**Security Context:**
- **Definition:** A Security Context is a container that holds the authentication and
authorization information for the currently authenticated user.
- **Usage:** It is stored in a `ThreadLocal` and provides access to the current user's
roles and permissions.

**How it Works:**
1. **Authentication:** Upon successful login, Spring Security creates a
`SecurityContext` that holds an `Authentication` object.
2. **Authorization:** The `SecurityContext` is used throughout the application to
check if the user has the necessary permissions to access resources.

**Example:**
```java
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtils {


public static String getCurrentUsername() {
Authentication auth =
SecurityContextHolder.getContext().getAuthentication();
return auth != null ? auth.getName() : "Anonymous";
}
}
```

### 9. How do you implement JWT token-based authentication?

**Answer:**

**Implementation Steps:**
1. **Generate Token:** After successful authentication, generate a JWT token
containing user details.
2. **Send Token:** Send the token to the client, typically in the response header.
3. **Authenticate Requests:** Include the token in the Authorization header of
subsequent requests. Verify the token and extract user information.

**Example Code (Java):**

```java
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtil {


private static final String SECRET_KEY = "your-secret-key";

public static String generateToken(String username) {


return Jwts.builder()
.setSubject(username)
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
}
```

### 10. How do you use salt and hash in JWT to secure tokens?

**Answer:**

**Salt and Hash:**


- **Salt:** A random value added to the token before hashing to enhance security
and prevent precomputed attacks.
- **Hash:** A cryptographic function applied to the salted token to ensure its integrity.

**Steps:**
1. **Generate Salt:** Create a unique salt for each token.
2. **Hash Token:** Combine the token with the salt and apply a hash function.
3. **Store and Validate:** Store the salted and hashed token. During validation,
combine the incoming token with the salt and hash it to compare with the stored
value.

**Example Code (Java):**

```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class TokenUtil {


private static final SecureRandom random = new SecureRandom();

public static String generateSalt() {


byte[] salt = new byte[16];
random.nextBytes(salt);
return new String(salt);
}

public static String hashToken(String token, String salt) throws


NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update((token + salt).getBytes());
byte[] hashedBytes = md.digest();
return new String(has

hedBytes);
}
}
```

### 11. Write a code to find the longest palindrome substring length in a string.

**Answer:**
Here is an example code to find the length of the longest palindrome substring:

**Code:**

```java
public class LongestPalindromeLength {

private static int expandAroundCenter(String s, int left, int right) {


while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}

public static int longestPalindromeLength(String s) {


if (s == null || s.length() == 0) return 0;

int maxLength = 0;

for (int i = 0; i < s.length(); i++) {


int len1 = expandAroundCenter(s, i, i); // Odd length palindromes
int len2 = expandAroundCenter(s, i, i + 1); // Even length palindromes
int len = Math.max(len1, len2);
maxLength = Math.max(maxLength, len);
}

return maxLength;
}

public static void main(String[] args) {


String input = "babad";
System.out.println("Length of longest palindrome substring: " +
longestPalindromeLength(input));
}
}
```

**Example:**
- **Input:** `"babad"`
- **Output:** `3` (The longest palindromes are `"bab"` or `"aba"`, both with a length of
3)

## Self Introduction and Project Details


1. **Self Introduction and Project Details:**
- Briefly introduce yourself, mentioning your experience, key skills, and current
role.
- Briefly describe your current project, the technologies you are using, the version
of Java and React you are using, and the testing frameworks in use.
- Mention the version of Java (Java 8, familiar with Java 17) and React (React
16.8 or React 18).
## JavaScript and React Questions
2. **What are ES6 features in JavaScript?**
- ES6 features include let and const, arrow functions, template literals, default
parameters, rest and spread operators, destructuring assignment, classes, promises,
modules, and enhanced object literals.

3. **Difference between `var` and `let`.**


- `var` is function-scoped, while `let` is block-scoped. Variables declared with `let`
are not hoisted to the top of their block, unlike `var`.

4. **What is object cloning in JavaScript?**


- Object cloning is the process of creating a copy of an object with the same
properties and values.

5. **Why do we need to clone an object?**


- Cloning an object is needed to avoid mutating the original object, ensuring data
integrity and avoiding side effects in the code.

6. **How to clone an object in JavaScript? Provide code.**


```javascript
const original = { a: 1, b: 2 };
const clone = { ...original }; // Shallow copy using spread operator
```

7. **Write a JavaScript function to count every character in a string and display it.**
```javascript
function countCharacters(str) {
const charCount = {};
for (let char of str) {
charCount[char] = charCount[char] ? charCount[char] + 1 : 1;
}
return charCount;
}
console.log(countCharacters("hello"));
```

8. **Which version of React are you using?**


- I am using React 17.

9. **Are you using functional components or class components?**


- I am primarily using functional components.

10. **What is `useRef` in React? Explain.**


- `useRef` is a React hook that allows you to create a mutable object that
persists for the lifetime of the component. It can be used to access DOM elements
directly or to hold a mutable value that doesn’t trigger re-renders when changed.

11. **What is a common component in ReactJS?**


- A common component is a reusable piece of UI that can be used across
different parts of an application, like buttons, form inputs, or modal dialogs.

12. **Have you used reusable components in your project, like tables?**
- Yes, I have created reusable components such as tables, buttons, and form
inputs to maintain consistency and reduce code duplication.

13. **How do you get data from an API and display it in the UI in ReactJS? How do
you handle errors? (Example: employee data with id, name, salary)**
```javascript
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const EmployeeList = () => {


const [employees, setEmployees] = useState([]);
const [error, setError] = useState(null);

useEffect(() => {
axios.get('/api/employees')
.then(response => setEmployees(response.data))
.catch(error => setError(error.message));
}, []);

if (error) {
return <div>Error: {error}</div>;
}

return (
<div>
<ul>
{employees.map(emp => (
<li key={emp.id}>{emp.name} - ${emp.salary}</li>
))}
</ul>
</div>
);
};

export default EmployeeList;


```

14. **Are you using CSS in your project?**


- Yes, I am using CSS for styling the components.

15. **Write code to change the color of text in a `div` or `span` when data is
posted.**
```javascript
import React, { useState } from 'react';

const ChangeTextColor = () => {


const [color, setColor] = useState('black');

const handleSubmit = (e) => {


e.preventDefault();
setColor('blue');
};

return (
<div>
<form onSubmit={handleSubmit}>
<button type="submit">Post Data</button>
</form>
<div style={{ color: color }}>This text will change color when data is
posted.</div>
</div>
);
};

export default ChangeTextColor;


```

## Java Questions
16. **Which version of Java are you using? (Java 8, familiar with Java 17)**
- I am using Java 8 and familiar with Java 17.

17. **Write a custom exception in Java and use it.**


```java
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

public class TestCustomException {


public static void main(String[] args) {
try {
validateAge(15);
} catch (CustomException e) {
e.printStackTrace();
}
}

static void validateAge(int age) throws CustomException {


if (age < 18) {
throw new CustomException("Age is not valid");
}
}
}
```

18. **Implement a method in Java to check if a string is present in a list.**


```java
import java.util.List;

public class StringChecker {


public static boolean isStringPresent(List<String> list, String str) {
return list.contains(str);
}
}
```

19. **Write Java code to remove repeated strings from a list.**


```java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicates {


public static List<String> removeDuplicates(List<String> list) {
Set<String> set = new HashSet<>(list);
return new ArrayList<>(set);
}
}
```

20. **How do you provide security in Spring Boot?**


- Security in Spring Boot is provided through Spring Security, which offers
authentication, authorization, and other security features. It can be configured using
Java configuration and annotations.

21. **Explain how JWT token-based authentication works briefly.**


- JWT token-based authentication works by generating a token after a user
successfully logs in. This token is then sent with each subsequent request in the
Authorization header. The server validates the token to authenticate the user.

22. **What is the use of the `@Transactional` annotation in Spring Data?**


- The `@Transactional` annotation in Spring Data is used to manage
transactions declaratively. It ensures that a method runs within a transaction and
manages commit or rollback based on the method’s execution.

23. **Have you used threads in your project?**


- Yes, I have used threads in my project to handle concurrent processing tasks
like processing multiple requests simultaneously.
24. **How do you limit API calls in Spring Boot?**
- API calls in Spring Boot can be limited using rate-limiting libraries like Bucket4j
or implementing custom rate-limiting logic using interceptors.

25. **Have you created any custom annotations in Spring Boot?**


- Yes, I have created custom annotations to encapsulate repetitive logic and
apply cross-cutting concerns.

26. **Create a Age validation custom annotation.**


- Steps
1. **Create the Annotation Interface**
2. **Create the Validator Class**
3. **Apply the Custom Annotation**

#### 1. Create the Annotation Interface

First, create a custom annotation interface for DOB validation.

```java
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Constraint(validatedBy = DOBValidator.class)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidDOB {
String message() default "Invalid Date of Birth";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
```

#### 2. Create the Validator Class

Next, implement the validator class that will contain the logic for validating the DOB.

```java
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDate;

public class DOBValidator implements ConstraintValidator<ValidDOB, LocalDate> {

@Override
public void initialize(ValidDOB constraintAnnotation) {
// Initialization code if necessary
}

@Override
public boolean isValid(LocalDate dob, ConstraintValidatorContext context) {
if (dob == null) {
return false; // or true, based on whether null is considered valid
}
// Check if the DOB is in the past
return dob.isBefore(LocalDate.now());
}
}
```

27. **Have you used a logger in your Spring Boot project?**


- Yes, I have used SLF4J with Logback for logging in my Spring Boot project.

28. **How can you see which controller API methods are running?**
- You can see which controller API methods are running by enabling logging for
HTTP requests in Spring Boot or using tools like Actuator to monitor endpoints.

29. **How do you create a Spring Boot project?**


- A Spring Boot project can be created using Spring Initializr, which generates a
project structure with the necessary dependencies and configurations.

30. **What does Spring Starter provide?**


- Spring Starter provides pre-configured templates for specific functionalities like
web, security, JPA, etc., making it easier to set up a Spring Boot project.

31. **Which dependencies do you commonly use in Spring Boot?**


- Common dependencies include Spring Boot Starter Web, Spring Boot Starter
Data JPA, Spring Boot Starter Security, and Spring Boot Starter Test.

32. **Which annotations do you use in Spring Boot?**


- Common annotations include `@SpringBootApplication`, `@RestController`,
`@RequestMapping`, `@Autowired`, `@Entity`, `@Repository`, and `@Service`.

33. **Which annotations do you use in JUnit tests?**


- Common annotations include `@Test`, `@BeforeEach`, `@AfterEach`,
`@Mock`, `@InjectMocks`, and `@RunWith`.

34. **Which libraries do you use for JUnit tests?**


- Common libraries include JUnit 5, Mockito, and Spring Boot Test.
# Java Full Stack Interview Questions for Cognizant
## First Round Assessment

### Coding Questions


1. **Question 1: Implement a React component that filters a list of transactions
based on an input date and sorts the list based on the amount when the amount
header is clicked**

3. **Question 2:Implement a Spring Boot application with POST, GET, and DELETE
APIs. Include proper response statuses and separate the controller, service, and
repository layers**
### 4 Multiple Choice Questions

## Technical Round 1 - Cognizant Interview

### 1. Self Introduction


**Answer:** [Provide a brief introduction about yourself, your experience, and your
technical expertise.]

### 2. About your project


**Answer:** [Explain your project, its objectives, the technologies used, and your role
in it.]

### 3. Have you worked on GCP and deployed any project in GCP?
**Answer:** [Yes/No. If yes, explain the project and deployment process.]

### 4. How many React projects have you worked on?


**Answer:** [State the number of projects and briefly describe each.]

### 5. Explain props in React.


**Answer:** Props are short for properties and are used to pass data from one
component to another in React.

### 6. How to pass data from child to parent in React.


**Answer:** By passing a function as a prop to the child component and then calling
that function in the child component with the data you want to pass.

### 7. How to validate props in React.


**Answer:** By using PropTypes, a library for type-checking props.

#### 8. Have you used reusable components in React? Give an example.


**Answer:** Yes, for example, a Button component that can be used across different
parts of an application.

### 9. Explain lazy loading in React.


**Answer:** Lazy loading in React is a technique for delaying the loading of non-
critical resources during the initial loading phase.
### 10. What is React.lazy?
**Answer:** `React.lazy` is a function that lets you render a dynamic import as a
regular component.

### 11. What are React fragments?


**Answer:** React fragments allow you to group a list of children without adding
extra nodes to the DOM.

### 12. Difference between fragment and div tag in React.


**Answer:** A fragment does not add an extra node to the DOM, whereas a div does.

### 13. Does using div instead of fragment take extra memory?
**Answer:** Yes, using div adds an extra node to the DOM, which can consume
more memory.

### 14. Which hooks have you used in React?


**Answer:** `useState`, `useEffect`, `useContext`, `useReducer`, `useCallback`,
`useMemo`, `useRef`, etc.

### 15. Explain useCallback hook.


**Answer:** `useCallback` returns a memoized callback function that only changes if
one of its dependencies changes.

### 16. Explain useEffect.


**Answer:** `useEffect` is a hook that runs side effects in function components. It can
be used for data fetching, direct DOM updates, and more.

### 17. What is a dependency array in useEffect?


**Answer:** The dependency array in `useEffect` specifies when the effect should be
re-run based on the changes in the array items.

### 18. How do you call APIs in React?


**Answer:** By using `fetch`, `axios`, or other HTTP client libraries within a
`useEffect` hook or event handler.

### 19. Explain the API intersection observer for lazy loading.
**Answer:** The Intersection Observer API is used to asynchronously observe
changes in the intersection of a target element with an ancestor element or the top-
level document’s viewport.

### 20. What do you use for state management in React?


**Answer:** `useState`, `useReducer`, Context API, Redux, etc.

### 21. What is Context API in React?


**Answer:** The Context API provides a way to pass data through the component
tree without having to pass props down manually at every level.

### 22. Do you know Redux?


**Answer:** Yes, Redux is a state management library for JavaScript applications,
used to manage the application state in a predictable way.
### 23. How do you memorize in React?
**Answer:** By using `useMemo` and `useCallback` hooks to memoize values and
functions.

### 24. Using map, write any code in JavaScript.


**Answer:**
```javascript
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
```

### 25. What is the return type of map and forEach in JavaScript?
**Answer:** `map` returns a new array, `forEach` returns `undefined`.

### 26. Write and explain a callback function in JavaScript.


**Answer:**
```javascript
function fetchData(callback) {
setTimeout(() => {
callback('Data received');
}, 1000);
}

fetchData(data => {
console.log(data); // Data received
});
```
A callback function is a function passed into another function as an argument, which
is then invoked inside the outer function.

### 27. Write a code for a promise example.


**Answer:**
```javascript
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise resolved');
}, 1000);
});

promise.then(data => {
console.log(data); // Promise resolved
});
```

### 28. Have you used async and await in JavaScript?


**Answer:** Yes, `async` and `await` are used to handle asynchronous operations in
a more readable way.
### 29. What is callback hell in React?
**Answer:** Callback hell refers to the situation where callbacks are nested within
other callbacks, leading to difficult-to-read and maintain code.

### 30. How do you handle errors in ReactJS?


**Answer:** By using `try-catch` blocks, error boundaries, and error handling in
promises.

### 31. If we are displaying some employee data and the employee is null, how can
you handle it in React code?
**Answer:** By using conditional rendering to check if the employee data is null
before attempting to display it.

### 32. Have you used the ?? operator in React?


**Answer:** Yes, the `??` (nullish coalescing) operator is used to provide a fallback
value if the left-hand operand is null or undefined.

### 33. Which Java version are you using?


**Answer:** [Specify the Java version you are using.]

### 34. What are the new features in Java 8?


**Answer:** Lambda expressions, functional interfaces, Stream API, new Date and
Time API, Optional class, and more.

### 35. Write a code to display today’s date and the date one month before using
Java 8 features.
**Answer:**
```java
import java.time.LocalDate;

public class DateExample {


public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate oneMonthBefore = today.minusMonths(1);
System.out.println("Today: " + today);
System.out.println("One Month Before: " + oneMonthBefore);
}
}
```

### 36. Write code to display age difference using the Period class.
**Answer:**
```java
import java.time.LocalDate;
import java.time.Period;

public class AgeDifference {


public static void main(String[] args) {
LocalDate birthDate = LocalDate.of(1990, 1, 1);
LocalDate today = LocalDate.now();
Period age = Period.between(birthDate, today);
System.out.println("Age: " + age.getYears() + " years, " + age.getMonths() + "
months, " + age.getDays() + " days.");
}
}
```

### 37. What is a functional interface in Java?


**Answer:** A functional interface is an interface with exactly one abstract method,
which can be used as a target for lambda expressions and method references.

### 38. Write a custom functional interface.


**Answer:**
```java
@FunctionalInterface
public interface MyFunctionalInterface {
int sum(int a, int b);
}

// Example usage
public class FunctionalInterfaceExample {
public static void main(String[] args) {
// Implementing the sum method using a lambda expression
MyFunctionalInterface addition = (a, b) -> a + b;

// Executing the sum method


int result = addition.sum(5, 3);
System.out.println("Sum: " + result); // Sum: 8
}
}

```

### 39. Why use the sum method instead of the apply method in Java?
**Answer:**

In the context of the custom functional interface, the `sum` method is specifically
named and defined to perform a summation operation on two integers. Here's why
using the `sum` method instead of a more generic method name like `apply` can be
advantageous:

1. **Clarity and Intent**: Naming the method `sum` clearly indicates its purpose is to
add two numbers. This makes the code more readable and the intent of the method
obvious to anyone who reads it.

2. **Domain-Specific Naming**: In this case, the interface is designed for summing


two integers. Using a domain-specific name like `sum` rather than a generic name
like `apply` aligns with the single-responsibility principle and makes the code easier
to understand and maintain.
3. **Consistency with Functional Interfaces**: While the standard functional
interfaces like `Function` use generic names like `apply` to support a wide range of
operations, custom functional interfaces can benefit from specific names that denote
the exact operation they perform.

Example with `apply`:


```java
@FunctionalInterface
public interface MyFunctionalInterface {
int apply(int a, int b);
}

// Usage
public class FunctionalInterfaceExample {
public static void main(String[] args) {
MyFunctionalInterface addition = (a, b) -> a + b;
int result = addition.apply(5, 3);
System.out.println("Result: " + result); // Result: 8
}
}
```

Example with `sum`:


```java
@FunctionalInterface
public interface MyFunctionalInterface {
int sum(int a, int b);
}

// Usage
public class FunctionalInterfaceExample {
public static void main(String[] args) {
MyFunctionalInterface addition = (a, b) -> a + b;
int result = addition.sum(5, 3);
System.out.println("Sum: " + result); // Sum: 8
}
}
```

Using `sum` in the custom functional interface makes the purpose of the method
clear and specific, enhancing code readability and maintainability.

### 40. Why do you need a custom functional interface? Give an example.
**Answer:** Custom functional interfaces are needed when you want to define a
specific contract that doesn't match existing functional interfaces.
```java
@FunctionalInterface
public interface StringConcatenator {
String concatenate(String a, String b);
}
```

### 41. What are streams in Java?


**Answer:** Streams represent a sequence of elements supporting sequential and
parallel aggregate operations.

### 42. Explain stream functions.


**Answer:** Stream functions include operations like `filter`, `map`, `reduce`,
`collect`, `forEach`, `sorted`, etc., used to process collections of objects.

### 43. Find the first non-repeated character using streams (code).
**Answer:**
```java
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FirstNonRepeated {


public static void main(String[] args) {
String input = "swiss";
Character result = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,
Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);

System.out.println("First non-repeated character: " + result);


}
}
```

### 44 Given two arrays, arr1 = [4,2,3,4,6] and arr2 = [6,8,2], the output should be
distinct array [2,3,4,6,8].
**Answer:**
```java
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

public class MergeArrays {


public static void main(String[] args) {
Integer[] arr1 = {4, 2, 3, 4, 6};
Integer[] arr2 = {6, 8, 2};
Set<Integer> resultSet = new TreeSet<>(Arrays.asList(arr1));
resultSet.addAll(Arrays.asList(arr2));
System.out.println(resultSet); // [2, 3, 4, 6, 8]
}
}
```

### 45. What is Spring Boot?


**Answer:** Spring Boot is a framework for building production-ready Spring
applications quickly with convention over configuration.

### 46. What are the basic annotations in Spring Boot?


**Answer:** `@SpringBootApplication`, `@RestController`, `@RequestMapping`,
`@Autowired`, etc.

### 47. What is Spring Security?


**Answer:** Spring Security is a framework that focuses on providing authentication
and authorization to Spring applications.

### 48. What is method-level security?


**Answer:** Method-level security allows you to apply security rules directly on
methods using annotations like `@PreAuthorize` and `@Secured`.

### 49. What is the difference between @Component and @Bean?


**Answer:** `@Component` is used to denote a class as a Spring component, while
`@Bean` is used to declare a bean inside a configuration class.

### 50. What is the difference between @Primary and @Qualifier?


**Answer:** `@Primary` is used to give a higher preference to a bean when multiple
beans of the same type exist, while `@Qualifier` is used to specify which bean to use
when multiple options are available.

### 51. What is the difference between @Controller and @RestController?


**Answer:** `@Controller` is used for traditional MVC controllers, returning views.
`@RestController` combines `@Controller` and `@ResponseBody`, returning
JSON/XML responses directly.

### 52. Given the following structure, create an entity class in Spring Boot using JPA
annotations.
```json
{
"empId": "",
"empName": "",
"email": "",
"department": {
"deptId": "",
"deptName": "",
"projects": [
{
"projectId": "",
"projectName": ""
},
{
"projectId": "",
"projectName": ""
}
]
}
}
```
**Answer:**
```java
import javax.persistence.*;
import java.util.List;

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long empId;
private String empName;
private String email;

@ManyToOne
@JoinColumn(name = "deptId")
private Department department;

// Getters and Setters


}

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long deptId;
private String deptName;

@OneToMany(mappedBy = "department", cascade = CascadeType.ALL)


private List<Project> projects;

// Getters and Setters


}

@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long projectId;
private String projectName;

@ManyToOne
@JoinColumn(name = "deptId")
private Department department;

// Getters and Setters


}
```

## Final Round - Cognizant Interview

### 1. Explain your experience in React projects and the components you have
worked on.
**Answer:** I have worked on several React projects, including a bank application
where I primarily focused on the user registration page and transaction data
handling. I have worked with various components such as forms, modals, tables, and
custom reusable components.

### 2. What is the purpose of Context API?


**Answer:** The Context API is used to share data across the component tree
without passing props down manually at every level. It helps manage state globally,
making it easier to handle shared data like user authentication, themes, and settings.

### 3. Have you passed data through the backend using authentication via headers
or body?
**Answer:** Yes, I have passed data through the backend using authentication via
headers. Typically, I use JWT tokens in the headers for secure communication
between the client and server.

### 4. How do you validate your data and which components have you used in your
project?
**Answer:** I validate data using Formik along with Yup for schema validation.
Formik handles form state management and validation, while Yup is used for
defining validation schemas.

### 5. Are you using Formik in your project globally or in every component?
**Answer:** I use Formik in every component where form handling is required. This
ensures each form has its own state and validation logic.

### 6. How do you validate passwords in your ReactJS application?


**Answer:** I validate passwords using Formik and Yup. Yup allows me to define
complex validation rules, such as minimum length, inclusion of special characters,
and matching confirmation passwords.

### 7. Have you created any reusable components in your project?


**Answer:** Yes, I have created several reusable components, such as input fields,
buttons, modals, and form validation schemas. These components help maintain
consistency and reduce code duplication.

### 8. For security purposes, are you passing JWT tokens from client-side to server-
side?
**Answer:** Yes, I pass JWT tokens from the client-side to the server-side through
HTTP headers to ensure secure communication and authentication.

### 9. How is JWT working, and are you validating it on the server-side or client-
side?
**Answer:** JWT tokens are generated upon user authentication and sent to the
client. They are then included in the HTTP headers for subsequent requests.
Validation is done on the server-side to ensure the token's authenticity and to grant
access to protected routes.

### 10. How do you test your React components?


**Answer:** I test my React components using tools like Jest and React Testing
Library. These tools allow me to write unit tests and integration tests to ensure
component functionality and behavior.

### 11. How do you improve performance in your components?


**Answer:** I improve performance by using techniques such as memoization with
`React.memo`, optimizing re-renders with `useCallback` and `useMemo`, lazy
loading components with `React.lazy`, and ensuring efficient state management.

### 12. Have you used refs in your project?


**Answer:** Yes, I have used refs for accessing DOM elements directly, managing
focus, and integrating with third-party libraries where direct DOM manipulation is
required.

### 13 What are the key features introduced in ES6?

**Answer:**
1. **Arrow Functions:** Provides a shorter syntax for writing functions.
```javascript
const add = (a, b) => a + b;
```

2. **Classes:** Simplifies the creation of objects and inheritance.


```javascript
class Person {
constructor(name) {
this.name = name;
}

greet() {
console.log(`Hello, my name is ${this.name}`);
}
}

const john = new Person('John');


john.greet();
```

3. **Template Literals:** Allows string interpolation and multi-line strings.


```javascript
const name = 'John';
const message = `Hello, ${name}!`;
console.log(message);
```

4. **Default Parameters:** Enables function parameters to have default values.


```javascript
function greet(name = 'Guest') {
console.log(`Hello, ${name}`);
}

greet(); // Hello, Guest


```

5. **Destructuring Assignment:** Extracts values from arrays or objects into distinct


variables.
```javascript
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name, age); // John 30

const [first, second] = [10, 20];


console.log(first, second); // 10 20
```

6. **Rest and Spread Operators:** Used with arrays and objects.


```javascript
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3)); // 6

const arr1 = [1, 2, 3];


const arr2 = [...arr1, 4, 5, 6];
console.log(arr2); // [1, 2, 3, 4, 5, 6]

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
```

7. **Promises:** For asynchronous programming.


```javascript
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Success!'), 1000);
});

promise.then(result => console.log(result)); // Success!


```

8. **Modules:** Enables import and export of modules.


```javascript
// module.js
export const name = 'John';

// main.js
import { name } from './module.js';
console.log(name); // John
```

9. **Enhanced Object Literals:** Makes object creation easier.


```javascript
const name = 'John';
const person = {
name,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};

person.greet(); // Hello, my name is John


```

10. **Let and Const:** Introduces block-scoped variables and constants.


```javascript
let variable = 'I can be reassigned';
const constant = 'I cannot be reassigned';

variable = 'New value';


console.log(variable); // New value

// constant = 'New value'; // Error: Assignment to constant variable


```

---

### 14. What is the difference between a React functional component and an arrow
component?

**Answer:**
- **React Functional Component:**
A React functional component is a JavaScript function that returns a React
element. It can be written using the `function` keyword.
```javascript
function MyComponent() {
return <div>Hello, World!</div>;
}
```
- **Arrow Component:**
An arrow component is a functional component defined using the ES6 arrow
function syntax. It also returns a React element.
```javascript
const MyComponent = () => {
return <div>Hello, World!</div>;
}
```

**Key Differences:**
1. **Syntax:** Functional components use the `function` keyword, while arrow
components use the arrow function `=>` syntax.
2. **`this` Binding:** Arrow functions do not have their own `this` context, inheriting it
from the parent scope. Functional components with the `function` keyword have their
own `this` context, which can be useful in class components but less so in functional
components.
3. **Conciseness:** Arrow functions are often more concise and can be written in a
single line if the function body is simple.

---

### 15 Why would you use an arrow function in a React component?

**Answer:**
1. **Lexical `this` Binding:** Arrow functions do not have their own `this` context and
inherit `this` from the parent scope. This prevents common mistakes with `this`
binding in class components.
```javascript
class MyComponent extends React.Component {
handleClick = () => {
console.log(this); // `this` refers to the component instance
}

render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
```

2. **Simplified Syntax:** Arrow functions provide a more concise and readable


syntax, especially for simple functions.
```javascript
const MyComponent = () => <div>Hello, World!</div>;
```

3. **No Need for Binding:** In class components, methods defined with arrow
functions do not need to be explicitly bound in the constructor, reducing boilerplate
code.
```javascript
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this); // Not needed with arrow
functions
}

handleClick() {
console.log(this); // `this` is undefined without binding
}

render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
```

4. **Consistency:** Using arrow functions throughout your codebase can provide


consistency, especially when working with functional components and hooks.

......etc (General Questions && Project-Oriented Questions)

## HR Round - Cognizant Interview


- salary & project etc....

## Ford Motor Client Interview

1. **Can you provide a brief self-introduction and explain your current project?**

- **Answer:** This question typically requires a personalized response where you


introduce yourself, your background, skills, and experience. Followed by a brief
description of your current project, including its goals, technologies used, and your
role in the project.

2. **Given the string `String st = "Win Win!!! You have got a lottery";`, write a Java
program using stream that:**
- **Processes this string to determine if it should be classified as "Spam" or "Not
Spam".**
- **Counts the occurrences of the words "win" and "lottery".**
- **If the count is 2.5 or less, classify the string as "Not Spam"; otherwise, classify
it as "Spam".**

```java
import java.util.Arrays;

public class SpamChecker {


public static void main(String[] args) {
String st = "Win Win!!! You have got a lottery";
long ans = Arrays.stream(st.toLowerCase().split("\\s+"))
.map(word -> word.replaceAll("[^a-zA-Z]", ""))
.filter(e -> e.equals("win") || e.equals("lottery"))
.count();

String result = ans <= 2.5 ? "Not Spam" : "Spam";


System.out.println(result);
}
}
```

3. **Is `count` a terminal operator or an intermediate operator in Java Streams?**

- **Answer:** `count` is a terminal operator in Java Streams. It triggers the


processing of the stream and produces a result.

4. **What is upcasting and downcasting in Java?**

- **Answer:**
- **Upcasting:** Converting a subclass reference to a superclass reference. It is
implicit and safe, e.g., `Dog dog = new Dog(); Animal animal = dog;`
- **Downcasting:** Converting a superclass reference back to a subclass
reference. It is explicit and requires a cast, e.g., `Animal animal = new Dog(); Dog
dog = (Dog) animal;` It can cause a `ClassCastException` if the object is not actually
an instance of the subclass.

5. **For a music player where you want to add and remove songs in middle, which
collection is suitable and why?**

- **Answer**:For a music player where you need to frequently add and remove
songs in the middle of the collection, a **`LinkedList`** is more suitable compared to
an `ArrayList`. Here's why:

- **Efficient Insertions/Deletions**: `LinkedList` provides constant time complexity


(O(1)) for inserting and deleting elements if you have a reference to the node where
the operation needs to occur. This is because it involves only changing pointers
between nodes, which is efficient.

- **No Resizing Overhead**: Unlike `ArrayList`, which requires resizing and


copying elements to a new array when it grows, `LinkedList` does not require
resizing. This makes it more efficient for frequent insertions and deletions.
**Sequential Access**: While `LinkedList` has a higher overhead for accessing
elements by index (O(n) time complexity), it excels in scenarios where you are
performing many insertions and deletions rather than random access.

6. **What is the difference between `map` and `flatMap` in Java Streams?**

- **Answer:**
- **`map`:** Transforms each element in the stream into another object. It
applies a function to each element and returns a stream of the results.
- **`flatMap`:** Transforms each element into a stream of objects and then
flattens these streams into a single stream. It is used when the transformation results
in multiple elements for each input element.

7. **What are fail-fast and fail-safe iterators, and how can you overcome issues
related to them?**

- **Answer:**
- **Fail-fast iterators:** Throw a `ConcurrentModificationException` if the
collection is modified while iterating. To avoid issues, use synchronized collections or
concurrent collections like `CopyOnWriteArrayList`.
- **Fail-safe iterators:** Do not throw exceptions if the collection is modified.
They work on a clone of the collection, e.g., `ConcurrentHashMap` provides fail-safe
iterators.

8. **Which databases have you worked with?**

- **Answer:** This answer should be specific to your experience. Common


databases include MySQL, PostgreSQL, Oracle, SQL Server, MongoDB, etc.

9. **How would you design table structures for a scenario where a customer can
place multiple orders, and each order can contain multiple products?**

- **Answer:**
```sql
CREATE TABLE Customer (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(100)
);

CREATE TABLE Product (


product_id INT PRIMARY KEY,
product_name VARCHAR(100),
price DECIMAL
);

CREATE TABLE `Order` (


order_id INT PRIMARY KEY,
customer_id INT,
order_date DATE,
FOREIGN KEY (customer_id) REFERENCES Customer(customer_id)
);

CREATE TABLE OrderProduct (


order_id INT,
product_id INT,
quantity INT,
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES `Order`(order_id),
FOREIGN KEY (product_id) REFERENCES Product(product_id)
);
```

10. **Write a query to get the customer name and total order price for customers
named "Bharath" where the order is placed today.**

- **Answer:**
```sql
SELECT c.customer_name, SUM(p.price * op.quantity) AS total_order_price
FROM Customer c
JOIN `Order` o ON c.customer_id = o.customer_id
JOIN OrderProduct op ON o.order_id = op.order_id
JOIN Product p ON op.product_id = p.product_id
WHERE c.customer_name = 'Bharath'
AND o.order_date = CURDATE()
GROUP BY c.customer_name;
```

11. **Given the following Spring Boot code, will it work?**


```java
@Component
public class Controller {
@Autowired
private Filter filter;
}

public interface Filter {


}

@Component
public class Abc implements Filter {
}

@Component
public class Abc1 implements Filter {
}
```

- **Answer:** No, it will not work as intended. Spring will not be able to resolve
the `Filter` bean because there are multiple implementations (`Abc` and `Abc1`). You
need to use `@Qualifier` to specify which implementation should be injected.

12. **How would you fix the issue in the Spring Boot code provided above?**

- **Answer:** Use `@Qualifier` to specify which bean to inject:


```java
@Component
public class Controller {
@Autowired
@Qualifier("abc")
private Filter filter;
}

@Component("abc")
public class Abc implements Filter {
}

@Component("abc1")
public class Abc1 implements Filter {
}
```

13. **What is the difference between `@Primary` and `@Qualifier` in Spring?**

- **Answer:**
- **`@Primary`:** Indicates the preferred bean when multiple candidates are
available for autowiring. It is used at the bean definition level.
- **`@Qualifier`:** Used to specify which bean to inject when multiple beans of
the same type are available. It is used at the injection point.

14. **How can you ensure that an API request processes data and responds while
sending a notification to another API simultaneously in Spring Boot?**

- **Answer:** Use asynchronous processing with `@Async` or


`CompletableFuture` to handle the notification separately from the main request
processing. Here’s an example:
```java
@Service
public class MyService {
@Async
public CompletableFuture<Void> sendNotification() {
// Code to send notification
return CompletableFuture.completedFuture(null);
}

public void processRequest() {


// Process request
sendNotification(); // Non-blocking call
}
}
```

15. **How do you communicate between one API and another API?**

- **Answer:** You can use HTTP clients such as `RestTemplate`, `WebClient`


(for reactive applications), or external libraries to make API calls. For example, using
`RestTemplate`:
```java
@Autowired
private RestTemplate restTemplate;

public String callAnotherApi() {


String url = "http://example.com/api";
return restTemplate.getForObject(url, String.class);
}
```

16. **What is `Mono` and `Flux` in WebClient?**

- **Answer:**
- **`Mono`:** Represents a single asynchronous value or an empty value.
- **`Flux`:** Represents a stream of 0 to N asynchronous values.

17. **What is a Kafka server?**

- **Answer:** Apache Kafka is a distributed event streaming platform used for


building real-time data pipelines and streaming applications. It is designed for high-
throughput, fault tolerance, and scalability.

18. **Given a controller with a GET API that takes a number as a `@PathVariable`,
and returns a 404 Not Found for invalid values, how would you implement a JUnit
test case for this controller?**

- **Answer:**
```java
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
public void testGetApiNotFound() throws Exception {
mockMvc.perform(get("/api/{number}", 999)) // assuming 999 is invalid
.andExpect(status().isNotFound());
}
}
```

19. **How do you configure and connect a Spring Boot application to a database,
and how does it work?**

- **Answer:** Configure the `application.properties` or `application.yml` with


database connection details:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.dd

l-auto=update
```
Spring Boot uses these properties to configure the `DataSource`,
`EntityManagerFactory`, and `TransactionManager` beans automatically.

20. **How can you determine if the application is connected to MySQL or Oracle?**

- **Answer:** Check the `application.properties` or `application.yml` for the JDBC


URL. The URL usually contains the database type, e.g., `jdbc:mysql://` for MySQL or
`jdbc:oracle:thin:@` for Oracle.

21. **What is the `@Transactional` annotation in Spring?**

- **Answer:** The `@Transactional` annotation is used to define the scope of a


single database transaction. It ensures that all operations within the annotated
method are completed successfully before committing the transaction, and rolls back
the transaction in case of errors.

22. **Are you familiar with entity graphs in JPA?**

- **Answer:** Yes, entity graphs in JPA allow you to specify fetch strategies for
entities dynamically. They help in optimizing queries by specifying which related
entities should be fetched eagerly.

23. **Have you used `join` and `joinFetch` in JPA?**

- **Answer:** Yes, `join` is used in JPQL queries to perform joins between


entities, while `joinFetch` is used to fetch related entities eagerly in a single query to
avoid the N+1 select problem.

24. **What are closures in JavaScript, and can you provide an example?**

- **Answer:** Closures are functions that have access to variables from their
outer scope, even after the outer function has finished executing. Example:
```javascript
function outerFunction() {
let outerVariable = 'I am from outer function';
return function innerFunction() {
console.log(outerVariable);
}
}
let closureFunction = outerFunction();
closureFunction(); // Outputs: 'I am from outer function'
```

25. **What is debouncing in JavaScript?**


- **Answer:** Debouncing is a technique used to limit the rate at which a function
is executed. It ensures that a function is not called repeatedly in quick succession,
which helps in optimizing performance. Example:
```javascript
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
}
}
```

26. **What is `useEffect` in React?**

- **Answer:** `useEffect` is a React hook that allows you to perform side effects
in functional components. It is used to handle operations like data fetching,
subscriptions, or manually changing the DOM.

27. **What is the difference between `state` and `props` in React?**

- **Answer:**
- **`state`:** Represents data that changes over time within a component. It is
mutable and managed within the component using `useState` or `this.setState`.
- **`props`:** Short for properties, they are read-only data passed from parent
to child components. Props are immutable and used to pass data and event handlers
between components.

# *Contus Tech walk-in interview*


# First Round
## Assessment - Spring Boot Application

# Technical Round
## Java Questions

### 1. What is the purpose of the `intern` method in Java?


- The `intern` method ensures that all instances of a string with the same content
share the same memory location. It returns a canonical representation of the string,
which is useful for memory optimization and string comparison.

### 2. Explain the internal working process of `HashMap`.


- `HashMap` uses a hash table to store key-value pairs. It calculates a hash code
for each key and uses it to determine the index in an internal array. Collisions are
handled using linked lists or balanced trees. When the load factor exceeds a
threshold, the map is resized and rehashed.
### 3. What is the difference between mutable and immutable objects?
- Mutable objects can be changed after they are created (e.g., `ArrayList`).
Immutable objects cannot be changed after creation (e.g., `String`).

### 4. Why is `String` immutable in Java?


- `String` is immutable for security, synchronization, and performance reasons.
Immutable objects are inherently thread-safe and allow the reuse of string literals.

### 5. How can you create a mutable `String`?


- Use `StringBuilder` or `StringBuffer`, which are mutable versions of `String`.
```java
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
String result = sb.toString(); // "Hello World"
```

### 6. What is a marker interface?


- A marker interface is an interface with no methods or fields. It is used to indicate
or mark a class for a specific purpose (e.g., `Serializable`, `Cloneable`).

### 7. What is a functional interface?


- A functional interface has exactly one abstract method and may have multiple
default or static methods. It is used as a target for lambda expressions and method
references.
```java
@FunctionalInterface
public interface MyFunctionalInterface {
void doSomething();
}
```

### 8. What happens if a class contains two methods with the same name?
- If the methods have different parameter lists, it is method overloading. If the
methods have the same parameter list, it causes a compilation error.

### 9. What is a default method in Java?


- A default method in an interface provides a default implementation. It allows you
to add new methods to interfaces without breaking existing implementations.
```java
public interface MyInterface {
default void defaultMethod() {
System.out.println("Default method");
}
}
```

### 10. How can we access an instance variable inside a static method? (Code)
- Instance variables cannot be accessed directly from static methods. You need to
create an instance of the class to access them.
```java
public class MyClass {
private int instanceVar = 10;

public static void staticMethod() {


MyClass obj = new MyClass();
System.out.println(obj.instanceVar);
}
}
```

### 11. Explain the concept of a linked list


- A linked list is a data structure where each element (node) contains a reference to
the next node. It allows efficient insertion and deletion operations.

### 12. What is the difference between `LinkedList` and `ArrayList` in Java?
- `ArrayList` is backed by a dynamic array, providing O(1) time complexity for
access but O(n) for insertions and deletions. `LinkedList` is backed by a doubly
linked list, providing O(1) time complexity for insertions and deletions but O(n) for
access.

---

## Spring Boot Questions

### 1. How to use two different databases in a single Spring Boot project?
- Configure multiple `DataSource` beans and specify the database details in
`application.properties` or `application.yml`. Use `@Primary` annotation to mark the
default `DataSource`.
```java
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
```

### 2. How to handle exceptions in Spring Boot?


- Use `@ControllerAdvice` to handle exceptions globally. Create methods with
`@ExceptionHandler` to handle specific exceptions.
```java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
return new ResponseEntity<>(ex.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR);
}
}
```

### 3. How to handle a `NullPointerException` in Spring Boot?


- Use `@ExceptionHandler` within a `@ControllerAdvice` to catch
`NullPointerException` and return an appropriate response.
```java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String>
handleNullPointerException(NullPointerException ex) {
return new ResponseEntity<>("Null pointer exception occurred",
HttpStatus.BAD_REQUEST);
}
}
```

### 4. How to fetch a list of DTO data?


- Use a repository method to fetch data and map it to DTOs.
```java
@Repository
public interface MyRepository extends JpaRepository<MyEntity, Long> {
@Query("SELECT new com.example.dto.MyDTO(e.field1, e.field2) FROM
MyEntity e")
List<MyDTO> fetchAllDTOs();
}
```

### 5. How to provide access to a third-party client in Spring Boot?


- Use OAuth or JWT for authentication. Configure security settings to handle
access tokens and permissions.

### 6. How to enable CORS and where do you write the logic
- Use `@CrossOrigin` annotation on controllers or configure it globally.
```java
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://example.com");
}
}
```

### 7. How to enable centralized cross-policy?


- Use `@ControllerAdvice` to handle cross-cutting concerns like error handling or
logging.

### 8. What is the difference between JWT and OAuth?


- JWT (JSON Web Token) is a token format used for securely transmitting
information between parties. OAuth is an authorization framework that uses tokens
(like JWT) for securing API access.

### 9. Explain the internal working process of JWT


- JWT consists of a header, payload, and signature. The header and payload are
base64-encoded and the signature is created using a secret key. It is used for
stateless authentication.

### 10. What is Spring Security?


- Spring Security is a framework that provides comprehensive security services for
Java applications, including authentication, authorization, and protection against
common security vulnerabilities.

### 11. What is the use of beans and where do you use them in your application?
- Beans are managed objects within the Spring container. They are used for
dependency injection and are configured in the application context.

### 12. What is the difference between `@Component`, `@Service`, `@Repository`,


and `@Controller`, and what is the use of each?
- `@Component`: Generic stereotype for any Spring-managed component.
- `@Service`: Specialized component for service layer logic.
- `@Repository`: Specialized component for data access logic.
- `@Controller`: Specialized component for web controllers.

### 13. If you use `@Service` in place of `@Controller`, will it work or not?
- It will work but is not recommended. `@Service` is for service layer beans, while
`@Controller` is for handling web requests. Using the wrong annotation may lead to
incorrect behavior or misconfigured components.

### 14. What are the different types of Spring Security?


- Basic Authentication
- Form-based Authentication
- OAuth2
- JWT-based Authentication

### 15. Where are you validating the JWT token in your project?
- JWT tokens are typically validated in a custom filter or within a security
configuration class.

### 16. What architecture are you using to develop your project?
- Describe the architecture such as Microservices, Monolithic, Layered
Architecture, etc.

### 17. How to sort a list of data based on a field using JPA inbuilt methods?
- Use `JpaRepository` methods like `findAll(Sort sort)`.
```java
List<MyEntity> findAll(Sort sort);
```

### 18. How to fetch and sort a list of DTO data in Spring Boot?
- Use repository methods with sorting options or fetch data and sort manually in
service layer.
```java
@Query("SELECT new com.example.dto.MyDTO(e.field1, e.field2) FROM
MyEntity e ORDER BY e.field1")
List<MyDTO> fetchAndSortDTOs();
```

### 19. How to provide third-party client access in Spring Boot?


- Use OAuth2 or API keys to manage third-party client access.

### 20. Explain the use and application of `@Component`, `@Service`,


`@Repository`, and `@Controller`.
- `@Component` is used for generic components, `@Service` for business
services, `@Repository` for data access, and `@Controller
` for web request handling.

### 21. Can you use `@Service` in place of `@Controller`? If yes, what happens?
- Yes, but it is not recommended. `@Service` is intended for business logic and
does not handle web requests, which is the role of `@Controller`.

# Final Round

### 1. What tools have you used in your project?


- In my project, I have used tools such as Git for version control, Jenkins for
continuous integration and deployment, JIRA for task management, and Docker for
containerization.

### 2. Which database did you use in your project?


- We used PostgreSQL as our primary database due to its robustness and
support for complex queries.

### 3. How did you implement JWT authentication in your project?


- We implemented JWT authentication by creating a JWT token on user login,
which includes user roles and expiration time. The token is then verified with each
API request using a JWT filter in our Spring Boot application.

### 4. How did you configure two different databases in your Spring Boot project?
- We configured two different databases by creating separate `DataSource`
beans for each database and using `@Primary` annotation to specify the primary
data source.

### 5. Who provided the database structure in your project?


- The database structure was provided by our database architect, and the
development team collaborated to finalize and optimize it.

### 6. How were tasks assigned and managed in your project on a weekly basis?
- Tasks were assigned and managed using JIRA. Each week, we conducted sprint
planning meetings to assign tasks and track progress through daily stand-ups.

### 7. How did you implement an API gateway in your microservices architecture?
- We implemented an API gateway using Spring Cloud Gateway, which routes
requests to the appropriate microservices and handles cross-cutting concerns like
authentication and rate limiting.

### 8. How did you configure different services in the API gateway?
- We configured different services in the API gateway using route definitions in
the `application.yml` file, specifying the paths and service URLs.

### 9. What is an Eureka Server?


- Eureka Server is a service registry used in microservices architecture for service
discovery, allowing services to find and communicate with each other without
hardcoding their locations.

### 10. How do you handle simultaneous requests from multiple users, and who
determines request preference?
- We handle simultaneous requests using load balancers to distribute the traffic
across multiple instances of our services. Request preference is determined based
on the priority of the request and the resources available.

### 11. What does a Kafka server do?


- A Kafka server is used for real-time data streaming and message brokering,
allowing our microservices to communicate asynchronously and handle large
volumes of data efficiently.

### 12. How do you handle simultaneous requests from a large number of users?
- We handle simultaneous requests from a large number of users using a
combination of load balancing, caching, and scalable microservices architecture to
ensure high availability and performance.

### 13. What issues did you recently encounter with Swagger, and how did you
resolve them?
- We encountered issues with Swagger not displaying certain endpoints correctly.
We resolved them by ensuring all our controllers were properly annotated and by
updating the Swagger configuration to correctly scan all packages.

### 14. How do you upgrade your project, and what technologies are used for
upgrading?
- We upgrade our project by following a continuous integration and deployment
pipeline, using tools like Jenkins and Docker. We also perform thorough testing and
use feature toggles to ensure smooth rollouts.

### 15. What are some issues you faced in your project, and how did you overcome
them?
- One issue we faced was database performance under high load. We overcame
it by optimizing queries, indexing critical fields, and using caching mechanisms to
reduce the load on the database.

### 16.Have you worked with Log4j? If so, what was your experience?
- Yes, I have worked with Log4j for logging in our Spring Boot applications. It has
been effective in providing configurable logging levels and formats,

# HR Round
### Self ,Location, Salary etc.....

1. **Brief about the project:**


- The project is a real-time banking application designed to handle customer
transactions and registration. It includes functionalities such as account
management, transaction processing, and secure data handling using microservices
architecture and deployed on Docker.

2. **Steps to deploy microservices to Docker:**


- 1. **Dockerize each microservice** by creating a `Dockerfile`.
- 2. **Build Docker images** using the `docker build` command.
- 3. **Run containers** using `docker run`, specifying network configurations if
needed.
- 4. **Configure networking** (optional) with Docker Compose or custom
networks.
- 5. **Monitor and scale** using Docker commands or orchestration tools.

3. **Write a SQL query to retrieve first name, last name, age from the customer
table, and item, amount from the item table where age is greater than 25:**
```sql
SELECT c.first_name, c.last_name, c.age, i.item, i.amount
FROM customer c
JOIN item i ON c.customer_id = i.customer_id
WHERE c.age > 25;
```

4. **Explain Actuator in Spring Boot:**


- Actuator provides production-ready features in Spring Boot, such as monitoring
and managing applications via endpoints like health, metrics, and environment
information, making it easier to maintain and troubleshoot services.

5. **What are Servlet and JSP?**


- **Servlet**: A Java class that handles HTTP requests and generates dynamic
web content.
- **JSP (JavaServer Pages)**: A technology that allows embedding Java code
into HTML to create dynamic web pages, simplifying web development by separating
business logic from presentation.

6. **Describe Java Streams and Lambda functions:**


- **Streams**: A sequence of elements supporting functional-style operations to
process collections, like filtering and mapping.
- **Lambda Functions**: Anonymous functions used to implement functional
interfaces, enabling concise and readable code, especially in stream operations.

7. **What are the steps to establish a JDBC connection?**


- 1. **Load the JDBC driver** using `Class.forName()`.
- 2. **Establish a connection** using `DriverManager.getConnection()`.
- 3. **Create a statement object** using `connection.createStatement()`.
- 4. **Execute SQL queries** with `statement.executeQuery()` or
`executeUpdate()`.
- 5. **Close the connection** using `connection.close()`.

8. **Difference between StringBuffer and StringBuilder:**


- **StringBuffer**: Synchronized and thread-safe but slower due to overhead.
- **StringBuilder**: Non-synchronized, faster, and preferable in single-threaded
environments for string manipulation.

9. **How to document request and response options using Swagger, and how to
convert to YAML?**
- Swagger annotations in code (e.g., `@ApiOperation`, `@ApiResponse`)
document API endpoints. Convert the generated Swagger JSON documentation to
YAML using tools like Swagger Editor or online converters.

10. **How do you expose REST API call endpoints?**


- Expose endpoints by annotating controller methods with `@GetMapping`,
`@PostMapping`, etc., and defining the URI paths in Spring Boot applications.

11. **Which mechanism did you use to develop the project?**


- The project was developed using a microservices architecture with Spring Boot
for creating RESTful services, Docker for containerization, and a CI/CD pipeline for
automated deployments.

12. **What are implicit objects in JSP?**


- Implicit objects are pre-defined objects available in JSP for accessing various
functionalities like `request`, `response`, `session`, `application`, `out`, and more,
without explicit declaration.

13. **Create two lists: List 1 (java, aws, oracle, python), List 2 (java, oracle, jquery).
Find common elements and unique elements using Streams in Java code:**

```java
List<String> list1 = Arrays.asList("java", "aws", "oracle", "python");
List<String> list2 = Arrays.asList("java", "oracle", "jquery");
// Common elements
List<String> common = list1.stream()
.filter(list2::contains)
.collect(Collectors.toList());

// Unique elements
List<String> unique = Stream.concat(list1.stream(), list2.stream())
.distinct()
.filter(e -> !(list1.contains(e) && list2.contains(e)))
.collect(Collectors.toList());
```

# Assessment
2 DSA Coding
30 Multiple Choice Questions (MCQs)

# First Round Interview


### 1. Self-introduction
- **Answer:** *********
### 2. Which version of Java are you using?

- **Answer:** I am using Java **.

### 3. Java 8 features

- **Answer:**

1. **Lambda Expressions**: Allows for more concise and readable code by enabling
you to pass behavior as parameters. For example:
```java
(a, b) -> a + b
```

2. **Streams API**: Provides a powerful way to process sequences of elements (like


collections) in a functional style, supporting operations like filtering, mapping, and
reducing. For example:
```java
List<String> list = Arrays.asList("a1", "a2", "b1", "c2");
list.stream()
.filter(s -> s.startsWith("a"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
```

3. **New Date and Time API**: Introduces a new set of classes to handle date and
time with better precision and immutability compared to the old `Date` and
`Calendar` classes. For example:
```java
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
```

4. **Default Methods in Interfaces**: Allows interfaces to have method


implementations, which helps in extending interfaces without breaking existing
implementations. For example:
```java
interface MyInterface {
default void defaultMethod() {
System.out.println("Default implementation");
}
void abstractMethod();
}
```

5. **Optional Class**: Provides a container object which may or may not contain a
value, helping to avoid null checks and NullPointerExceptions. For example:
```java
Optional<String> opt = Optional.of("Hello");
opt.ifPresent(System.out::println); // Prints "Hello"
```

### 4. Java 9 static method

- **Answer:** Java 9 introduced private methods in interfaces that can be static or


non-static to share code between methods.

### 5. List.of method

- **Answer:** `List.of()` creates an immutable list with the provided elements. For
example,
`List<String> list = List.of("A", "B", "C");`.

### 6. Functional interface and example

- **Answer:** A functional interface has exactly one abstract method.


- Example: `@FunctionalInterface public interface Calculator { int add(int a, int b); }`.

### 7. What is Supplier in functional programming

- **Answer:** `Supplier` is a functional interface that provides a result of type `T`


without taking any input.

### 8. Create one functional interface containing add method, static sum method,
default multiple method, and use in main class
- **Answer:**
```java
@FunctionalInterface
public interface Calculator {
int add(int a, int b);

static int sum(int a, int b) {


return a + b;
}

default int multiply(int a, int b) {


return a * b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = (a, b) -> a + b;
System.out.println("Add: " + calc.add(5, 3));
System.out.println("Sum: " + Calculator.sum(5, 3));
System.out.println("Multiply: " + calc.multiply(5, 3));
}
}
```

### 9. Using streams, list of employees and count number of male and female
employees
- **Answer:**
```java
public Map<String, Long> countEmployeesByGender(List<Employee>
employees) {
return employees.stream()
.collect(Collectors.groupingBy(Employee::getGender,
Collectors.counting()));
}
```

### 10. employees.stream().filter(e -> e.getAge() > 18).map(e -> e.remove()).count()


what will be the output

- **Answer:** The output depends on whether `remove()` modifies the original list or
not. If it does, it will be the count of items that are removed. If not, it will be 0.

### 11. What is terminal operations

- **Answer:** Terminal operations produce a result or a side-effect, and they mark


the end of the stream pipeline. Examples include `collect()`, `count()`, and
`forEach()`.

### 12. Spring Boot controller using all annotations POST & GET vehicle details
- **Answer:**
```java

@RestController
@RequestMapping("/vehicles")
public class VehicleController {

@PostMapping
public ResponseEntity<Vehicle> addVehicle(@RequestBody Vehicle vehicle) {
// Save vehicle to database
return ResponseEntity.status(HttpStatus.CREATED).body(vehicle);
}

@GetMapping("/{id}")
public ResponseEntity<Vehicle> getVehicle(@PathVariable Long id) {
// Fetch vehicle from database
Vehicle vehicle = findVehicleById(id);
return ResponseEntity.ok(vehicle);
}
}

```

### 13. What are the issues you faced in Spring Boot development?

- **Answer:** Common issues include configuration errors, dependency conflicts,


and difficulty in debugging complex applications.

### 14. Which version of Spring Boot are you using?

- **Answer:** I am using Spring Boot **.

### 15. Primary & Qualifier annotation in Spring Boot

- **Answer:** `@Primary` specifies the default bean when multiple beans of the
same type exist.
- `@Qualifier` is used to specify which bean to inject when multiple candidates are
available.

### 16. How to use two different databases in a single Spring Boot application

- **Answer:** Configure multiple `DataSource` beans and use `@Primary` to indicate


the default `DataSource`. Use `@Qualifier` to inject the appropriate `DataSource`
where needed.

```java
@Configuration
public class DataSourceConfig {

@Bean
@Primary
@ConfigurationProperties("spring.datasource1")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties("spring.datasource2")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
}

```
### 17. JPA methods and @Query

- **Answer:** JPA methods include `findAll()`, `findById()`, `save()`, and `delete()`.


`@Query` allows defining custom JPQL or SQL queries.

### 18. How to get data for employee {id, name, address{id, location}} and fetch
location based on employee data

- **Answer:**

```java
public interface EmployeeRepository extends JpaRepository<Employee, Long>
{

// Exact match
List<Employee> findByAddressLocation(String location);

// Partial match
List<Employee> findByAddressLocationContaining(String location);
}
```

### 19. Why is React fast and what is virtual DOM

- **Answer:** React is fast due to its use of the virtual DOM, which minimizes direct
manipulation of the actual DOM, reducing performance overhead.

### 20. Virtual DOM internal structure

- **Answer:** The virtual DOM is a lightweight copy of the real DOM. It represents
the UI components as JavaScript objects, which React updates efficiently.

### 21. Which component do you use: functional or class-based

- **Answer:** I use both functional and class-based components, but prefer


functional components due to their simplicity and hooks support.
### 22. Other than useState and useEffect, which hooks do you use

- **Answer:** I use `useContext`, `useReducer`, `useMemo`, and `useCallback`


hooks.

23. What is useContext

- **Answer:** `useContext` allows accessing context values in functional


components, enabling state sharing across the component tree without prop drilling.

### 24. Context API alternate in React

- **Answer:**: Alternatives include Redux for state management or React's


`useState` and `useReducer` for local state.

### 25. Hoisting in JavaScript

- **Answer:** Hoisting refers to JavaScript's behavior of moving variable and function


declarations to the top of their containing scope during compilation.

### 26. What is prototype

- **Answer:** In JavaScript, `prototype` is an object from which other objects inherit


properties and methods. Every JavaScript object has a prototype.

# Second Round Interview -Pair Programming

### 1 Implement `POST` and `GET` APIs for a Vehicle resource in Spring Boot.
Provide the code for repository, service, and controller layers. Include JUnit test
cases for the `POST` and `GET` methods.

**Answer:**

- **Repository Layer:**

```java
import org.springframework.data.jpa.repository.JpaRepository;

public interface VehicleRepository extends JpaRepository<Vehicle, Long> {


}
```

- **Service Layer:**

```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class VehicleService {

@Autowired
private VehicleRepository vehicleRepository;

public List<Vehicle> getAllVehicles() {


return vehicleRepository.findAll();
}

public Vehicle saveVehicle(Vehicle vehicle) {


return vehicleRepository.save(vehicle);
}
}
```

- **Controller Layer:**

```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/vehicles")
@CrossOrigin(origins = "http://localhost:3000")
public class VehicleController {

@Autowired
private VehicleService vehicleService;

@GetMapping
public ResponseEntity<List<Vehicle>> getAllVehicles() {
List<Vehicle> vehicles = vehicleService.getAllVehicles();
return new ResponseEntity<>(vehicles, HttpStatus.OK);
}

@PostMapping
public ResponseEntity<Vehicle> createVehicle(@RequestBody Vehicle
vehicle) {
Vehicle savedVehicle = vehicleService.saveVehicle(vehicle);
return new ResponseEntity<>(savedVehicle, HttpStatus.CREATED);
}
}
```
- **JUnit Test Cases:**

### 1. Repository Layer Test

Since the repository layer interacts directly with the database, you typically use an in-
memory database or a test configuration to test repository methods. For JPA
repositories, the most common approach is to use an embedded H2 database or
similar for integration tests.

**`VehicleRepositoryTest.java`**

```java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
public class VehicleRepositoryTest {

@Autowired
private VehicleRepository vehicleRepository;

@BeforeEach
public void setUp() {
vehicleRepository.deleteAll();
}

@Test
public void testSaveVehicle() {
Vehicle vehicle = new Vehicle();
vehicle.setMake("Ford");
vehicle.setModel("Focus");
vehicle.setYear(2021);

Vehicle savedVehicle = vehicleRepository.save(vehicle);


assertThat(savedVehicle).isNotNull();
assertThat(savedVehicle.getId()).isNotNull();
}

@Test
public void testFindAllVehicles() {
Vehicle vehicle1 = new Vehicle();
vehicle1.setMake("Toyota");
vehicle1.setModel("Corolla");
vehicle1.setYear(2020);
vehicleRepository.save(vehicle1);

Vehicle vehicle2 = new Vehicle();


vehicle2.setMake("Honda");
vehicle2.setModel("Civic");
vehicle2.setYear(2019);
vehicleRepository.save(vehicle2);

List<Vehicle> vehicles = vehicleRepository.findAll();


assertThat(vehicles).hasSize(2);
}
}
```

### 2. Service Layer Test

The service layer test verifies that the service methods are functioning correctly. This
typically involves mocking the repository and ensuring that the service methods
interact with the repository as expected.

**`VehicleServiceTest.java`**

```java
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;


import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class VehicleServiceTest {

@Mock
private VehicleRepository vehicleRepository;

@InjectMocks
private VehicleService vehicleService;

@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testGetAllVehicles() {
Vehicle vehicle1 = new Vehicle();
vehicle1.setMake("Toyota");
vehicle1.setModel("Corolla");
vehicle1.setYear(2020);

Vehicle vehicle2 = new Vehicle();


vehicle2.setMake("Honda");
vehicle2.setModel("Civic");
vehicle2.setYear(2019);

when(vehicleRepository.findAll()).thenReturn(List.of(vehicle1, vehicle2));

List<Vehicle> vehicles = vehicleService.getAllVehicles();


assertThat(vehicles).hasSize(2);
assertThat(vehicles.get(0).getMake()).isEqualTo("Toyota");
assertThat(vehicles.get(1).getMake()).isEqualTo("Honda");
}

@Test
public void testSaveVehicle() {
Vehicle vehicle = new Vehicle();
vehicle.setMake("Ford");
vehicle.setModel("Focus");
vehicle.setYear(2021);

when(vehicleRepository.save(vehicle)).thenReturn(vehicle);

Vehicle savedVehicle = vehicleService.saveVehicle(vehicle);


assertThat(savedVehicle).isNotNull();
assertThat(savedVehicle.getMake()).isEqualTo("Ford");
}
}
```
### 3. Controller Layer Test

Test the controller by mocking the service layer to isolate it. Use MockMvc to perform
HTTP requests to controller endpoints and verify the correct status codes and
response bodies. Ensure to check if the controller handles the HTTP requests as
expected and returns the appropriate responses.

**`VehicleControllerTest.java`**

```java
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import java.util.List;

import static org.mockito.ArgumentMatchers.any;


import static org.mockito.Mockito.when;

@WebMvcTest(VehicleController.class)
public class VehicleControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private VehicleService vehicleService;

@Autowired
private ObjectMapper objectMapper;

@Test
public void testGetAllVehicles() throws Exception {
when(vehicleService.getAllVehicles()).thenReturn(List.of(
new Vehicle(1L, "Toyota", "Corolla", 2020),
new Vehicle(2L, "Honda", "Civic", 2019)
));

mockMvc.perform(MockMvcRequestBuilders.get("/vehicles"))
.andExpect(MockMvcResultMatchers.status().isOk())

.andExpect(MockMvcResultMatchers.jsonPath("$[0].make").value("Toyota"))

.andExpect(MockMvcResultMatchers.jsonPath("$[1].make").value("Honda"));
}

@Test
public void testCreateVehicle() throws Exception {
Vehicle vehicle = new Vehicle();
vehicle.setMake("Ford");
vehicle.setModel("Focus");
vehicle.setYear(2021);

when(vehicleService.saveVehicle(any(Vehicle.class))).thenReturn(vehicle);

mockMvc.perform(MockMvcRequestBuilders.post("/vehicles")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(vehicle)))
.andExpect(MockMvcResultMatchers.status().isCreated())

.andExpect(MockMvcResultMatchers.jsonPath("$.make").value("Ford"));
}
}
```

### 2 Implement a React component that fetches vehicle data from the backend,
displays it in a grid, and write a test case for the component.

**Answer:**

- **React Component:**

**`VehicleList.js`**

```jsx
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const VehicleList = () => {


const [vehicles, setVehicles] = useState([]);
const [error, setError] = useState(null);

useEffect(() => {
axios.get('http://localhost:8080/vehicles')
.then(response => {
setVehicles(response.data);
})
.catch(error => {
setError("There was an error fetching the vehicles.");
console.error("There was an error fetching the vehicles!", error);
});
}, []);

return (
<div className="vehicle-list">
<h1>Vehicle List</h1>
{error && <p className="error">{error}</p>}
<div className="grid-container">
{vehicles.map(vehicle => (
<div key={vehicle.id} className="grid-item">
<h3>{vehicle.make} {vehicle.model}</h3>
<p>Year: {vehicle.year}</p>
</div>
))}
</div>
</div>
);
};

export default VehicleList;


```

**CSS (for grid layout):**

**`App.css`**

```css
.vehicle-list {
padding: 20px;
}

.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 20px;
}

.grid-item {
border: 1px solid #ddd;
padding: 10px;
border-radius: 5px;
}
```

- **React Test Case:**

**`VehicleList.test.js`**

```jsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import axios from 'axios';
import VehicleList from './VehicleList';
import '@testing-library/jest-dom/extend-expect';

// Mocking Axios
jest.mock('axios');

test('renders vehicle list', async () => {


// Mocking the response data
axios.get.mockResolvedValue({
data: [
{ id: 1, make: 'Toyota', model: 'Corolla', year: 2020 },
{ id: 2, make: 'Honda', model: 'Civic', year: 2019 },
],
});
render(<VehicleList />);

// Assertions
expect(await screen.findByText(/Toyota Corolla/i)).toBeInTheDocument();
expect(await screen.findByText(/Honda Civic/i)).toBeInTheDocument();
});

test('handles error response', async () => {


// Mocking the error response
axios.get.mockRejectedValue(new Error("Network Error"));

render(<VehicleList />);

// Assertions
expect(await screen.findByText(/There was an error fetching the
vehicles./i)).toBeInTheDocument();
});
```

# Ford Interview
## Java/Spring Boot
### 1. Explain CSR (Cross-Site Request) and how you handle it in your applications.

Cross-Site Request Forgery (CSRF) is an attack that tricks the victim into submitting
a malicious request. It exploits the trust a site has in the user's browser. To handle
CSRF in Spring Boot, you can use the CSRF protection provided by Spring Security.
By default, CSRF protection is enabled in Spring Security.

```java
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfig
urerAdapter;

public class SecurityConfig extends WebSecurityConfigurerAdapter {


@Override
protected void configure(HttpSecurity http) throws Exception {
http

.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.authorizeRequests()
.anyRequest().authenticated();
}
}
```
### 2. What is JWT Security, and how do you implement it?

JWT (JSON Web Token) Security is a method for securely transmitting information
between parties as a JSON object. This information can be verified and trusted
because it is digitally signed. JWTs can be signed using a secret (with the HMAC
algorithm) or a public/private key pair (using RSA or ECDSA).
Implementing JWT Security in Spring Boot
#### To implement JWT security in a Spring Boot application, you typically follow
these steps:
**Add Dependencies:** Include necessary dependencies for Spring Security and
JWT in your project. These can be added in the pom.xml file for Maven projects or
build.gradle for Gradle projects.

**Configure Spring Security:** Configure Spring Security to intercept requests and


ensure only authenticated users can access certain endpoints. This involves setting
up a security configuration class.

**Create JWT Utility Class:** This class will handle JWT creation, validation, and
parsing. It includes methods to generate tokens, extract claims, and validate tokens.

**Create Authentication Filter:** Implement a filter that intercepts incoming requests


and checks for a valid JWT in the Authorization header. This filter will use the JWT
utility class to validate the token and set the authentication context.

**User Authentication and Authorization:** Implement user authentication by


overriding the UserDetailsService to load user-specific data. Use the
AuthenticationManager to authenticate users and generate a JWT for authenticated
users.

### 3. Describe OAuth2 and how it is used in your applications.

OAuth2 (Open Authorization) is an authorization framework that allows applications


to obtain limited access to user accounts on an HTTP service, such as Facebook,
GitHub, or Google. It works by delegating user authentication to the service that
hosts the user account and authorizing third-party applications to access the user
account.

### 4. How do you implement paging to get data in Spring Boot?

You can use Spring Data JPA’s `Pageable` interface to implement paging.

```java
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface UserRepository extends JpaRepository<User, Long> {


Page<User> findAll(Pageable pageable);
}
// Service
public Page<User> getUsers(Pageable pageable) {
return userRepository.findAll(pageable);
}

// Controller
@GetMapping("/users")
public Page<User> listUsers(Pageable pageable) {
return userService.getUsers(pageable);
}
```

### 5. How do you sort data based on a property in Spring Boot?

You can use Spring Data JPA’s `Sort` class to sort data.

```java
import org.springframework.data.domain.Sort;

public List<User> getUsers() {


return userRepository.findAll(Sort.by(Sort.Direction.ASC, "name"));
}
```

### 6. What is an API Gateway, and why is it used?

An API Gateway is a server that acts as an API front-end, receiving API requests,
enforcing throttling and security policies, passing requests to the back-end service,
and then passing the response back to the requester. It is used to manage traffic,
handle cross-cutting concerns like security, and provide a single entry point for client
requests.

### 7. How do you implement load balancing in your applications?

You can implement load balancing using tools like Ribbon or Spring Cloud
LoadBalancer in a Spring Boot application.

```java
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
```
### 8. Explain the difference between Monolithic and Microservices architectures.

- **Monolithic Architecture:** A single unified codebase where all the components


and services are tightly coupled and run as a single service.
- **Microservices Architecture:** An approach where an application is composed of
loosely coupled services, each running in its own process and communicating
through lightweight mechanisms like HTTP or messaging queues.

### 9. What is Kubernetes, and how do you use it in your applications?

Kubernetes is an open-source container orchestration platform that automates the


deployment, scaling, and management of containerized applications. You can use it
to deploy, manage, and scale your microservices.

### 10. How do you connect one microservice to another?

You can use REST APIs, messaging queues (like RabbitMQ), or service discovery
tools (like Eureka) to connect microservices.

### 11. What is the difference between @RestController and @Controller in Spring
Boot?

- **@RestController:** Combines @Controller and @ResponseBody, used to create


RESTful web services.
- **@Controller:** Used to define a controller and is typically used with view
templates to render HTML.

### 12. How do you perform code quality analysis in your projects?

You can use tools like SonarQube for static code analysis, which helps in identifying
code smells, bugs, and security vulnerabilities.

### 13. What is the difference between authentication and authorization?

- **Authentication:** The process of verifying the identity of a user.


- **Authorization:** The process of verifying what resources an authenticated user
has access to.

### 14. How do you scale your application?

You can scale your application horizontally by adding more instances or vertically by
adding more resources (CPU, memory) to the existing instances. Tools like
Kubernetes help in managing scaling.

### 15. What are profiles in Spring Boot, and how do you use them?

Profiles in Spring Boot allow you to configure different environments (e.g.,


development, testing, production). You can specify different configurations in
`application-{profile}.properties` files.
```java
// application-dev.properties
spring.datasource.url=jdbc:h2:mem:devdb

// application-prod.properties
spring.datasource.url=jdbc:mysql://localhost/proddb

// Main application
@SpringBootApplication
@PropertySource("classpath:application-${spring.profiles.active}.properties")
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
```

## React

### 1. What is middleware in ReactJS, and how do you use it?

Middleware in React, typically used with state management libraries like Redux, is a
way to extend the capabilities of the store by adding custom functionality between
dispatching an action and the moment it reaches the reducer.

```javascript
const loggerMiddleware = store => next => action => {
console.log('Dispatching:', action);
let result = next(action);
console.log('Next state:', store.getState());
return result;
};

const store = createStore(


rootReducer,
applyMiddleware(loggerMiddleware)
);
```

### 2. Explain the Context API and Redux. How do they differ, and when do you use
each?

- **Context API:** Built-in feature of React for prop drilling and global state
management. Best for small to medium applications.
- **Redux:** A state management library that provides a single source of truth and a
predictable state container. Best for larger applications with more complex state
management needs.

### 3. How do you write unit tests in React?


You can use testing libraries like Jest and React Testing Library to write unit tests.

```javascript
import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {


render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
```

### 4. Have you worked on reusable components in React? Give an example.

Yes, for example, a Button component that can be reused across the application.

```javascript
const Button = ({ label, onClick }) => (
<button onClick={onClick}>
{label}
</button>
);

// Usage
<Button label="Click Me" onClick={handleClick} />
```

### 5. What is a Higher-Order Component (HoC) in ReactJS, and how do you use
it?

A Higher-Order Component (HoC) is a function that takes a component and returns a


new component. It’s used for reusing component logic.

```javascript
const withLogging = WrappedComponent => {
return class extends React.Component {
componentDidMount() {
console.log('Component mounted');
}

render() {
return <WrappedComponent {...this.props} />;
}
};
};

// Usage
const EnhancedComponent = withLogging(MyComponent);
```
## Assessment
### Spring Boot App - HackerRank Assessment
### 5 Multiple Choice Questions (MCQs)

## First Round Interview

### 1. Explain the concept of OOP (Object-Oriented Programming) in Java.


- **Answer:** OOP in Java is a programming paradigm based on the concept of
objects, which can contain data and code. The four main principles of OOP are
encapsulation, inheritance, polymorphism, and abstraction.

### 2. What are the differences between `==` and `equals()` in Java?
- **Answer:** `==` checks for reference equality, meaning it checks whether two
references point to the same object in memory. `equals()` checks for value equality,
meaning it checks whether two objects are meaningfully equivalent.

### 3. How does Java handle memory management?


- **Answer:** Java uses an automatic garbage collection mechanism to manage
memory. It allocates memory on the heap for new objects and reclaims memory from
objects that are no longer referenced.

### 4. How do you handle exceptions in Java?


- **Answer:** Exceptions in Java are handled using try-catch blocks, where code
that might throw an exception is placed inside the try block and exception handling
code is placed inside the catch block.

### 5. What are checked and unchecked exceptions in Java?


- **Answer:** Checked exceptions are exceptions that must be either caught or
declared in the method signature using the `throws` keyword. Unchecked exceptions
are exceptions that do not need to be explicitly handled, typically subclasses of
`RuntimeException`.

### 6. How do you handle exceptions in Spring Boot applications?


- **Answer:** Spring Boot provides the `@ExceptionHandler` annotation to handle
exceptions in a controller. Additionally, `@ControllerAdvice` can be used to define
global exception handlers for the entire application.

### 7. Given a list of employees, find the list of employees based on gender. Result
should be - Male, [e1, e2, e3] Female, [e4, e5].
- **Answer:**
```java
Map<String, List<Employee>> employeesByGender = employees.stream()
.collect(Collectors.groupingBy(Employee::getGender));
```

### 8. Explain the basics of Spring Boot.


- **Answer:** Spring Boot simplifies the development of Spring applications by
providing a set of tools and libraries for rapid application development. It offers
features like auto-configuration, standalone application configuration, and embedded
servers.

### 9. Write a code example for a JPA repository and a derived query.
- **Answer:**
```java
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
List<Employee> findByGender(String gender);
}
```

### 10. Explain thread pools and their use in Java.


- **Answer:** Thread pools manage a collection of reusable threads for
executing tasks, which improves application performance by reducing the overhead
of creating and destroying threads. Java provides `ExecutorService` to manage
thread pools.

### 11. Configure HikariCP in a Spring Boot application.


- **Answer:**
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/db
username: user
password: pass
hikari:
maximum-pool-size: 10
```

### 12. Explain Hibernate queries and entity graphs.


- **Answer:** Hibernate queries can be written using HQL or Criteria API. Entity
graphs optimize queries by defining which related entities should be fetched,
reducing the number of queries executed and improving performance.

### 13. How do you write test cases differently for controller, data, and service
layers?
- **Answer:**
```java
// Controller Test
@WebMvcTest(EmployeeController.class)
public class EmployeeControllerTest {
@Autowired
private MockMvc mockMvc;

@MockBean
private EmployeeService employeeService;
@Test
public void testGetEmployee() throws Exception {
mockMvc.perform(get("/employees/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}

// Service Test
@ExtendWith(MockitoExtension.class)
public class EmployeeServiceTest {
@Mock
private EmployeeRepository employeeRepository;

@InjectMocks
private EmployeeService employeeService;

@Test
public void testFindEmployeeById() {
when(employeeRepository.findById(1L)).thenReturn(Optional.of(new
Employee("John")));
Employee employee = employeeService.findEmployeeById(1L);
assertEquals("John", employee.getName());
}
}

// Repository Test
@DataJpaTest
public class EmployeeRepositoryTest {
@Autowired
private EmployeeRepository employeeRepository;

@Test
public void testFindByGender() {
List<Employee> employees =
employeeRepository.findByGender("Male");
assertEquals(3, employees.size());
}
}
```

### 14. Explain code coverage and tools like SonarQube.


- **Answer:** Code coverage measures how much of the code is tested by unit
tests. Tools like SonarQube analyze code quality, including code coverage, and
provide reports to help improve code reliability and maintainability.

### 15. What are deployment tools and how do they work?
- **Answer:** - **Answer:** Deployment tools like Jenkins, Docker, and
Kubernetes automate the process of deploying applications, ensuring consistent
environments and simplifying scaling and management.

### 16. Difference between vanilla JavaScript and React.


- **Answer:** Vanilla JavaScript is a plain JavaScript without any libraries or
frameworks. React is a library for building user interfaces, offering components, state
management, and virtual DOM for efficient updates.

### 17. Explain useState and useEffect hooks in React.


- **Answer:** `useState` is a hook that lets you add state to functional
components. `useEffect` is a hook for performing side effects, such as data fetching
or updating the DOM, in functional components.

### 18. Write a basic API call using React.


- **Answer:**
```javascript
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
```

### 19. Transform an IP address from `192.62.255.31` to `291.26.552.13`.


- **Answer:**
```javascript
function transformIP(ip) {
return ip.split('.').map(octet => {
return octet.split('').reverse().join('');
}).join('.');
}
console.log(transformIP('192.62.255.31')); // 291.26.552.13
```
## Second Round Interview: Pair Programming
### 1. Develop a UI page to show a list of items in the search page using React.
- **Answer:**
```javascript
import React, { useState, useEffect } from 'react';

const ItemList = () => {


const [items, setItems] = useState([]);
const [searchTerm, setSearchTerm] = useState('');

useEffect(() => {
fetch('http://localhost:8080/api/items')
.then(response => response.json())
.then(data => setItems(data));
}, []);

const filteredItems = items.filter(item => item.name.includes(searchTerm));


return (
<div>
<input
type="text"
placeholder="Search items"
value={searchTerm}
onChange={e => setSearchTerm(e.target.value)}
/>
<ul>
{filteredItems.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};

export default ItemList;


```

### 2. Write an API with Spring Boot and use the API endpoint in React to show the
list.
- **Spring Boot API:**
```java
@RestController
@RequestMapping("/api/items")
public class ItemController {
@Autowired
private ItemService itemService;

@GetMapping
public List<Item> getAllItems() {
return itemService.getAllItems();
}
}

@Service
public class ItemService {
@Autowired
private ItemRepository itemRepository;

public List<Item> getAllItems() {


return itemRepository.findAll();
}
}

@Repository
public interface ItemRepository extends JpaRepository<Item, Long> {}

@Entity
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

// getters and setters


}
```

- **React Integration:**
```javascript
import React, { useState, useEffect } from 'react';

const ItemList = () => {


const [items, setItems] = useState([]);

useEffect(() => {
fetch('http://localhost:8080/api/items')
.then(response => response.json())
.then(data => setItems(data));
}, []);

return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};

export default ItemList;


```

# HCL L1

1. **Brief about the project:**


- The project is focused on developing a distributed banking application that
handles real-time transactions using microservices architecture. It includes features
like customer registration, account management, and secure transaction processing.
Technologies like Spring Boot, Kafka, Docker, and React are used, ensuring high
scalability and reliability.

2. **Explain Kafka architecture:**


- Kafka architecture consists of Producers, Consumers, Brokers, Topics, and
Zookeeper. Producers send data to Kafka topics, while Consumers read data from
these topics. Kafka Brokers manage the storage and retrieval of messages, and
Zookeeper handles metadata, including leader election and partition management,
ensuring Kafka's fault tolerance and distributed nature.

3. **What is Jenkins and how do you use it?**


- Jenkins is an open-source automation server used for continuous integration
and continuous delivery (CI/CD). It automates the build, test, and deployment
processes, enabling faster and more reliable software delivery. I use Jenkins to
trigger automated builds on code commits, run tests, and deploy applications to
different environments.

4. **What are the features of Java 17?**


- Java 17 includes several new features such as sealed classes, pattern matching
for switch (preview), new macOS rendering pipeline, enhanced pseudo-random
number generators, and the removal of the experimental AOT and JIT compilers. It
also includes long-term support (LTS) for stability in enterprise applications.

5. **What are the features of Java 8?**


- Java 8 introduced several major features, including Lambda expressions, the
Stream API for functional-style operations on collections, the new Date and Time API
(java.time), default methods in interfaces, and the Optional class to handle null
values more gracefully.

6. **Create a single thread in Java using different approaches (code):**


```java
// Using Thread class
Thread thread1 = new Thread() {
public void run() {
System.out.println("Thread using Thread class");
}
};
thread1.start();

// Using Runnable interface


Runnable runnable = () -> System.out.println("Thread using Runnable interface");
Thread thread2 = new Thread(runnable);
thread2.start();

// Using ExecutorService
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> System.out.println("Thread using ExecutorService"));
executor.shutdown();
```

7. **Create a text input and password input in React and display them when a button
is clicked using functional components:**
```javascript
import React, { useState } from 'react';

function App() {
const [text, setText] = useState('');
const [password, setPassword] = useState('');
const [show, setShow] = useState(false);

const handleClick = () => {


setShow(true);
};

return (
<div>
<input
type="text"
placeholder="Enter text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<input
type="password"
placeholder="Enter password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button onClick={handleClick}>Show</button>
{show && (
<div>
<p>Text: {text}</p>
<p>Password: {password}</p>
</div>
)}
</div>
);
}

export default App;


```

8. **Explain your weekly tasks:**


- My weekly tasks typically involve developing new features, fixing bugs, and
optimizing existing code for better performance. I collaborate with team members in
daily stand-up meetings, work on writing unit and integration tests, and participate in
code reviews. Additionally, I contribute to the continuous integration pipeline and
ensure smooth deployments.

9. **What is Agile methodology?**


- Agile methodology is an iterative approach to software development and project
management. It emphasizes collaboration, flexibility, and customer feedback,
allowing teams to deliver small, functional pieces of software incrementally. Agile
promotes adaptive planning, evolutionary development, early delivery, and
continuous improvement.
10. **What is Jira and how do you use it?**
- Jira is a project management tool used for tracking tasks, bugs, and issues. It
supports Agile methodologies like Scrum and Kanban. I use Jira to manage and
prioritize tasks, track progress through sprints, create and assign issues, and
document project workflows. Jira also integrates with CI/CD pipelines for automated
updates.

# HCL L2

1. **Explain your recent project.**


- *Provide details about your recent project, including the technology stack, your
role, the objectives, challenges faced, and how you overcame those challenges.*

2. **What are the new features in Java 8?**


- *Java 8 introduced several new features, including:*
- *Lambda expressions*
- *Functional interfaces*
- *Stream API*
- *New Date and Time API (java.time)*
- *Default methods in interfaces*
- *Method references*
- *Optional class*

3. **What is a static method in Java?**


- *A static method belongs to the class rather than instances of the class. It can
be called without creating an instance of the class.*

4. **How can we use static methods in an interface?**


- *Static methods in interfaces can be used to provide utility methods that are
related to the interface but do not need an instance. They are called using the
interface name.*

5. **How can we call a static method?**


- *Static methods can be called using the class name or the interface name if
defined in an interface, e.g., `ClassName.staticMethod()` or
`InterfaceName.staticMethod()`.*

6. **How many ways can we call static methods?**


- *Static methods can be called in two ways:*
- *Using the class name (e.g., `Math.sqrt(4)` for `Math.sqrt`)*
- *Directly if in the same class (e.g., `staticMethod()`)*

7. **What is a default method in Java?**


- *Default methods are methods in interfaces that have a body. They provide a
default implementation that can be used by implementing classes.*

8. **What is the use of default methods in interfaces?**


- *Default methods allow interfaces to evolve without breaking existing
implementations. They enable the addition of new methods with default behavior.*
9. **What is a method reference in Java?**
- *Method references are a shorthand notation for calling a method. They provide
a way to refer to methods without invoking them.*

10. **How many ways can we create method references?**


- *Method references can be created in the following ways:*
- *Reference to a static method*
- *Reference to an instance method of a specific object*
- *Reference to an instance method of an arbitrary object*
- *Reference to a constructor*

11. **Provide a customized example of a method reference with full code and
explanation.**

```java
import java.util.Arrays;
import java.util.List;

public class MethodReferenceExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

// Using method reference to call static method


names.forEach(MethodReferenceExample::printName);

// Using method reference to call instance method


MethodReferenceExample instance = new MethodReferenceExample();
names.forEach(instance::printNameInstance);
}

// Static method
public static void printName(String name) {
System.out.println(name);
}

// Instance method
public void printNameInstance(String name) {
System.out.println(name);
}
}
```

12. **What is a stream in Java?**


- *A stream in Java is a sequence of elements supporting sequential and parallel
aggregate operations. It is used for processing collections of objects in a functional
style.*

13. **What is a parallel stream?**


- *A parallel stream is a type of stream that enables parallel processing of data
by splitting the data into multiple chunks and processing them concurrently.*

14. **What is the difference between a stream and a parallel stream?**


- *A stream processes data sequentially, while a parallel stream divides the data
into multiple chunks and processes them concurrently using multiple threads.*

15. **How does the internal process work in parallel streams?**


- *Parallel streams use the ForkJoinPool to split the data into smaller chunks,
process them concurrently in multiple threads, and then merge the results.*

16. **How many ways can we create a thread in Java?**


- *Threads can be created in two main ways:*
- *By implementing the `Runnable` interface*
- *By extending the `Thread` class*

17. **Provide example code for implementing the `Runnable` interface and explain
how to use it.**

```java
public class RunnableExample implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}

public static void main(String[] args) {


RunnableExample runnable = new RunnableExample();
Thread thread = new Thread(runnable);
thread.start();
}
}
```

18. **If `MyThread` implements `Runnable`, and I create a thread like this: `Thread t
= new Thread(new MyThread())`, how is this different from extending the `Thread`
class?**
- *Implementing `Runnable` allows you to use composition and separate the
thread's job from its execution. Extending `Thread` tightly couples the thread's job
with its execution, limiting flexibility.*

19. **What is `ExecutorService` in threads?**


- *`ExecutorService` is a high-level replacement for managing and controlling
thread execution. It provides methods for managing a pool of threads and scheduling
tasks.*

20. **How many ways can we create an `ExecutorService`?**


- *`ExecutorService` can be created using:*
- *`Executors.newFixedThreadPool(int nThreads)`*
- *`Executors.newSingleThreadExecutor()`*
- *`Executors.newCachedThreadPool()`*
- *`Executors.newScheduledThreadPool(int corePoolSize)`*

21. **What is autowiring in Spring?**


- *Autowiring is a feature in Spring that allows the framework to automatically
inject dependencies into a bean.*

22. **How many modes of autowiring are there?**


- *Autowiring modes include:*
- *`@Autowired` (by type)*
- *`@Qualifier` (by name)*
- *`@Resource` (by name)*
- *`@Inject` (by type)*

24. **Explain `@Qualifier` and `@Inject`.**


- *`@Qualifier` is used to provide specific beans when multiple candidates are
available. `@Inject` is a Java standard annotation used to inject dependencies.*

25. **What is the difference between `@Autowired` and `@Qualifier`?**


- *`@Autowired` is used for automatic injection by type, while `@Qualifier` is
used in conjunction with `@Autowired` to specify which bean to inject when multiple
beans are available.*

26. **Can we use `@Autowired` in place of `@Qualifier`?**


- *`@Autowired` alone cannot specify which bean to inject if there are multiple
candidates. `@Qualifier` is needed to resolve such ambiguities.*

27. **What are the limitations of autowiring?**


- *Limitations include:*
- *Ambiguity when multiple beans of the same type are available.*
- *Difficulty in identifying dependencies at runtime.*
- *Inability to inject beans based on dynamic conditions.*

28. **What is Spring Security?**


- *Spring Security is a framework that provides comprehensive security services
for Java applications, including authentication, authorization, and protection against
various security threats.*

29. **How do you configure Spring Security?**


- *Spring Security can be configured using:*
- *Java configuration with `@EnableWebSecurity` and `SecurityConfig`
classes.*
- *XML configuration (less common in recent versions).*

30. **What is JWT token-based authentication?**


- *JWT (JSON Web Token) token-based authentication is a method where
authentication information is transmitted as a JSON object and is used to verify the
identity of users.*

31. **How many ways can you configure custom security?**


- *Custom security can be configured using:*
- *Java-based configuration with `SecurityConfigurerAdapter`*
- *Custom filters and handlers*
- *Spring Security extensions*

32. **What is an API gateway?**


- *An API gateway is a server that acts as an API front-end, receiving API
requests, enforcing throttling, routing requests, and aggregating results.*

33. **How to implement an API gateway? Which dependency is needed?**


- *To implement an API gateway, you can use tools like Spring Cloud Gateway or
Netflix Zuul. Dependencies needed include:*
- *`spring-cloud-starter-gateway` for Spring Cloud Gateway*
- *`zuul` for Netflix Zuul*

34. **What is load balancing?**


- *Load balancing distributes incoming network traffic across multiple servers to
ensure no single server becomes overwhelmed, enhancing reliability and
performance.*

35. **How do you implement load balancing in microservices?**


- *Load balancing in microservices can be implemented using:*
- *Client-side load balancing with libraries like Ribbon*
- *Server-side load balancing with tools like Nginx or HAProxy*

36. **What is fault tolerance?**


- *Fault tolerance refers to the ability of a system to continue operating properly
in the event of a failure of some of its components.*

37. **How do you handle fault tolerance?**


- *Fault tolerance can be handled using:*
- *Redundancy and failover strategies*
- *Circuit breakers (e.g., using Resilience4j)*
- *Retry mechanisms and fallback methods*

38. **What is a circuit breaker

?**
- *A circuit breaker is a design pattern that prevents a system from making calls
to a failing service, allowing it to recover and preventing cascading failures.*

39. **How do you implement a circuit breaker?**


- *A circuit breaker can be implemented using libraries like:*
- *Resilience4j*
- *Hystrix*

40. **What is the design pattern for a circuit breaker?**


- *The circuit breaker pattern consists of three states:*
- *Closed (normal operation)*
- *Open (service is failing)*
- *Half-Open (test if the service has recovered)*

41. **How do you handle limits in a circuit breaker?**


- *Limits in a circuit breaker can be handled by:*
- *Setting thresholds for failure rates*
- *Defining timeout durations for service calls*
- *Configuring retry and fallback mechanisms*

42. **What are the features of RESTful web services?**


- *Features include:*
- *Stateless communication*
- *Resource-based URLs*
- *Standard HTTP methods (GET, POST, PUT, DELETE)*
- *JSON or XML responses*
- *HTTP status codes for responses*

43. **What are the available HTTP status codes, and why are they important?**
- *Common HTTP status codes include:*
- *200 OK*
- *201 Created*
- *204 No Content*
- *400 Bad Request*
- *401 Unauthorized*
- *404 Not Found*
- *500 Internal Server Error*
- *They are important for indicating the result of an HTTP request and guiding
client-side behavior.*

44. **Which database are you using?**


- *Provide the name of the database you are using (e.g., MySQL, PostgreSQL,
MongoDB) and any relevant details about its configuration and usage.*

45. **Write a query to get the username when the name starts with 'A' and ends with
'E'.**

```sql
SELECT username
FROM users
WHERE name LIKE 'A%E';
```

46. **Write an SQL query to find the 2nd maximum salary.**

```sql
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
```

47. **Write an SQL query to find the 10th maximum salary.**


```sql
SELECT salary
FROM (
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 10
) AS temp
ORDER BY salary ASC
LIMIT 1;
```

48. **What is the difference between the `WHERE` and `HAVING` clauses?**
- *The `WHERE` clause filters rows before any groupings are made, while the
`HAVING` clause filters groups after the `GROUP BY` operation.*

49. **Give an example of using the `HAVING` clause.**

```sql
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
```

50. **Can you use grouping in the `WHERE` clause?**


- *No, grouping and aggregation functions must be used with the `HAVING`
clause, not the `WHERE` clause.*

51. **Write a Java code snippet to find names starting with 'A' using streams.**

```java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Andrew", "Amanda",
"George");

List<String> result = names.stream()


.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());

System.out.println(result); // Output: [Alice, Andrew, Amanda]


}
}
```
52. **Given the number 6178, how many iterations are required to reach 1629 and
99? Write the code logic to solve this.**

```java
import java.util.Arrays;

public class KaprekarRoutine {


public static void main(String[] args) {
int number = 6178;
int iterations = 0;

while (number != 6174 && number != 99) {


number = performKaprekarIteration(number);
System.out.println("Current number: " + number);
iterations++;
}

System.out.println("Total iterations: " + iterations);


}

private static int performKaprekarIteration(int number) {


String numStr = String.format("%04d", number); // Pad with zeros if
necessary
char[] numChars = numStr.toCharArray();

Arrays.sort(numChars); // Ascending order


int smallNum = Integer.parseInt(new String(numChars));

// Reverse the order for descending


String largeStr = new StringBuilder(new
String(numChars)).reverse().toString();
int largeNum = Integer.parseInt(largeStr);

return largeNum - smallNum;


}
}
```

# HR
1. **self-salary etc..**

1. **What are the main features introduced in Java 8?**


- Lambda Expressions
- Functional Interfaces
- Streams API
- Default Methods in Interfaces
- Optional Class
- New Date and Time API (java.time)
- Nashorn JavaScript Engine
- Method References

2. **What are the key differences between an interface and an abstract class in
Java?**
- Interfaces can only have abstract methods (until Java 8, which introduced
default and static methods), while abstract classes can have both abstract and
concrete methods.
- A class can implement multiple interfaces but can inherit from only one abstract
class.
- Interfaces cannot have instance variables, while abstract classes can.
- Interfaces provide a form of multiple inheritance; abstract classes provide a form
of single inheritance.

3. **How do you implement Executor Services in Java?**


```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceExample {


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

for (int i = 0; i < 10; i++) {


Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}

class WorkerThread implements Runnable {


private String command;

public WorkerThread(String s) {
this.command = s;
}

@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Start.
Command = " + command);
processCommand();
System.out.println(Thread.currentThread().getName() + " End.");
}

private void processCommand() {


try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```

4. **Which databases have you used in your projects, and what was your experience
with them?**
- **MySQL:** Used for web applications; strong support for transactions and data
integrity.
- **PostgreSQL:** Preferred for complex queries and large datasets; excellent
support for JSON data types and extensions.
- **MongoDB:** Utilized for handling unstructured data and fast prototyping; great
for horizontal scaling.
- **Oracle:** Employed in enterprise-level applications requiring robust security
and advanced features.

5. **How can you declare and use functional programming constructs in Java?**
```java
// Lambda Expression
List<String> names = Arrays.asList("John", "Jane", "Jack");
names.forEach(name -> System.out.println(name));

// Functional Interface Example


@FunctionalInterface
interface MathOperation {
int operation(int a, int b);
}

MathOperation addition = (a, b) -> a + b;


System.out.println("10 + 5 = " + addition.operation(10, 5));
```

6. **What are the differences between `@RestController` and `@Controller` in


Spring Boot?**
- `@RestController` is a combination of `@Controller` and `@ResponseBody`. It
automatically serializes return objects into JSON or XML and writes them into the
HTTP response.
- `@Controller` is used to mark classes as Spring MVC controllers. Methods in
these classes typically return view names and are resolved by view resolvers.

7. **How do you schedule tasks in Spring Boot?**


```java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("The time is now " + new Date());
}
}
```

8. **How is Jenkins integrated with Spring Boot? What dependencies or


configuration files are needed?**
- **Jenkinsfile:**
```groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
sh './mvnw clean package'
}
}
stage('Test') {
steps {
sh './mvnw test'
}
}
stage('Deploy') {
steps {
sh 'docker build -t spring-boot-app .'
sh 'docker run -d -p 8080:8080 spring-boot-app'
}
}
}
}
```
- **Dependencies:**
- Jenkins server
- Maven or Gradle for build automation
- Docker for containerization (if deploying with Docker)

9. **What is the difference between `HashMap` and `ConcurrentHashMap` in Java?


**
- `HashMap` is not synchronized and is not thread-safe.
- `ConcurrentHashMap` is thread-safe and allows concurrent access to its
segments.

10. **What are the key classes and interfaces in the `java.util.concurrent` package?
**
- **Key Classes:** `ExecutorService`, `ScheduledExecutorService`, `Future`,
`CountDownLatch`, `CyclicBarrier`, `Semaphore`, `ConcurrentHashMap`,
`CopyOnWriteArrayList`
- **Key Interfaces:** `Executor`, `Callable`, `Future`, `BlockingQueue`

11. **Describe the collections framework in Java.**


- **Core Interfaces:** `Collection`, `List`, `Set`, `Queue`, `Map`
- **Implementations:** `ArrayList`, `LinkedList`, `HashSet`, `TreeSet`,
`PriorityQueue`, `HashMap`, `TreeMap`
- **Utilities:** `Collections`, `Arrays`

12. **How do you use profiles in Spring Boot?**


```yaml
# application.yml
spring:
profiles:
active: dev
---
# application-dev.yml
server:
port: 8081
---
# application-prod.yml
server:
port: 8082
```

13. **If both `application.properties` and `application.yaml` are present in a Spring


Boot application, which one takes precedence?**
- `application.properties` takes precedence over `application.yaml`.

14. **Explain the `@Autowired` annotation in Spring.**


- `@Autowired` is used for automatic dependency injection. Spring's dependency
injection mechanism uses this annotation to resolve and inject collaborating beans
into the desired bean.

15. **Using a lambda expression, write a Java program to sum the elements of an
array.**
```java
import java.util.Arrays;
public class SumArray {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};

// Using a lambda expression with Stream API


int sum = Arrays.stream(array)
.reduce(0, (a, b) -> a + b);

System.out.println("Sum: " + sum);


}
}
```

16. **Write a Java program to generate all permutations of an array using lambda
expressions.**
```java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Permutations {


public static void main(String[] args) {
int[] array = {1, 2, 3};
List<List<Integer>> result = permute(array);
result.forEach(System.out::println);
}

public static List<List<Integer>> permute(int[] nums) {


return permute(IntStream.range(0,
nums.length).boxed().collect(Collectors.toList()), nums);
}

private static List<List<Integer>> permute(List<Integer> indices, int[] nums) {


if (indices.isEmpty()) {
List<Integer> perm = new ArrayList<>();
for (int num : nums) {
perm.add(num);
}
return List.of(perm);
}

return indices.stream()
.flatMap(i -> {
List<Integer> remaining = new ArrayList<>(indices);
remaining.remove(Integer.valueOf(i));
return permute(remaining, swap(nums, i)).stream();
})
.collect(Collectors.toList());
}

private static int[] swap(int[] array, int i) {


int[] newArray = array.clone();
int temp = newArray[i];
newArray[i] = newArray[0];
newArray[0] = temp;
return newArray;
}
}
```
**Etc...**

### 1. **Explain your project briefly.**


My project involves [describe your project here], utilizing technologies such as Spring
Boot, React, microservices, and databases. The core functionality includes [key
features], and I was responsible for [your role].

---

### 2. **Given an array of integers and a number ‘sum’, print all pairs in the array
whose sum equals ‘sum’.**
```java
public class PairSum {
public static void main(String[] args) {
int[] arr = {1, 5, 7, -1, 5};
int exp = 6;
Map<Integer,Integer> map=new LinkedHashMap<>();
for(int i=0;i<arr.length;i++) {
int e=arr[i];
int dif=exp-e;
if(map.containsKey(dif)) {
for(int j=1;j<=map.get(dif);j++)
System.out.println("("+dif+","+e+")");
}
map.put(e,map.getOrDefault(e,0)+1);
}
}
```

---

### 3. **Design a table structure for books and members**


- **Books Table:**
- BookID (Primary Key)
- Title
- AuthorID (Foreign Key)

- **Authors Table:**
- AuthorID (Primary Key)
- Name

- **Members Table:**
- MemberID (Primary Key)
- Name

- **Borrowing Table:**
- BorrowID (Primary Key)
- MemberID (Foreign Key)
- BookID (Foreign Key)
- BorrowDate
- DueDate
- ReturnDate

---

### 4. **What happens if an exception is thrown in a method? Explain with a code


example.**
When an exception is thrown in a method, it disrupts the normal flow of the program.
If the exception is not caught, the method terminates and the exception is
propagated to the calling method.
```java
public class ExceptionExample {
public static void main(String[] args) {
try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e);
}
}

public static int divide(int a, int b) throws ArithmeticException {


return a / b; // This will throw ArithmeticException if b is 0
}
}
```

---

### 5. **What is dependency injection?**


Dependency injection is a design pattern used in Spring to manage object
dependencies by injecting them at runtime rather than defining them manually in
code. It promotes loose coupling and testability.

---

### 6. **Give an example of dependency injection in Spring Boot.**


```java
@Service
public class EmployeeService {
public String getEmployee() {
return "Employee Details";
}
}

@RestController
public class EmployeeController {
private final EmployeeService employeeService;

@Autowired
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}

@GetMapping("/employee")
public String getEmployee() {
return employeeService.getEmployee();
}
}
```

---

### 7. **How do you pass dependency from the controller to the service in Spring
Boot?**
You pass the service class dependency to the controller class by using the
`@Autowired` annotation in Spring Boot. This allows Spring to inject the service
object at runtime.

---

### 8. **List some common Spring Boot annotations.**


- `@SpringBootApplication`: Entry point for Spring Boot applications.
- `@Autowired`: Inject dependencies automatically.
- `@RestController`: Combines `@Controller` and `@ResponseBody`.
- `@Service`: Marks a class as a service provider.
- `@Repository`: Marks a class as a DAO.
- `@GetMapping`, `@PostMapping`: Used for handling HTTP GET/POST requests.

---

### 9. **How do you store unique employee names in a `Map` in Java?**


```java
Map<String, Employee> employeeMap = new HashMap<>();
employeeMap.put("John", new Employee("John"));
employeeMap.put("Alice", new Employee("Alice"));
// Ensure employee names are unique when inserting into the map.
```

---

### 10. **How do you sort a list of employees based on employee names?**
```java
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("John"));
employees.add(new Employee("Alice"));
employees.sort(Comparator.comparing(Employee::getName));
```

---

### 11. **How do you retrieve database data based on a particular page in Spring
Boot?**
You can use `Pageable` from Spring Data JPA to retrieve data based on pagination:
```java
Pageable pageable = PageRequest.of(pageNumber, pageSize);
Page<Employee> employees = employeeRepository.findAll(pageable);
```

---

### 12. **How do you write a query to get data for a specific page in a database?**
```sql
SELECT * FROM employees LIMIT 10 OFFSET 20;
```
This will fetch 10 records starting from the 21st record (for pagination).

---

### 13. **How do you deploy your project?**


- Build the project using `mvn clean install`.
- Deploy the generated `.jar` or `.war` file to a server (Tomcat, cloud platform like
AWS, or Kubernetes).
- Use CI/CD pipelines for continuous deployment.

---

### 14. **How do you develop code using a Git repository?**


1. Clone the repository using `git clone`.
2. Create a new branch using `git checkout -b new-branch`.
3. Make changes and commit them using `git commit`.
4. Push the branch using `git push`.
5. Create a pull request to merge the changes.

---

### 15. **How do you handle the `application.properties` file in Spring Boot?**
The `application.properties` file is used for configuring your Spring Boot application,
such as database configurations, server ports, and other environment-specific
properties. You can access these properties using `@Value` or
`@ConfigurationProperties` annotations.

---

### 16. **Which cloud are you using for deployment?**


I am using [AWS/Azure/GCP] for deployment, utilizing services like Elastic
Beanstalk, EC2, or Kubernetes for application hosting.

---

### 17. **How do you communicate between two microservices?**


Microservices can communicate using:
- **REST APIs** (via HTTP requests).
- **Message brokers** like RabbitMQ, Kafka for asynchronous communication.
- **Feign clients** in Spring Boot for simplified HTTP client calls between services.

#Technical Round
## Self-Introduction and Project Explanation

1. **Self-introduction with a brief explanation about your project.**


- *"Hello, I’m [Your Name]. I have been working in software development for [X]
years, specializing in Java and React. Currently, I am involved in a project that
focuses on developing a [brief description of the project]."*

2. **Have you developed any project for your referencing purpose?**


- *"Yes, I have worked on several projects for reference, including [briefly mention
training projects or key projects you’ve worked on]. These projects helped me
enhance my skills in [mention technologies or areas]."*

3. **Explain about your developed project. (Follow-up questions based on the


project)**
- *"My recent project involved [describe the scope of your project]. It was
designed to [mention key objectives or features]. We utilized technologies such as
[mention technologies] to achieve [mention goals or results]."*

4. **How do you monitor your project?**


- *"I use various tools like New Relic and Grafana for monitoring application
performance and logs. Additionally, I rely on automated tests and CI/CD pipelines to
ensure the project’s stability."*

5. **Which database did you use?**


- *"I used SQL for managing relational data due to its robust features and
performance advantages."*

## Java
1. **What is a class loader?**
- *A class loader is a part of the Java Runtime Environment (JRE) that loads Java
classes into memory. It dynamically loads, links, and initializes classes as needed.*

2. **What is the Object class?**


- *The Object class is the root class of the Java class hierarchy. Every class in
Java inherits from Object, and it provides basic methods like `toString()`, `equals()`,
and `hashCode()`.*
3. **What are the equals and hashCode methods in the Object class?**
- *`equals()` is used to compare two objects for equality, while `hashCode()`
returns a unique integer for each object. These methods are used in collections like
HashMap.*

4. **Explain encapsulation.**
- *Encapsulation is the concept of wrapping data (variables) and methods
(functions) into a single unit or class. It restricts direct access to some of the object's
components, which can help prevent accidental interference and misuse.*

5. **Give a real-time example of encapsulation.**


- *A real-time example is a bank account class. The account details (balance,
account number) are private, and access is provided through public methods
(deposit, withdraw) to ensure controlled and secure manipulation of the data.*

6. **Compare static block vs static method.**


- *A static block is used for initializing static variables or performing some
initialization when the class is first loaded. A static method, on the other hand, can be
called without creating an instance of the class and can only access static
members.*

7. **Does a static block execute first or does a constructor execute first?**


- *A static block executes before a constructor. It runs when the class is first
loaded, whereas the constructor is executed when an instance of the class is
created.*

8. **If I remove static from the main method, will it work?**


- *No, the `main` method must be static because it is the entry point for the JVM
to start the application. Without `static`, the JVM cannot call the method.*

9. **Write a code to move array elements with 0s to the last and explain.
arr={1,0,1,1,0,0,1} output={1,1,1,1,0,0,0}**
```java
public class MoveZeros {
public static void moveZeros(int[] arr) {
int count = 0; // Count of non-zero elements
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
arr[count++] = arr[i]; // Move non-zero elements to the front
}
}
while (count < arr.length) {
arr[count++] = 0; // Fill remaining positions with zeros
}
}
}
```
- *This code iterates through the array, moving all non-zero elements to the front.
After that, it fills the remaining positions with zeros.*
10. **Class Inheritance Issue:**
```java
class A {
public void sum() {}
}
class B extends A {
public void sum() {}
}
// class C extends A, B {} // Compilation error
```
- *Java does not support multiple inheritance directly. You need to refactor the
code, perhaps using interfaces or abstract classes.*

11. **Interface Implementation Issue:**


```java
interface A {
void sum();
}
interface B{
void sum();
}
class C implements A, B {
// which sum method i want to implemet
}
```
- *In Java, when a class implements multiple interfaces that declare methods with
the same name and signature, you only need to provide one implementation for that
method in the class. This single implementation will be used for both interfaces.*
```java
class C implements A, B {
@Override
public void sum() {
// Single implementation of the sum method
System.out.println("Sum method implemented in class C");
}
}
```
12. **What is a functional interface?**
- *A functional interface is an interface with a single abstract method. They are
used as the target type for lambda expressions and method references. Examples
include `Runnable` and `Callable`.*

13. **Write code to find the second largest number in the array `[1, 2, 3, 4, 5, 2, 4]`
using Java 8.**
```java
import java.util.Arrays;
import java.util.Comparator;

public class SecondLargestNumber {


public static void main(String[] args) {
int[] a = {3, 6, 32, 1, 8, 5, 31, 22};

int secondLargest = Arrays.stream(a)


.boxed()
.sorted(Comparator.reverseOrder())
.distinct()
.skip(1)
.findFirst()
.orElseThrow(() -> new
IllegalArgumentException("Array must contain at least two distinct elements"));

System.out.println("Second Largest Number: " + secondLargest);


}
}

```
- *This code first removes duplicates, sorts the array, and then retrieves the
second last element.*

14. **What is a HashMap?**


- *HashMap is a collection that stores key-value pairs. It allows for efficient
retrieval of values based on their keys.*

15. **Can a HashMap key be null?**


- *Yes, HashMap allows one null key and multiple null values.*

16. **Explain the internal working process of a HashMap.**


- *HashMap uses an array of buckets to store key-value pairs. The hash code of
the key determines the bucket in which the entry is stored. Collisions are handled by
linking entries in the same bucket.*

17. **What is the new change in Java 8 hashCode?**


- *Java 8 introduced improvements to the `hashCode` method, particularly in
hash-based collections. For example, `HashMap` uses a balanced tree structure for
high collision scenarios.*

18. **What is the default size of a HashMap?**


- *The default initial capacity of a HashMap is 16 buckets.*

19. **Explain fail-safe and fail-fast iterators.**


- *Fail-fast iterators immediately throw `ConcurrentModificationException` if the
collection is modified during iteration. Fail-safe iterators, like those in
`CopyOnWriteArrayList`, work on a copy of the collection and do not throw
exceptions if the collection is modified.*

-*[Reference code]*
*Code Example for Fail-Fast Iterators:*
```java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FailFastExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");

Iterator<String> iterator = list.iterator();

// Modify the collection while iterating


while (iterator.hasNext()) {
String item = iterator.next();
System.out.println(item);
list.add("D"); // This will cause ConcurrentModificationException
}
}
}
```
*Code Example for Fail-Safe Iterators:*

```java
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class FailSafeExample {


public static void main(String[] args) {
List<String> list = new CopyOnWriteArrayList<>();
list.add("A");
list.add("B");
list.add("C");

for (String item : list) {


System.out.println(item);
list.add("D"); // This will not cause ConcurrentModificationException
}

// Print the list after modification


System.out.println("List after modification: " + list);
}
}
```

### Hibernate
1. **What is Hibernate?**
- *Hibernate is an ORM (Object-Relational Mapping) framework that simplifies
database interactions by mapping Java objects to database tables.*
2. **Does JPA implement Hibernate? (True or False and why)**
- *False. JPA (Java Persistence API) is a specification for ORM in Java. Hibernate
is an implementation of JPA.*

3. **If JDBC is there, why do we need Hibernate?**


- *Hibernate provides a higher level of abstraction compared to JDBC. It handles
complex database operations, caching, and object mapping more efficiently than raw
JDBC.*

4. **Do you know SQL and NoSQL databases?**


- *Yes, I am familiar with both SQL databases (e.g., PostgreSQL, MySQL) and
NoSQL databases (e.g., MongoDB, Cassandra).*

### SQL
1. **What is the difference between HAVING and WHERE clause?**
- *`WHERE` is used to filter rows before aggregation, while `HAVING` is used to
filter groups after aggregation.*

2. **Can I use WHERE to filter a group of records?**


- *No, `WHERE` filters rows, not groups. Use `HAVING` to filter groups.*

3. **What is an index in SQL?**


- *An index is a database object that improves the speed of data retrieval
operations on a table. It creates a separate data structure that allows for faster
searches.*

### Spring Boot


1. **What is the difference between PUT and PATCH?**
- *`PUT` is used to update an entire resource, while `PATCH` is used to update
partial data of a resource.*

2. **Can we use PUT in place of POST? Will it work or not?**


- *Yes, `PUT` can be used in place of `POST`, but they have different semantics.
`PUT` is idempotent, meaning multiple identical requests have the same effect as a
single request, while `POST` may result in different outcomes.*

3. **What is the difference between @RestController and @Controller?**


- *`@RestController` is a specialized version of `@Controller` that combines
`@Controller` and `@ResponseBody`, meaning it returns JSON/XML responses
directly. `@Controller` is used for rendering views (like JSPs).*

4. **Why is REST API stateless?**


- *REST APIs are stateless to ensure scalability and reliability. Each request from
the client to the server must contain all the information needed to understand and
process the request.*

### Additional Questions

1. **How do you know .NET?**


- *[_____]*
2. **Can you give an example of where you have used all your technical skills?**
- *[_____]*

# Manager Round

1. **Can you provide a brief explanation of your project?**


- *[your self].*

2. **What specific work did you do with ReactJS in your project?**


- *I worked on creating reusable components, implementing form validation with
Formik, and managing state using React’s Context API. I also optimized the
application's performance by using React hooks like `useMemo` and `useCallback`,
and implemented lazy loading for certain components to enhance loading times.*

3. **On a scale of 1 to 10, how would you rate yourself in Java, Spring Boot, and
microservices?**
- *I would rate myself as follows: Java - 8, Spring Boot - 8, Microservices - 7.5. I
have extensive experience in Java and Spring Boot, and I am comfortable
developing and managing microservices architectures, though I continue to seek
opportunities to deepen my expertise in microservices.*

4. **How did you learn .NET?**


- *I learned .NET Core by working on a personal project and by following tutorials
and courses available online. I also created content about .NET on my YouTube
channel, which helped reinforce my learning by teaching the concepts to others. This
approach allowed me to deepen my understanding and gain practical experience.*

5. **Which databases have you used in your projects?**


- *I have used MySQL and H2 databases in my projects. MySQL was utilized for
managing relational data due to its robustness and scalability, while H2 was used for
in-memory data storage and testing purposes, which helped in speeding up the
development and testing processes*

6. **What issues did you face in your first and second projects, and how did you
overcome them?**
- *In my first project, a bank application, I faced issues with data integrity, security,
and performance. I resolved these by implementing strong transaction management,
using Spring Security for authentication, and optimizing database queries. In my
second project, I did not encounter significant issues.*

7. **How have you improved the performance of your code?**


- *I have improved code performance by profiling and identifying bottlenecks,
optimizing algorithms and data structures, and implementing caching strategies.
Additionally, I have refactored code for better readability and maintainability, which
also contributes to improved performance and reduced complexity.*
# KVAS Technologies

# Technical Interview
---

### 1. **Introduce yourself with a focus on your recent projects and the technologies
you've worked with.**

**Answer:**
I am BSK, a Java full stack developer with 3 years of experience in building scalable
web applications. My recent project involved developing a abc application where I
focused on the user registration page and transaction data handling. I used ReactJS
for the frontend, Spring Boot for the backend, and implemented microservices
architecture. My tech stack includes Java, Spring Boot, Hibernate, ReactJS, and
MySQL.

### 2. **Describe a recent task or project you worked on. What challenges did you
face and how did you overcome them?**

**Answer:**
In my recent project, I worked on a feature to implement real-time transaction
monitoring. The challenge was ensuring the system could handle high-frequency
transactions without performance degradation. I optimized the database queries,
used Redis for caching frequently accessed data, and applied asynchronous
processing for non-critical tasks. This improved the system's performance
significantly.

### 3. **Why are you looking for a new job? What motivates your job search?**

**Answer:**
I am seeking new opportunities to expand my skill set and work on more challenging
projects. I am particularly interested in roles that offer the chance to work with
cutting-edge technologies and innovative solutions, which will help me grow both
professionally and personally.

### 4. **Write a code example for Bubble Sort in Java.**

**Answer:**

```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {3, 5, 1, 0, 4, 6};
bubbleSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}

public static void bubbleSort(int[] arr) {


int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```

### 5. **What is the difference between PUT, PATCH, and POST in RESTful
services?**

**Answer:**
- **PUT:** Used to update an existing resource or create a resource if it does not
exist. It is idempotent, meaning multiple identical requests should yield the same
result.
- **PATCH:** Used to apply partial updates to a resource. It is not necessarily
idempotent.
- **POST:** Used to create a new resource. It is not idempotent, and repeated
requests may create multiple resources.

### 6. **If an API takes a long time to respond, how do you handle it in your
application?**

**Answer:**
To handle long API response times, I would implement asynchronous processing
using the `@Async` annotation in Spring Boot or use techniques like caching,
timeout settings, or a circuit breaker pattern to manage delayed responses and
prevent performance bottlenecks.

### 7. **What is the @Async annotation in Spring Boot, and how does it work?**

**Answer:**
The `@Async` annotation in Spring Boot is used to run methods asynchronously in a
separate thread. This allows the main thread to continue processing without waiting
for the annotated method to complete, improving the application's performance.

### 8. **How do you write a native query in JPA with Spring Boot?**

**Answer:**
A native query in JPA can be written using the `@Query` annotation with the
`nativeQuery` attribute set to `true`. For example:

```java
@Query(value = "SELECT * FROM users WHERE email = ?1", nativeQuery = true)
User findByEmail(String email);
```

### 9. **Explain what Dependency Injection is in Spring Boot.**

**Answer:**
Dependency Injection (DI) in Spring Boot is a design pattern where the framework
injects dependencies (objects) into a class rather than the class creating them. This
promotes loose coupling and enhances testability and modularity.

### 10. **Provide an example where Dependency Injection is used in a Spring Boot
application.**

**Answer:**
In a Spring Boot application, a service class can be injected into a controller using
`@Autowired`:

```java
@Service
public class UserService {
// Business logic
}

@RestController
public class UserController {
@Autowired
private UserService userService;

// Controller methods using userService


}
```

### 11. **In which scenarios would you use the @Autowired annotation in Spring
Boot?**

**Answer:**
The `@Autowired` annotation is used in Spring Boot to inject dependencies, such as
service or repository beans, into a class. It can be used in constructors, setters, or
directly on fields.

### 12. **What are the different bean scopes available in Spring Boot?**

**Answer:**
The different bean scopes in Spring Boot are:
- **Singleton:** One instance per Spring container.
- **Prototype:** A new instance every time the bean is requested.
- **Request:** One instance per HTTP request.
- **Session:** One instance per HTTP session.
- **Application:** One instance per ServletContext.
### 13. **How does the request-response cycle work in a Spring Boot application?**

**Answer:**
In a Spring Boot application, a client sends an HTTP request, which is received by
the DispatcherServlet. The request is then routed to the appropriate controller
method, which processes the request and returns a response. The response is sent
back to the client via the DispatcherServlet.

### 14. **How does the prototype scope work in Spring Boot?**

**Answer:**
In the prototype scope, a new instance of the bean is created each time it is
requested from the Spring container. This is useful when you need multiple instances
of a bean with different states.

### 15. **How does the singleton scope work in Spring Boot?**

**Answer:**
In the singleton scope, a single instance of the bean is created and shared across
the entire Spring container. This is the default scope in Spring Boot and is used
when you want a single shared instance.

### 16. **What are the @Primary and @Qualifier annotations in Spring Boot, and
when would you use them?**

**Answer:**
- **@Primary:** Used to indicate the preferred bean when multiple beans of the
same type exist.
- **@Qualifier:** Used to specify which bean should be injected when multiple beans
of the same type exist and `@Primary` is not sufficient.

### 17. **Explain the different types of relationships in JPA (e.g., One-to-One, One-
to-Many, Many-to-One, Many-to-Many).**

**Answer:**
- **One-to-One:** Each entity instance is associated with one instance of another
entity.
- **One-to-Many:** An entity instance is associated with multiple instances of another
entity.
- **Many-to-One:** Multiple instances of an entity are associated with one instance of
another entity.
- **Many-to-Many:** Multiple instances of an entity are associated with multiple
instances of another entity.

### 18. **How do you handle exceptions in a Spring Boot application?**

**Answer:**
In Spring Boot, exceptions can be handled using `@ExceptionHandler` in controllers
or globally using `@ControllerAdvice`. This allows for centralized exception handling
and custom error responses.

### 19. **What is the @ControllerAdvice annotation, and how does it work in Spring
Boot?**

**Answer:**
`@ControllerAdvice` is used to define global exception handling for Spring MVC
controllers. It allows you to write a single piece of code that handles exceptions
across all controllers.

### 20. **What is Aspect-Oriented Programming (AOP), and how is it used in Spring
Boot?**

**Answer:**
Aspect-Oriented Programming (AOP) allows you to separate cross-cutting concerns
(e.g., logging, security) from the business logic. In Spring Boot, AOP is implemented
using aspects and advice that can be applied declaratively to methods or classes.

### 21. **What approaches have you used for authentication in your Spring Boot
projects?**

**Answer:**
In my projects, I have used JWT (JSON Web Token) for stateless authentication, as
well as OAuth2 for secure access. Both approaches provide robust security and are
easy to integrate with Spring Security.

### 22. **How does JWT token-based authentication work in Spring Boot?**

**Answer:**
In JWT token-based authentication, a token is generated after a user successfully
logs in. This token is then included in the header of subsequent requests to
authenticate the user. The server verifies the token's validity and extracts user
information from it.

### 23. **What is role-based authentication, and how do you implement it in Spring
Boot?**

**Answer:**
Role-based authentication restricts access to certain parts of the application based
on user roles. In Spring Boot, it can be implemented using Spring Security by
assigning roles to users and securing endpoints with `@PreAuthorize` or
`@Secured`.

### 24. **How do you perform health checks in a Spring Boot application?**

**Answer:**
Health checks in Spring Boot can be performed using the Actuator module, which
provides endpoints like `/actuator/health` to check the application's health and status.

### 25. **What is a YAML file in Spring Boot, and how is it used?**
**Answer:**
A YAML file in Spring Boot is an alternative to the `application.properties` file for
configuring the application. It

provides a more readable and hierarchical way to define configuration settings.

### 26. **Given a string `str` and a substring `str1`, count how many times `str1`
appears in `str`.**

- **Example Input:**
`str = "i am good boy"`
`str1 = "am"`
- **Example Output:**
`1`

**Answer:**

```java
public class SubstringCount {
public static void main(String[] args) {
String str = "i am good boy";
String str1 = "am";
int count = countOccurrences(str, str1);
System.out.println(count);
}

public static int countOccurrences(String str, String subStr) {


int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
}
```

---
# HR Interview

### 1. Give a self-introduction and explain your project.


### 2. What tasks did you work on in your last project?
### 3. What are your salary expectations?
### 4. Are you interested in learning new technology?
### 5. Why are you looking for a new job? etc....
### 1. **Brief explanation about your project and daily tasks.**

In my current project, I am working on a [briefly describe the project’s purpose, such


as "banking application that handles customer transactions and account
management"]. My daily tasks involve designing and implementing microservices
using Spring Boot, developing RESTful APIs, managing the database using
JPA/Hibernate, writing unit tests with JUnit and Mockito, and deploying services to a
cloud environment like AWS. I also participate in code reviews, pair programming,
and daily stand-ups to ensure smooth progress.

### 2. **You mentioned you worked on microservices; can you elaborate?**

Yes, I have experience in designing, developing, and deploying microservices. I have


worked on breaking down a monolithic application into smaller, independent
microservices that can be developed, deployed, and scaled independently. Each
microservice handled a specific business capability and communicated with others
through RESTful APIs or message queues. This architecture improved our system's
scalability, maintainability, and fault tolerance.

### 3. **How do you handle fault tolerance in microservices?**

Fault tolerance in microservices is achieved using several strategies, including


implementing retries, fallbacks, and circuit breakers. We use libraries like Hystrix or
Resilience4j to manage circuit breaking and timeouts, ensuring that the failure of one
microservice does not cascade and affect the entire system. We also deploy services
across multiple instances and use load balancers to distribute traffic, ensuring high
availability.

### 4. **What is a circuit breaker in microservices?**

A circuit breaker is a design pattern used to detect and handle failures in


microservices. When a service fails or becomes unresponsive, the circuit breaker
trips and stops further calls to the failing service. Instead, it returns a fallback
response or an error message. This prevents the system from being overwhelmed
by repeated attempts to call the failing service, helping to maintain overall stability.

### 5. **How do you manage retrying, timeouts, and circuit breakers in


microservices?**

Retries, timeouts, and circuit breakers are managed using libraries like Resilience4j
or Hystrix. We configure retry logic to attempt an operation a certain number of times
before failing. Timeouts are set to ensure that requests do not hang indefinitely.
Circuit breakers monitor the failures and, after a threshold, trip to prevent further
calls. We also implement fallback mechanisms to provide default responses when a
service fails.

### 6. **How do microservices communicate with each other?**


Microservices communicate with each other using HTTP/REST, messaging queues,
or RPC frameworks like gRPC. For RESTful communication, we use HTTP requests
with JSON payloads. For asynchronous communication, we use messaging systems
like Kafka or RabbitMQ. gRPC is used for efficient communication between services,
especially when low latency and high throughput are required.

### 7. **What is gRPC?**

gRPC is a high-performance, open-source RPC framework that allows microservices


to communicate with each other efficiently. It uses Protocol Buffers (protobuf) for
serializing structured data, which is more efficient than JSON. gRPC supports bi-
directional streaming and is language-agnostic, allowing services written in different
programming languages to communicate seamlessly.

### 8. **How do you transfer data efficiently between microservices?**

To transfer data efficiently between microservices, we use lightweight data formats


like Protocol Buffers (protobuf) with gRPC. We also ensure that only necessary data
is transmitted by designing APIs with minimal payloads. Data compression and
pagination techniques are also applied to manage large datasets effectively.

### 9. **What is event-driven processing in microservices?**

Event-driven processing in microservices is an architectural pattern where services


communicate and react to events rather than direct requests. When an event occurs
(e.g., a user places an order), it is published to an event bus (e.g., Kafka). Other
services subscribe to these events and perform their actions accordingly. This
decouples services, allowing them to evolve independently and handle high traffic
efficiently.

### 10. **Explain the CQRS pattern in microservices.**

CQRS (Command Query Responsibility Segregation) is a design pattern where the


read and write operations are separated into different models. The command model
handles writes (modifications), while the query model handles reads (queries). This
separation allows for optimizing each model independently, improving performance,
and simplifying the design, especially in complex systems.

### 11. **What is the difference between synchronous and asynchronous


communication in microservices?**

- **Synchronous Communication:** Involves direct communication between


microservices where the caller waits for a response before proceeding. It is typically
implemented using REST APIs or RPC. This method can lead to tight coupling and
latency issues.

- **Asynchronous Communication:** Involves message-based communication where


the caller sends a message and continues its processing without waiting for a
response. It is typically implemented using messaging systems like Kafka or
RabbitMQ. This method promotes loose coupling and better scalability.
### 12. **What is load balancing, and how do you handle it in microservices?**

Load balancing is the process of distributing incoming network traffic across multiple
servers or instances to ensure no single server is overwhelmed. In microservices,
load balancing is handled using tools like NGINX, HAProxy, or cloud-based solutions
like AWS Elastic Load Balancer. Service discovery tools like Eureka can also
dynamically balance loads among instances.

### 13. **How do you monitor and measure metrics in microservices?**

We monitor and measure metrics in microservices using tools like Prometheus,


Grafana, and ELK stack (Elasticsearch, Logstash, Kibana). Metrics like CPU usage,
memory consumption, request rates, response times, and error rates are tracked.
Logs and traces are also collected using tools like Zipkin or Jaeger for distributed
tracing. Alerts are set up to notify the team of any issues.

### 14. **How do you handle a high number of incoming requests in microservices,
and how do you track and manage them?**

To handle a high number of incoming requests, we scale microservices horizontally


by deploying multiple instances behind a load balancer. We implement rate limiting,
caching, and use of efficient data stores. To track and manage requests, we use
distributed tracing tools like Jaeger and Prometheus for monitoring, which helps in
identifying bottlenecks and optimizing performance.

### 15. **Can you give some examples of design patterns?**

Some common design patterns used in microservices and general software


development include:
- **Singleton:** Ensures a class has only one instance.
- **Factory Method:** Creates objects without specifying the exact class.
- **Observer:** Allows objects to subscribe and receive notifications from another
object.
- **Strategy:** Enables selecting an algorithm's behavior at runtime.
- **Decorator:** Adds behavior to objects dynamically.

### 16. **Write a code example of the Singleton design pattern in Java.**

```java
public class Singleton {
// Private static instance of the class
private static Singleton instance;

// Private constructor to prevent instantiation


private Singleton() {}

// Public method to provide access to the instance


public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```

### 17. **If two threads access the same class simultaneously, how do you manage
it?**

To manage concurrent access by multiple threads, we use synchronization. In the


Singleton pattern, the `getInstance()` method is synchronized to ensure only one
thread can access it at a time, preventing multiple instances from being created.

### 18. **How can you give the option to clone a Singleton class?**

To allow cloning in a Singleton class while maintaining the singleton property,


override the `clone()` method and throw a `CloneNotSupportedException`.

```java
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Cannot clone a singleton object");
}
```

### 19. **What is the `Cloneable` interface in Java?**

The `Cloneable` interface in Java is a marker interface that indicates that a class
allows its objects to be cloned. When a class implements `Cloneable`, the
`Object.clone()` method creates a shallow copy of the object. If a class does not
implement `Cloneable`, calling `clone()` throws a `CloneNotSupportedException`.

### 20. **Write code to handle exceptions like `ArithmeticException` for division by
zero.**

```java
public class DivisionExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}

public static int divide(int a, int b) {


return a / b;
}
}
```

### 21. **Why do we use the `Optional` class in Java?**

The `Optional` class in Java is used to represent a value that might be `null`. It helps
avoid `NullPointerException` by providing a way to handle `null` values explicitly.
Using `Optional`, you can define default values, perform operations only when the
value is present, or throw an exception if the value is absent.

### 22. **Which methods are available in the `Optional` class?**

Some commonly used methods in the `Optional` class include:


- `of(T value)`: Creates an Optional with the specified value.
- `ofNullable(T value)`: Creates an Optional that may be empty if the value is `null`.
- `empty()`: Returns an empty Optional.
- `get()`: Returns the value if present, otherwise throws an exception.
- `isPresent()`: Checks if the value is present.
- `ifPresent(Consumer<? super T> action)`: Executes the given action if the value is
present.

- `orElse(T other)`: Returns the value if present, otherwise returns the provided
default value.
- `orElseThrow(Supplier<? extends X> exceptionSupplier)`: Returns the value if
present, otherwise throws the provided exception.

### 23. **How did you optimize a project when migrating from Java 7 to Java 8?
Provide a full project explanation.**

When migrating from Java 7 to Java 8, we optimized our project by leveraging Java
8's new features:
- **Lambda Expressions:** Replaced anonymous inner classes with lambda
expressions, making the code more concise and readable.
- **Streams API:** Used streams to process collections in a more functional style,
improving performance and reducing boilerplate code.
- **Optional:** Replaced null checks with `Optional` to handle `null` values more
safely.
- **Date and Time API:** Migrated from the old `java.util.Date` and
`java.util.Calendar` classes to the new `java.time` package, which offers a more
robust and easy-to-use API for date and time manipulation.

For example, we refactored the code to replace loops with streams, used
`Collectors` to accumulate results, and leveraged parallel streams to improve
performance in multi-core environments.

### 24. **What classes are available in the Java Time API?**

Some of the key classes in the Java Time API (`java.time` package) include:
- `LocalDate`: Represents a date (year, month, day) without time.
- `LocalTime`: Represents a time (hours, minutes, seconds, nanoseconds) without a
date.
- `LocalDateTime`: Combines `LocalDate` and `LocalTime` into a single date-time
object.
- `ZonedDateTime`: Represents a date-time with a time zone.
- `Instant`: Represents a specific point in time, typically used for timestamps.
- `Duration`: Represents a duration or amount of time.
- `Period`: Represents a date-based amount of time, such as "2 years, 3 months,
and 4 days."

### 25. **How do you schedule tasks in Java?**

Tasks in Java can be scheduled using the `ScheduledExecutorService` or the


`Timer` class. The `ScheduledExecutorService` is preferred as it provides more
flexibility and allows for multiple tasks to be scheduled concurrently.

```java
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TaskScheduler {


public static void main(String[] args) {
ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);

scheduler.scheduleAtFixedRate(() -> {
System.out.println("Task executed at: " + System.currentTimeMillis());
}, 0, 1, TimeUnit.SECONDS);
}
}
```

### 26. **What are parallel streams in Java?**

Parallel streams in Java allow you to process data in parallel, taking advantage of
multiple cores of the CPU. It is a feature of the Streams API where the stream's
operations are divided into smaller tasks that run concurrently, potentially improving
performance for large data sets.

### 27. **What are the advantages and disadvantages of parallel streams?**

**Advantages:**
- **Performance Improvement:** Parallel streams can significantly speed up the
processing of large data sets by utilizing multiple CPU cores.
- **Simplified Concurrency:** Parallel streams abstract away the complexities of
writing concurrent code, making it easier to implement parallelism.

**Disadvantages:**
- **Overhead:** For small data sets, the overhead of parallelization might outweigh
the benefits, leading to worse performance than sequential streams.
- **Non-Deterministic Order:** Parallel streams do not guarantee the order of
processing, which can be problematic if order matters.
- **Complexity in Debugging:** Debugging parallel streams can be more challenging
than sequential code due to the concurrency involved.

# MindGate
## L1 Interview
1. **Self-introduction based on your project.**
- "I am ______ with 3 years of experience in Java and ReactJS. In my current
project, I developed a customer registration service using ReactJS and Spring Boot,
integrating with multiple microservices to ensure secure and efficient data handling."

2. **Explain microservices architecture.**


- "Microservices architecture divides an application into small, independent
services, each responsible for a specific business functionality. These services
communicate over a network, allowing for decentralized development, scaling, and
deployment."

3. **How do microservices communicate internally?**


- "Microservices communicate internally using protocols like HTTP/REST, gRPC,
or messaging systems like Kafka. Service discovery tools and load balancers help
manage requests and ensure service availability."

4. **How does a JWT token work internally?**


- "A JWT token encodes user information and is signed with a secret key. The
token is sent to the client and included in subsequent requests. The server verifies
the token's signature to authenticate the user."

5. **Explain the Collection hierarchy in Java.**


- "The Collection hierarchy starts with `Iterable`, followed by `Collection`,
branching into `List`, `Set`, and `Queue`. `Map` is a separate interface for key-value
pairs, not extending `Collection`."

6. **If a `List` is declared as `final`, can we modify it?**


- "Yes, a `final` `List` can have its contents modified, but its reference cannot be
reassigned to another `List` object."

7. **Why does a `Set` not allow duplicates?**


- "A `Set` does not allow duplicates because it uses the `equals()` and
`hashCode()` methods to ensure all elements are unique."

8. **What is the difference between fail-safe and fail-fast iterators?**


- "Fail-fast iterators throw a `ConcurrentModificationException` if the collection is
modified during iteration. Fail-safe iterators work on a copy of the collection, allowing
safe iteration."
9. **Explain `ConcurrentHashMap`.**
- "`ConcurrentHashMap` is a thread-safe implementation of `Map` that allows
concurrent read and write operations by dividing the map into segments, reducing
contention."

10. **What happens when you use `HashMap` in a multithreaded environment?**


- "Using `HashMap` in a multithreaded environment can lead to data corruption
and unpredictable results due to concurrent modifications. `ConcurrentHashMap`
should be used instead."

11. **Describe the Java thread lifecycle.**


- "The Java thread lifecycle includes New, Runnable, Blocked, Waiting, Timed
Waiting, and Terminated states. A thread transitions through these states based on
its execution and synchronization."

12. **Write a custom `ArrayList` that does not allow duplicates.**


```java
import java.util.ArrayList;

public class UniqueArrayList<E> extends ArrayList<E> {


@Override
public boolean add(E e) {
if (!contains(e)) {
return super.add(e);
}
return false;
}
}
```

13. **How do you find the occurrences of words using `HashMap` in Java?**
```java
import java.util.HashMap;
import java.util.Map;

public class WordCount {


public static void main(String[] args) {
String text = "apple apple banana apple orange banana";
Map<String, Integer> wordCount = new HashMap<>();
for (String word : text.split(" ")) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```

14. **Write an SQL query to print account names based on the currency name.**
```sql
SELECT A.ACCNAME
FROM ACCOUNT A
JOIN COUNTRY C ON A.COUNTRYID = C.COUNTRYID
JOIN CURRENCY CUR ON C.CURRID = CUR.CURRID
WHERE CUR.CURRNAME = 'currency_name';
```

# L1 MindGate
1. **How to migrate HTML & JavaScript code to ReactJS?**

**Answer:**
To migrate HTML and JavaScript code to ReactJS, follow these steps:
- **Set Up React Environment:** Initialize a new React project using Create React
App or any other setup tool.
- **Component Structure:** Identify distinct sections of your HTML and JavaScript
that can be transformed into React components.
- **Convert HTML to JSX:** Replace HTML with JSX in your React components.
Ensure that you adjust syntax issues like class attributes (`class` to `className`),
inline styles, and self-closing tags.
- **State Management:** Convert JavaScript logic related to state and events into
React state and event handlers.
- **Refactor Functions:** Transform your JavaScript functions into React
component methods or hooks.
- **Routing:** If your application has multiple pages, set up React Router to
handle navigation.

2. **How to consume already shared messages in Kafka?**

**Answer:**
To consume messages that have already been shared in Kafka:
- **Set Consumer Group:** Configure your Kafka consumer to be part of a
consumer group. Kafka maintains offsets per consumer group.
- **Seek to Offset:** Use the `seek` method on your Kafka consumer to set the
offset to the position from which you want to start consuming messages. You can
seek to the beginning of the topic or a specific offset.
- **Configure Consumer Properties:** Ensure your consumer properties are set
correctly, such as `auto.offset.reset` (e.g., `earliest` to read from the beginning).

3. **What are your daily roles and responsibilities?**

**Answer:**
This answer will vary depending on the role, but generally:
- **Development:** Writing and maintaining code for various features and fixing
bugs.
- **Collaboration:** Working with cross-functional teams including designers,
product managers, and other developers.
- **Code Reviews:** Participating in code reviews to ensure code quality and
adherence to best practices.
- **Testing:** Writing and running unit tests and integration tests.
- **Deployment:** Assisting with the deployment of applications and ensuring
smooth production operations.

4. **What is the difference between `@RestController` and `@Controller` in Spring?


**

**Answer:**
- **`@Controller`:** Used in Spring MVC to define a controller class. It is used for
building web applications and returns views (JSP, Thymeleaf).
- **`@RestController`:** A specialized version of `@Controller` used for RESTful
web services. It combines `@Controller` and `@ResponseBody`, meaning it returns
data (usually JSON or XML) directly rather than rendering a view.

5. **What is the difference between method overloading and method overriding in


Java?**

**Answer:**
- **Method Overloading:** Occurs when multiple methods in a class have the
same name but different parameters (different type or number). It is resolved at
compile-time.
- **Method Overriding:** Occurs when a subclass provides a specific
implementation for a method that is already defined in its superclass. It is resolved at
runtime and must have the same name, return type, and parameters.

6. **What is a thread in Java?**

**Answer:**
A thread in Java is a lightweight subprocess that runs concurrently with other
threads. Threads allow a program to perform multiple tasks simultaneously. Each
thread has its own execution path but shares the same process resources.

7. **How do you handle exceptions in a `Runnable` since it cannot throw checked


exceptions?**

**Answer:**
Since `Runnable` does not allow throwing checked exceptions, handle exceptions
within the `run` method using a `try-catch` block. Log or manage the exception as
needed:

```java
public class MyRunnable implements Runnable {
@Override
public void run() {
try {
// Code that might throw an exception
} catch (Exception e) {
// Handle the exception
e.printStackTrace();
}
}
}
```

8. **What are the differences between `Callable` and `Runnable` in Java?**

**Answer:**
- **`Runnable`:** Represents a task that can be executed by a thread. It does not
return a result and cannot throw checked exceptions.
- **`Callable`:** Similar to `Runnable`, but it can return a result and can throw
checked exceptions. It has a `call` method that returns a value and may throw
exceptions.

9. **What is the difference between `wait()` and `sleep()` methods in Java?**

**Answer:**
- **`wait()`:** Called on an object’s monitor to release the lock and wait until
notified. It is used for inter-thread communication and requires synchronization.
- **`sleep()`:** A static method of the `Thread` class that pauses the thread for a
specified time but does not release the lock on any object.

10. **Can you explain the thread life cycle in Java?**

**Answer:**
The thread life cycle consists of:
- **New:** The thread is created but not yet started.
- **Runnable:** The thread is ready to run and waiting for CPU time.
- **Blocked:** The thread is waiting to acquire a lock or resource.
- **Waiting:** The thread is waiting indefinitely for another thread to perform a
particular action.
- **Timed Waiting:** The thread is waiting for a specified period.
- **Terminated:** The thread has completed execution or terminated.

11. **What is a thread pool in Java and how does it work?**

**Answer:**
A thread pool is a collection of reusable threads that are used to perform multiple
tasks. It reduces the overhead of thread creation and destruction by reusing existing
threads. The `ExecutorService` interface in Java provides a way to manage thread
pools, using classes like `ThreadPoolExecutor` and
`ScheduledThreadPoolExecutor`.

12. **What are the differences between Spring MVC and Spring Boot?**

**Answer:**
- **Spring MVC:** A framework for building web applications using the Model-
View-Controller design pattern. Requires configuration for setting up the application.
- **Spring Boot:** A framework that simplifies the setup and development of
Spring applications. It provides auto-configuration, embedded servers, and a
convention-over-configuration approach, allowing for rapid development.

13. **How do you join two tables in SQL? Provide an example query.**

**Answer:**
To join two tables in SQL, you use the `JOIN` clause. For example, to join
`employees` and `departments` tables:

```sql
SELECT e.employee_id, e.name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.department_id;
```

14. **Write a Java code snippet to find the top element in a mountain array.**

**Answer:**

```java
public class MountainArrayTop {

public static int findTopElement(int[] arr) {


int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) {
return arr[mid];
} else if (arr[mid] > arr[mid - 1]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // should not reach here if input is a valid mountain array
}

public static void main(String[] args) {


int[] mountainArray = {1, 3, 8, 12, 4, 2};
System.out.println("Top element: " + findTopElement(mountainArray));
}
}
```

**Example:**
- **Input:** `[1, 3, 8, 12, 4, 2]`
- **Output:** `12`

15. **Which technologies have you worked with, and how have you utilized them in
your projects?**
**Answer:**
This question is specific to your experience and will vary. Here’s an example
structure:
- **ReactJS:** Used for building dynamic and responsive user interfaces.
- **Spring Boot:** Utilized for creating RESTful APIs and microservices.
- **Kafka:** Implemented for handling real-time data streams and message
processing.
- **Docker/Kubernetes:** Deployed and managed containerized applications for
scalable and consistent environments.

# L2 MindGate

1. **Can you describe a project you have worked on?**

**Answer:**
- Provide an overview of the project, including its objectives, technology stack,
and your role.
- Mention key features or functionalities, any challenges faced, and how they
were overcome.

2. **How do you scale your project?**

**Answer:**
- Describe the strategies you use for scaling, such as load balancing, database
optimization, caching, or microservices architecture.
- Explain how you ensure the application can handle increased traffic or data
volume.

3. **How do you analyze code for performance and quality?**

**Answer:**
- Mention tools and techniques used, such as code reviews, static analysis tools,
profiling, and performance testing.
- Explain how you identify and address bottlenecks or issues in the code.

4. **Which version of Spring Boot and Java have you used in your project?**

**Answer:**
- Specify the versions of Spring Boot and Java used.
- Explain why you chose these versions and how they fit with your project
requirements.

5. **Why did you choose this company?**

**Answer:**
- Discuss what attracted you to the company, such as its reputation, culture,
projects, or growth opportunities.
- Mention how your goals and skills align with the company’s mission and values.
6. **Have you used threads in your project? If so, how?**

**Answer:**
- Provide examples of how you used threads, such as for parallel processing,
improving performance, or handling concurrent tasks.
- Describe any challenges related to thread management and how you addressed
them.

7. **Why do you use `ExecutorService` in your projects?**

**Answer:**
- Explain the benefits of using `ExecutorService`, such as managing thread pools,
simplifying concurrent task execution, and improving resource management.
- Discuss how it helps avoid issues related to manual thread management.

8. **Is it possible to solve tasks without using `ExecutorService`?**

**Answer:**
- Explain that while tasks can be solved without `ExecutorService` using raw
threads, `ExecutorService` provides a more efficient and manageable approach.
- Discuss the potential difficulties of manual thread management and how
`ExecutorService` simplifies concurrency.

9. **How do you ensure code quality and maintainability in your projects?**

**Answer:**
- Talk about practices such as code reviews, adherence to coding standards,
writing unit tests, and using design patterns.
- Mention tools and processes that help maintain code quality over time.

10. **How do you handle version control and collaboration in your projects?**

**Answer:**
- Describe your version control strategy, such as branching, merging, and pull
requests.
- Explain how you use collaboration tools and practices to work effectively with
your team.

# HR
1. BASICS,SALARY & LOCATION ....

### Oracle Interview Questions

## First Round
1. **Self-introduction**
2. **Coding Questions** -HackerRank coding
- Code 1-Find higest and lowest Rank of Students
- Code 2- Vending machine Problem
3. **SQL Queries**
- Query 1- joins Based Query
- Query 2- Pivot Based Query

## Second Round

### 1. Self-introduction based on project


- **Answer**: Provide a concise overview of your current project, highlighting key
technologies used, your role, and major achievements.
-
### 2. Write a Spring Boot project for login and register using JWT token through an
online Java compiler
- **Answer**:
```java
@SpringBootApplication
public class JwtDemoApplication {
public static void main(String[] args) {
SpringApplication.run(JwtDemoApplication.class, args);
}
}

@RestController
@RequestMapping("/auth")
public class AuthController {

@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody User user) {
// Code to save user
return ResponseEntity.ok("User registered successfully");
}

@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest
authRequest) {
// Code to authenticate user and generate JWT
return ResponseEntity.ok(new AuthResponse(jwtToken));
}
}

@Service
public class JwtService {
public String generateToken(UserDetails userDetails) {
// Code to generate JWT
}
}
```

### 3. How to handle when microservices fail


- **Answer**: Use fallback mechanisms, retry policies, and circuit breakers to
handle microservice failures. Implementing a circuit breaker pattern using libraries
like Resilience4j helps isolate failing services and prevent cascading failures.

### 4. How to implement circuit breakers in microservices


- **Answer**: Use Resilience4j to implement circuit breakers:
```java
@Service
public class MyService {

@CircuitBreaker(name = "myService", fallbackMethod = "fallbackMethod")


public String performOperation() {
// Code that may fail
}

public String fallbackMethod(Throwable t) {


return "Fallback response";
}
}
```

### 5. Write a program to sort a string array without using any sort method or inbuilt
functions
- **Answer**:
```java
public class StringArraySort {
public static void main(String[] args) {
String[] arr = {"banana", "apple", "cherry"};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (compareStrings(arr[i], arr[j]) > 0) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (String str : arr) {
System.out.println(str);
}
}

public static int compareStrings(String s1, String s2) {


int len = Math.min(s1.length(), s2.length());
for (int i = 0; i < len; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
return s1.charAt(i) - s2.charAt(i);
}
}
return s1.length() - s2.length();
}
}
```

### 6. Internal working process of HashMap


- **Answer**: HashMap works on the principle of hashing. It uses an array of
buckets to store key-value pairs. The `hashCode()` method determines the bucket
index. When collisions occur (i.e., multiple keys hash to the same index), they are
stored in a linked list or tree structure within the bucket. When retrieving, the key's
hash code and `equals()` method are used to find the correct value.

### 7. Scenario where overriding `hashCode` and `equals` is necessary in Java


- **Answer**: When creating a custom object to be used as a key in a HashMap
or other hash-based collections, you must override `hashCode` and `equals` to
ensure correct behavior. For example:
```java
public class Employee {
private int id;
private String name;

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id && Objects.equals(name, employee.name);
}

@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
```

### 8. Difference between HashMap and Hashtable


- **Answer**:
- **HashMap**: Non-synchronized, allows one null key and multiple null values,
generally faster.
- **Hashtable**: Synchronized, does not allow null keys or values, generally
slower due to synchronization overhead.

### 9. Difference between synchronized and non-synchronized with real-time


examples
- **Answer**:
- **Synchronized**: Thread-safe, ensures only one thread can access a
resource at a time. Example: `Hashtable` is synchronized.
- **Non-synchronized**: Not thread-safe, multiple threads can access resources
simultaneously. Example: `HashMap` is non-synchronized.
### 10. Write a program to make a HashMap synchronized
**Answer**:

```java
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SyncHashMapExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("1", "One");
map.put("2", "Two");
Map<String, String> syncMap = Collections.synchronizedMap(map);

synchronized (syncMap) {
for (Map.Entry<String, String> entry : syncMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
}
```

## Final Round
1. **Self-introduction**
2. **About qualification**
3. **About project**
4. **How you learned coding and family details**
5. **Which technology you know**
6. **If we offer you new technology, which technology would you choose?**
7. **In your developing project, which is your most struggling phase?**
8. **How did you overcome that?**
... **Etc...**

### 1. **Can you give a brief introduction about yourself, focusing on your recent
projects and the technologies you’ve worked with?**

*Answer:*
"I am a Java developer with extensive experience in building web applications using
Spring Boot and Hibernate. Recently, I worked on a student management system
where I implemented a REST API using Spring Boot. The project involved creating
and managing student records with features such as validation and exception
handling. I used JPA for database interactions and integrated global exception
handling to manage validation errors efficiently. This project helped me refine my
skills in building robust and scalable applications."
### 2. **What are the key features introduced in Java 8?**

*Answer:*
- **Lambda Expressions:** Allows concise representation of anonymous functions.
- **Functional Interfaces:** Interfaces with a single abstract method, used with
lambda expressions.
- **Streams API:** Enables functional-style operations on collections.
- **Optional Class:** A container object that may or may not contain a non-null value.
- **Default Methods:** Methods in interfaces with default implementations.
- **Date and Time API:** Provides a comprehensive date-time library.

### 3. **Write a Java method to withdraw an amount from an account. If the amount
is available, it should be withdrawn; otherwise, throw a custom exception
`InsufficientBalanceException` and handle it appropriately.**

*Answer:*

```java
public class BankAccount {
private double balance;

public BankAccount(double balance) {


this.balance = balance;
}

public void withdraw(double amount) throws InsufficientBalanceException {


if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance.");
} else {
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: " +
balance);
}
}

public double getBalance() {


return balance;
}
}

class InsufficientBalanceException extends Exception {


public InsufficientBalanceException(String message) {
super(message);
}
}
```

### 4. **Write a JUnit test case for the withdraw method you just implemented.**

*Answer:*
```java
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class BankAccountTest {

@Test
public void testWithdrawSuccess() throws InsufficientBalanceException {
BankAccount account = new BankAccount(1000.0);
account.withdraw(500.0);
assertEquals(500.0, account.getBalance());
}

@Test
public void testWithdrawFailure() {
BankAccount account = new BankAccount(300.0);
assertThrows(InsufficientBalanceException.class, () ->
account.withdraw(500.0));
}
}
```

### 5. **Using Java 8 Streams, how would you find the frequency of each character
in a string?**

*Answer:*

```java
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CharacterFrequency {


public static void main(String[] args) {
String str = "Java 8 Streams";
Map<Character, Long> frequencyMap = str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));

System.out.println(frequencyMap);
}
}
```

### 6. **Have you completed any certifications? If so, which ones, and how have
they helped you in your career?**

*Answer:*
"I have completed certifications in Java SE 8 Programmer and Spring Professional.
These certifications enhanced my understanding of core Java concepts and the
Spring framework, which has been instrumental in my ability to build scalable and
maintainable applications. The certifications provided me with deeper insights into
Java 8 features and Spring Boot best practices, which I apply in my projects to
deliver high-quality software."

### 7. **Which framework are you using to write test cases in your projects?**

*Answer:*
"I use JUnit 5 for writing test cases, along with Mockito for mocking dependencies.
JUnit 5 offers advanced features and better flexibility compared to its predecessors,
and Mockito helps in isolating the units of code during testing."

### 8. **Can you explain the architecture and data flow of Spring MVC?**

*Answer:*
- **Model:** Represents the data and business logic. Managed by Spring, often
using JPA entities.
- **View:** The presentation layer that displays data. Implemented using
technologies like JSP or Thymeleaf.
- **Controller:** Handles incoming requests, processes them, and returns a view or
data. Acts as an intermediary between Model and View.
- **DispatcherServlet:** The central servlet that handles all incoming requests and
routes them to appropriate controllers.
- **Flow:** The user makes a request -> DispatcherServlet forwards it to the
controller -> Controller interacts with the model and returns a view name ->
DispatcherServlet resolves the view and sends the response to the user.

### 9. **How does JWT token-based authentication work?**

*Answer:*
- **User Authentication:** User logs in with credentials, and the server validates
them.
- **Token Generation:** Upon successful login, the server generates a JWT
containing user information and signs it with a secret key.
- **Token Storage:** The client stores the JWT, typically in local storage or cookies.
- **Token Usage:** For subsequent requests, the client sends the JWT in the
Authorization header.
- **Token Validation:** The server verifies the token's signature and expiration. If
valid, it processes the request; otherwise, it rejects it.

### 10. **Why is REST API considered stateless?**

*Answer:*
- REST APIs are stateless because each request from the client must contain all the
necessary information for the server to fulfill the request. The server does not store
any session state between requests. This allows for scalability and simplicity, as the
server does not need to keep track of client states.
### 11. Create a Spring Boot project using Spring Initializer. Implement two APIs
(GET and POST) and handle exceptions in the project.
#### **Project Structure**

1. **Controller**
2. **Service**
3. **Repository**
4. **Entity**
5. **Exception Handling**
6. **Application Properties**

---

#### **1. Create a Spring Boot Project Using Spring Initializer**

- **Go to Spring Initializer:** Open [Spring Initializr](https://start.spring.io/).


- **Project Setup:**
- **Project:** Maven Project
- **Language:** Java
- **Spring Boot Version:** 3.x.x
- **Group:** `com.example`
- **Artifact:** `demo`
- **Name:** `demo`
- **Package Name:** `com.example.demo`
- **Packaging:** Jar
- **Java Version:** 17
- **Dependencies:**
- **Spring Web**
- **Spring Boot DevTools**
- **Spring Data JPA**
- **H2 Database**
- **Generate the Project:** Click "Generate" to download the project as a ZIP file.
- **Import into IDE:** Extract the ZIP file and import it into your IDE.

---

#### **2. Project Code**

#### **a. Entity**

Create the `Student` entity class:

```java
package com.example.demo.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.validation.constraints.Min;
@Entity
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@Min(18)
private int age;

// Constructors, Getters, and Setters

public Student() {}

public Student(String name, int age) {


this.name = name;
this.age = age;
}

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}
```

#### **b. Repository**

Create the `StudentRepository` interface:


```java
package com.example.demo.repository;

import com.example.demo.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student, Long> {


}
```

#### **c. Service**

Create the `StudentService` interface and its implementation:

**StudentService Interface:**

```java
package com.example.demo.service;

import com.example.demo.model.Student;

import java.util.List;

public interface StudentService {


Student saveStudent(Student student);
List<Student> getAllStudents();
Student getStudentById(Long id);
}
```

**StudentService Implementation:**

```java
package com.example.demo.service.impl;

import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import com.example.demo.service.StudentService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

private final StudentRepository studentRepository;

public StudentServiceImpl(StudentRepository studentRepository) {


this.studentRepository = studentRepository;
}

@Override
public Student saveStudent(Student student) {
return studentRepository.save(student);
}

@Override
public List<Student> getAllStudents() {
return studentRepository.findAll();
}

@Override
public Student getStudentById(Long id) {
return studentRepository.findById(id).orElse(null);
}
}
```

#### **d. Controller**

Create the `StudentController` class:

```java
package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/students")
public class StudentController {

private final StudentService studentService;

public StudentController(StudentService studentService) {


this.studentService = studentService;
}

@GetMapping
public ResponseEntity<List<Student>> getAllStudents() {
return new ResponseEntity<>(studentService.getAllStudents(),
HttpStatus.OK);
}
@PostMapping
public ResponseEntity<Student> createStudent(@Valid @RequestBody Student
student) {
return new ResponseEntity<>(studentService.saveStudent(student),
HttpStatus.CREATED);
}
}
```

#### **e. Exception Handling**

Create global exception handling for validation errors:

```java
package com.example.demo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.LinkedHashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>>
handleValidationException(MethodArgumentNotValidException ex) {
Map<String, String> errors = new LinkedHashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error -> {
errors.put(error.getField(), error.getDefaultMessage());
});
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}
```

#### **f. Application Properties**

Configure H2 database and server port in `application.properties`:

```properties
server.port=8080
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update
```

#### **g. Main Application Class**

Your main application class should look like this:

```java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}
}
```

---

#### **3. Running the Application**

1. **Run** the application by executing the `main` method in the `DemoApplication`


class.
2. **Test the APIs** using tools like Postman or `curl`:
- **GET** `/api/students` - Retrieves all students.
- **POST** `/api/students` - Creates a new student. Use JSON body like
`{"name": "John Doe", "age": 22}`.

---

### 1. Can you briefly introduce yourself?


------*****------
### 2. Can you give a brief explanation about your projects?
------******-----
### 3. What are the common error status codes?
- **400 Bad Request**: The server could not understand the request due to invalid
syntax.
- **401 Unauthorized**: The client must authenticate itself to get the requested
response.
- **403 Forbidden**: The client does not have access rights to the content.
- **404 Not Found**: The server can not find the requested resource.
- **500 Internal Server Error**: The server has encountered a situation it doesn't
know how to handle.

### 4. What are the new features in Java 8?


- **Lambda Expressions**: Introduce a new syntax and way to pass behavior as a
parameter.
- **Functional Interfaces**: Interfaces with a single abstract method.
- **Stream API**: For processing sequences of elements.
- **Optional**: A container object which may or may not contain a value.
- **New Date and Time API**: For improved date and time manipulation.
- **Default Methods**: Allow methods in interfaces to have implementations.

### 5. What is the String pool in Java?


The String pool is a special storage area in the Java heap where String literals are
stored. It helps in saving memory and improving performance by reusing instances
of String literals.

### 6. What is a marker interface and what are some inbuilt marker interfaces in
Java?
A marker interface is an interface with no methods or fields, used to signal to the
JVM or compiler some special behavior. Examples include:
- **Serializable**: Indicates that a class can be serialized.
- **Cloneable**: Indicates that a class can be cloned.
- **Remote**: Indicates that a class can be used in RMI (Remote Method
Invocation).

### 7. What is an HTTP POST method?


The HTTP POST method is used to send data to the server to create a resource.
The data sent to the server with POST is stored in the request body of the HTTP
request.

### 8. What is the difference between POST and GET methods?


- **GET**: Requests data from a specified resource, and the data is sent in the URL.
- **POST**: Submits data to be processed to a specified resource, and the data is
sent in the request body.

### 9. Can you use a try block without a catch block?


Yes, a try block can be used without a catch block if it is followed by a finally block.
The finally block will execute regardless of whether an exception occurs or not.

### 10. How do you use try with multiple catch blocks?
```java
try {
// code that may throw exceptions
} catch (IOException e) {
// handle IOException
} catch (SQLException e) {
// handle SQLException
} finally {
// cleanup code
}
```
This allows handling different types of exceptions separately.

### 11. What is try with resources?


Try with resources is a feature in Java that allows you to declare resources to be
closed automatically after the try block. It is used for managing resources such as
streams, files, etc.
```java
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// use br
} catch (IOException e) {
// handle IOException
}
```

### 12. How do you connect multiple databases in Spring Boot?


You can configure multiple data sources in Spring Boot by defining multiple
`DataSource` beans and using `@Primary` to specify the default data source. You
also need to configure multiple `EntityManagerFactory` and `TransactionManager`
beans for different data sources.

### 13. What is the difference between 400 and 403 status codes?
- **400 Bad Request**: Indicates that the server cannot process the request due to
client error (e.g., malformed request syntax).
- **403 Forbidden**: Indicates that the client’s request is valid, but the server is
refusing action. The client does not have the necessary permissions.

### 14. How do you create a singleton class in Java?


```java
public class Singleton {
private static Singleton instance;

private Singleton() {
// private constructor
}

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
# Tech Mahindra
## Java Questions

### 1. What are the new features in Java 8?


- Lambda Expressions
- Stream API
- Optional Class
- Default Methods in Interfaces
- Method References
- New Date and Time API (java.time)
- Nashorn JavaScript Engine

### 2. What is batch processing in Java?


- Batch processing refers to executing a series of jobs without manual
intervention. It can be implemented using frameworks like Spring Batch, which
provides reusable functions that process large volumes of data.

### 3. What is job scheduling in Java?


- Job scheduling involves setting up tasks to run at specified times or intervals.
Java provides APIs like `java.util.Timer` and
`java.util.concurrent.ScheduledExecutorService`. Additionally, libraries like Quartz
Scheduler offer more advanced features.

### 4. What are the inbuilt Java functional interfaces?


- `Predicate<T>`
- `Function<T, R>`
- `Supplier<T>`
- `Consumer<T>`
- `BiFunction<T, U, R>`

### 5. What is the difference between an interface and a functional interface?


- An interface can have any number of abstract methods.
- A functional interface has exactly one abstract method and can have any
number of default or static methods. It is used as the assignment target for lambda
expressions.

### 6. Explain the Singleton design pattern.


- The Singleton design pattern ensures that a class has only one instance and
provides a global point of access to it. It is typically implemented by making the
constructor private and providing a static method that returns the instance.

### 7. How can you break the Singleton design pattern?


- Using reflection to call the private constructor.
- Using serialization and deserialization.
- Using cloning.

### 8. What is a default method in Java and what is its use?


- A default method in an interface provides a default implementation that can be
overridden by implementing classes. It allows interfaces to evolve without breaking
existing implementations.

### 9. How do you handle errors in Java?


- Using try-catch blocks to catch and handle exceptions.
- Using `throws` keyword to declare exceptions.
- Using custom exception classes for specific error handling.

### 10. **How many types of exceptions are there in Java?


- Checked exceptions (subclasses of `Exception` except `RuntimeException`)
- Unchecked exceptions (subclasses of `RuntimeException`)
- Errors (subclasses of `Error`)

### 11. Explain checked and unchecked exceptions.


- Checked exceptions must be declared in a method or constructor's `throws`
clause if they can be thrown by the execution of the method or constructor and
propagated outside the method or constructor boundary.
- Unchecked exceptions do not need to be declared in a `throws` clause and can
be thrown at any time during the execution of the program.

### 12. What is the difference between shallow copy and deep copy?
- Shallow copy copies the object's fields as they are, so if the field is a reference to
another object, only the reference is copied.
- Deep copy creates a new instance of each object, recursively copying all nested
objects.

### 13. If you throw an IOException inside a try block, can you handle it in a catch
block with a runtime exception? Will it work or not and why?
- No, it will not work. An IOException is a checked exception and must be caught
or declared to be thrown. A catch block for a runtime exception (unchecked
exception) will not handle it.

### 14. What is serialization and deserialization?


- Serialization is the process of converting an object into a byte stream for storage
or transmission.
- Deserialization is the process of converting a byte stream back into an object.

15. Implement a generic double linked list with a method to remove an element
based on the index in Java.
```java
public class DoublyLinkedList<T> {
class Node {
T data;
Node prev, next;

Node(T data) {
this.data = data;
}
}
private Node head, tail;

public void remove(int index) {


if (index < 0) return;
Node current = head;
for (int i = 0; i < index && current != null; i++) {
current = current.next;
}
if (current == null) return;

if (current.prev != null) {
current.prev.next = current.next;
} else {
head = current.next;
}
if (current.next != null) {
current.next.prev = current.prev;
} else {
tail = current.prev;
}
}
}
```

### 16. Given two arrays, combine them into a single sorted array.
```java
int[] solution(int[] list1, int[] list2) {

int i = 0, j = 0, a = list1.length - 1, b = list2.length - 1;


int[] ans = new int[a+1 + b+1];
int k = 0;
while (i <= a || j <= b) {
if (i <= a && j <= b) {
if (list1[i] <= list2[j]) {
ans[k++] = list1[i++];
} else {
ans[k++] = list2[j++];
}
} else if (i <= a) {
ans[k++] = list1[i++];
} else if (j <= b) {
ans[k++] = list2[j++];
}
}
return ans;
}

```
### 17. Ladder array code in Java.
```java
public void printLadderArray(int n) {
int[][] ladder = new int[n][];
for (int i = 0; i < n; i++) {
ladder[i] = new int[i + 1];
for (int j = 0; j < i + 1; j++) {
ladder[i][j] = j + 1;
}
}
for (int[] row : ladder) {
System.out.println(Arrays.toString(row));
}
}
```

## Spring Boot Questions

### 1. What are profiles in Spring Boot?


- Profiles in Spring Boot are a way to segregate parts of your application
configuration and make it only available in certain environments. You can activate
profiles using the `--spring.profiles.active` command-line argument or by setting the
`spring.profiles.active` property in application properties.

### 2. How do you provide security in Spring Boot?


- By using Spring Security, which provides authentication and authorization.
Common methods include in-memory authentication, JDBC authentication, and
LDAP authentication.

### 3. Explain the process of JWT token-based authentication.


- The client sends a login request with credentials.
- The server validates the credentials and generates a JWT token.
- The client stores the token and includes it in the Authorization header of
subsequent requests.
- The server validates the token and processes the request if the token is valid.

### 4. What classes do you use in JWT token security?


- `JwtTokenProvider` for token generation and validation.
- `JwtAuthenticationFilter` to filter and validate requests.
- `JwtAuthenticationEntryPoint` for handling authentication errors.

### 5. Why do you need the UserDetails class in Spring Security?


- The `UserDetails` class represents a core user information. It provides
necessary information like username, password, and authorities for authentication
and authorization.

### 6. How do you handle exceptions in Spring Boot?


- Using `@ControllerAdvice` and `@ExceptionHandler` to handle exceptions
globally.
- Customizing the error response by defining a `ResponseEntity` with appropriate
status and message.

## Microservices Questions

### 1. What is fault tolerance in microservices?


- Fault tolerance is the ability of a system to continue operating properly in the
event of the failure of some of its components. This can be achieved using patterns
like circuit breaker, retry mechanisms, and fallback methods.

### 2. What is logging and distributed tracing in microservices?


- Logging involves recording information about the system's operation. Distributed
tracing helps in tracking and analyzing requests as they propagate through a
distributed system. Tools like ELK stack, Zipkin, and Jaeger are used for this
purpose.

### 3. How do you communicate between one microservice and another


microservice?
- Using REST APIs over HTTP.
- Using messaging queues like RabbitMQ or Kafka.
- Using gRPC for efficient communication.

### 4. How do you limit requests in microservices?


- Using rate limiting techniques, such as token bucket algorithm or leaky bucket
algorithm.
- Implementing API gateway tools like Netflix Zuul or Spring Cloud Gateway to
enforce rate limiting.

### 5. What is a Kafka server?


- Kafka is a distributed event streaming platform capable of handling high
throughput and low-latency data streams. It is used for building real-time data
pipelines and streaming applications.

### 6. Explain Jenkins and its use in microservices.


- Jenkins is a continuous integration and continuous delivery tool. It automates
the building, testing, and deploying of applications. In microservices, Jenkins can
manage the pipelines for each microservice, ensuring that changes are integrated
and deployed smoothly.

You might also like