Core Java - Company Based Int Qus
Core Java - Company Based Int Qus
Core Java - Company Based Int Qus
11. **Provide a customized example of a method reference with full code and
explanation.**
```java
import java.util.Arrays;
import java.util.List;
// Static method
public static void printName(String name) {
System.out.println(name);
}
// Instance method
public void printNameInstance(String name) {
System.out.println(name);
}
}
```
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");
}
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.*
?**
- *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.*
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.*
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';
```
```sql
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
```
```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.*
```sql
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
```
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;
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;
# Client Round
---
### 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.
### 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.
### 13. **What is the difference between `String`, `StringBuilder`, and `StringBuffer`?
**
- `String`: Immutable.
- `StringBuilder`: Mutable and not thread-safe.
- `StringBuffer`: Mutable and thread-safe (synchronized).
### 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.
### 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.
### 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 `|`.
### 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();
```
### 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).
### 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);
}
### 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.
### 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).
@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)
}
}
```
---
### 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}
```
### 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`.
### 10. How strong are you in Java theory and programming? Give a rating out of
10.
I would rate myself 8 out of 10.
### 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.
### 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;
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.
### 29. Write a code logic for the Singleton design pattern.
```java
public class Singleton {
private static Singleton instance;
private Singleton() {}
### 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".
### 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() {}
}
### 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);
```
@Autowired
public MyService(MyRepository repository) {
this.repository = repository;
}
}
```
# HR
--package, self
**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`).
**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.
**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.
**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.
**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.
### 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;
### 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;
# Altimetrix Company
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.
# Altimetrix Client L1
___soon
---
### **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.
---
- **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`)
---
- **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
# 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.
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.
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;
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;
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;
System.out.println(result);
}
}
```
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`.
@Autowired
public NotificationService(@Qualifier("emailService") MessageService
messageService) {
this.messageService = messageService;
}
@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);
}
}
```
```java
@Configuration
public class AppConfig {
@Bean
@Primary
public MessageService primaryMessageService() {
return new EmailService();
}
@Bean
public MessageService secondaryMessageService() {
return new SMSService();
}
}
```
## SQL Questions
# L2 Interview Questions
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."
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."
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;
@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + ", department='" +
department + "', salary=" + salary + "}";
}
}
```
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())
));
```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.
```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.
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.");
}
@Repository
public interface CheckoutRepository extends JpaRepository<Checkout, Long> {
}
@Repository
public interface BookRepository {
@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;
**Answer:**
**Syntax:**
```java
(parameters) -> expression
```
**Example:**
```java
import java.util.Arrays;
import java.util.List;
**Answer:**
**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.
**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;
**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.
**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;
**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.
```java
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
### 10. How do you use salt and hash in JWT to secure tokens?
**Answer:**
**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.
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
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 {
int maxLength = 0;
return maxLength;
}
**Example:**
- **Input:** `"babad"`
- **Output:** `3` (The longest palindromes are `"bab"` or `"aba"`, both with a length of
3)
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"));
```
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';
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>
);
};
15. **Write code to change the color of text in a `div` or `span` when data is
posted.**
```javascript
import React, { useState } from 'react';
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>
);
};
## 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.
```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 {};
}
```
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;
@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());
}
}
```
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.
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
### 3. Have you worked on GCP and deployed any project in GCP?
**Answer:** [Yes/No. If yes, explain the project and deployment process.]
### 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.
### 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.
### 25. What is the return type of map and forEach in JavaScript?
**Answer:** `map` returns a new array, `forEach` returns `undefined`.
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.
promise.then(data => {
console.log(data); // Promise resolved
});
```
### 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.
### 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;
### 36. Write code to display age difference using the Period class.
**Answer:**
```java
import java.time.LocalDate;
import java.time.Period;
// 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;
```
### 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.
// 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
}
}
```
// 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);
}
```
### 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;
### 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;
### 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;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long deptId;
private String deptName;
@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long projectId;
private String projectName;
@ManyToOne
@JoinColumn(name = "deptId")
private Department department;
### 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.
### 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.
### 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.
**Answer:**
1. **Arrow Functions:** Provides a shorter syntax for writing functions.
```javascript
const add = (a, b) => a + b;
```
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
console.log(sum(1, 2, 3)); // 6
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
console.log(obj2); // { a: 1, b: 2, c: 3 }
```
// main.js
import { name } from './module.js';
console.log(name); // John
```
---
### 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.
---
**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>;
}
}
```
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>;
}
}
```
1. **Can you provide a brief self-introduction and explain your current 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;
- **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:
- **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.
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)
);
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;
```
@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?**
@Component("abc")
public class Abc implements Filter {
}
@Component("abc1")
public class Abc1 implements Filter {
}
```
- **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?**
15. **How do you communicate between one API and another API?**
- **Answer:**
- **`Mono`:** Represents a single asynchronous value or an empty value.
- **`Flux`:** Represents a stream of 0 to N asynchronous values.
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?**
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:** 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.
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'
```
- **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.
- **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.
# Technical Round
## Java Questions
### 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.
### 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;
### 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.
---
### 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();
}
```
### 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");
}
}
```
### 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.
### 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.
### 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();
```
### 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
### 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.
### 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.
### 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.
### 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.....
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;
```
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.
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)
- **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
```
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);
```
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"
```
- **Answer:** `List.of()` creates an immutable list with the provided elements. For
example,
`List<String> list = List.of("A", "B", "C");`.
### 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);
### 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()));
}
```
- **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.
### 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:** `@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
```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
### 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);
}
```
- **Answer:** React is fast due to its use of the virtual DOM, which minimizes direct
manipulation of the actual DOM, reducing performance overhead.
- **Answer:** The virtual DOM is a lightweight copy of the real DOM. It represents
the UI components as JavaScript objects, which React updates efficiently.
### 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;
- **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;
- **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:**
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;
@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);
@Test
public void testFindAllVehicles() {
Vehicle vehicle1 = new Vehicle();
vehicle1.setMake("Toyota");
vehicle1.setModel("Corolla");
vehicle1.setYear(2020);
vehicleRepository.save(vehicle1);
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;
@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);
when(vehicleRepository.findAll()).thenReturn(List.of(vehicle1, vehicle2));
@Test
public void testSaveVehicle() {
Vehicle vehicle = new Vehicle();
vehicle.setMake("Ford");
vehicle.setModel("Focus");
vehicle.setYear(2021);
when(vehicleRepository.save(vehicle)).thenReturn(vehicle);
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;
@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';
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>
);
};
**`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;
}
```
**`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');
// Assertions
expect(await screen.findByText(/Toyota Corolla/i)).toBeInTheDocument();
expect(await screen.findByText(/Honda Civic/i)).toBeInTheDocument();
});
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;
.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.
**Create JWT Utility Class:** This class will handle JWT creation, validation, and
parsing. It includes methods to generate tokens, extract claims, and validate tokens.
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;
// Controller
@GetMapping("/users")
public Page<User> listUsers(Pageable pageable) {
return userService.getUsers(pageable);
}
```
You can use Spring Data JPA’s `Sort` class to sort data.
```java
import org.springframework.data.domain.Sort;
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.
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.
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?
### 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.
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?
// 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
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;
};
### 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.
```javascript
import { render, screen } from '@testing-library/react';
import App from './App';
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?
```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)
### 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.
### 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));
```
### 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);
}
```
### 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());
}
}
```
### 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.
useEffect(() => {
fetch('http://localhost:8080/api/items')
.then(response => response.json())
.then(data => setItems(data));
}, []);
### 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;
@Repository
public interface ItemRepository extends JpaRepository<Item, Long> {}
@Entity
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
- **React Integration:**
```javascript
import React, { useState, useEffect } from 'react';
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>
);
};
# HCL L1
// 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);
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>
);
}
# HCL L2
11. **Provide a customized example of a method reference with full code and
explanation.**
```java
import java.util.Arrays;
import java.util.List;
// Static method
public static void printName(String name) {
System.out.println(name);
}
// Instance method
public void printNameInstance(String name) {
System.out.println(name);
}
}
```
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");
}
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.*
?**
- *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.*
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.*
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';
```
```sql
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
```
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.*
```sql
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
```
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;
```java
import java.util.Arrays;
# HR
1. **self-salary etc..**
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.
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.");
}
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));
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("The time is now " + new Date());
}
}
```
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`
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};
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;
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());
}
---
### 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);
}
}
```
---
- **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
---
---
---
@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.
---
---
---
### 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).
---
---
---
### 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.
---
---
#Technical Round
## Self-Introduction and Project Explanation
## 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.*
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.*
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.*
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;
```
- *This code first removes duplicates, sorts the array, and then retrieves the
second last element.*
-*[Reference code]*
*Code Example for Fail-Fast Iterators:*
```java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
```java
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
### 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.*
### 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.*
# Manager Round
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.*
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.*
# 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.
**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 + " ");
}
}
### 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);
```
**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;
### 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.
**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
### 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);
}
---
# HR Interview
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.
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.
### 14. **How do you handle a high number of incoming requests in microservices,
and how do you track and manage them?**
### 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;
### 17. **If two threads access the same class simultaneously, how do you manage
it?**
### 18. **How can you give the option to clone a Singleton class?**
```java
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Cannot clone a singleton object");
}
```
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.");
}
}
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.
- `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."
```java
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
scheduler.scheduleAtFixedRate(() -> {
System.out.println("Task executed at: " + System.currentTimeMillis());
}, 0, 1, TimeUnit.SECONDS);
}
}
```
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."
13. **How do you find the occurrences of words using `HashMap` in Java?**
```java
import java.util.HashMap;
import java.util.Map;
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.
**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).
**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.
**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.
**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.
**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.
**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();
}
}
}
```
**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.
**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.
**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.
**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 {
**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
**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.
**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.
**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.
**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.
**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.
**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.
**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 ....
## 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
@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
}
}
```
### 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);
}
}
@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);
}
}
```
```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;
### 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;
@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;
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.
*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.
*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**
---
---
```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;
@Min(18)
private int age;
public Student() {}
import com.example.demo.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
**StudentService Interface:**
```java
package com.example.demo.service;
import com.example.demo.model.Student;
import java.util.List;
**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 {
@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);
}
}
```
```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 {
@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);
}
}
```
```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);
}
}
```
```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
```
```java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
---
---
### 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).
### 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.
### 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.
private Singleton() {
// private constructor
}
### 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.
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;
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) {
```
### 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));
}
}
```
## Microservices Questions