├── README.md ├── MindGate ├── MindGate.md └── MindGate1.md ├── TCS ├── tcs.md └── TCS.md ├── FSS └── FSS.md ├── Aspire systems └── AspireSystem2.md ├── Altimetrix ├── Altimetrix.md └── Altimetrix_Interview.md ├── IBS Software (walk_in) └── IBS.md ├── Hire Bridge Consultancy └── HireBridgeConsultancy.md ├── Oracle └── oracle.md ├── ACL Digital (Paypal,Adobe) └── Paypal-new Client.md ├── ZOHO (walk_in) └── zoho.md ├── HCL └── hcl.md ├── Tech Mahindra └── TechMahindra.md ├── Ford Motor ├── FordReference.md └── Foad Interview_1.md ├── Amazon └── Amazon.md ├── KVAS Technologies └── KVASTechnologies.md ├── Centrico └── Centrico.md ├── PayPal └── PayPal.md ├── Axis └── Axis.md ├── Infosis └── InfosisInterview.md ├── Synechron └── Synechron.md └── LTIMindtree └── LtiMindtree.md /README.md: -------------------------------------------------------------------------------- 1 | # Java-Full-Stack-interview-questions-3-years-experience 2 | A curated collection of Java full stack interview questions for professionals with 3 years of experience. This repository covers essential topics like Java, Hibernate, Spring Boot, microservices, JavaScript, ReactJS, HTML, CSS, and JUnit, tailored to help you excel in your interviews with various companies. 3 | -------------------------------------------------------------------------------- /MindGate/MindGate.md: -------------------------------------------------------------------------------- 1 | # MindGate 2 | ## L1 Interview 3 | 1. **Self-introduction based on your project.** 4 | - "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." 5 | 6 | 2. **Explain microservices architecture.** 7 | - "Microservices architecture divides an application into small, independent services, each responsible for a specific business functionality. These services communicate over a network, allowing for decentralized development, scaling, and deployment." 8 | 9 | 3. **How do microservices communicate internally?** 10 | - "Microservices communicate internally using protocols like HTTP/REST, gRPC, or messaging systems like Kafka. Service discovery tools and load balancers help manage requests and ensure service availability." 11 | 12 | 4. **How does a JWT token work internally?** 13 | - "A JWT token encodes user information and is signed with a secret key. The token is sent to the client and included in subsequent requests. The server verifies the token's signature to authenticate the user." 14 | 15 | 5. **Explain the Collection hierarchy in Java.** 16 | - "The Collection hierarchy starts with `Iterable`, followed by `Collection`, branching into `List`, `Set`, and `Queue`. `Map` is a separate interface for key-value pairs, not extending `Collection`." 17 | 18 | 6. **If a `List` is declared as `final`, can we modify it?** 19 | - "Yes, a `final` `List` can have its contents modified, but its reference cannot be reassigned to another `List` object." 20 | 21 | 7. **Why does a `Set` not allow duplicates?** 22 | - "A `Set` does not allow duplicates because it uses the `equals()` and `hashCode()` methods to ensure all elements are unique." 23 | 24 | 8. **What is the difference between fail-safe and fail-fast iterators?** 25 | - "Fail-fast iterators throw a `ConcurrentModificationException` if the collection is modified during iteration. Fail-safe iterators work on a copy of the collection, allowing safe iteration." 26 | 27 | 9. **Explain `ConcurrentHashMap`.** 28 | - "`ConcurrentHashMap` is a thread-safe implementation of `Map` that allows concurrent read and write operations by dividing the map into segments, reducing contention." 29 | 30 | 10. **What happens when you use `HashMap` in a multithreaded environment?** 31 | - "Using `HashMap` in a multithreaded environment can lead to data corruption and unpredictable results due to concurrent modifications. `ConcurrentHashMap` should be used instead." 32 | 33 | 11. **Describe the Java thread lifecycle.** 34 | - "The Java thread lifecycle includes New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated states. A thread transitions through these states based on its execution and synchronization." 35 | 36 | 12. **Write a custom `ArrayList` that does not allow duplicates.** 37 | ```java 38 | import java.util.ArrayList; 39 | 40 | public class UniqueArrayList extends ArrayList { 41 | @Override 42 | public boolean add(E e) { 43 | if (!contains(e)) { 44 | return super.add(e); 45 | } 46 | return false; 47 | } 48 | } 49 | ``` 50 | 51 | 13. **How do you find the occurrences of words using `HashMap` in Java?** 52 | ```java 53 | import java.util.HashMap; 54 | import java.util.Map; 55 | 56 | public class WordCount { 57 | public static void main(String[] args) { 58 | String text = "apple apple banana apple orange banana"; 59 | Map wordCount = new HashMap<>(); 60 | for (String word : text.split(" ")) { 61 | wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); 62 | } 63 | for (Map.Entry entry : wordCount.entrySet()) { 64 | System.out.println(entry.getKey() + ": " + entry.getValue()); 65 | } 66 | } 67 | } 68 | ``` 69 | 70 | 14. **Write an SQL query to print account names based on the currency name.** 71 | ```sql 72 | SELECT A.ACCNAME 73 | FROM ACCOUNT A 74 | JOIN COUNTRY C ON A.COUNTRYID = C.COUNTRYID 75 | JOIN CURRENCY CUR ON C.CURRID = CUR.CURRID 76 | WHERE CUR.CURRNAME = 'currency_name'; 77 | ``` 78 | 79 | -------------------------------------------------------------------------------- /TCS/tcs.md: -------------------------------------------------------------------------------- 1 | ### 1. Can you briefly introduce yourself? 2 | ------*****------ 3 | ### 2. Can you give a brief explanation about your projects? 4 | ------******----- 5 | ### 3. What are the common error status codes? 6 | - **400 Bad Request**: The server could not understand the request due to invalid syntax. 7 | - **401 Unauthorized**: The client must authenticate itself to get the requested response. 8 | - **403 Forbidden**: The client does not have access rights to the content. 9 | - **404 Not Found**: The server can not find the requested resource. 10 | - **500 Internal Server Error**: The server has encountered a situation it doesn't know how to handle. 11 | 12 | ### 4. What are the new features in Java 8? 13 | - **Lambda Expressions**: Introduce a new syntax and way to pass behavior as a parameter. 14 | - **Functional Interfaces**: Interfaces with a single abstract method. 15 | - **Stream API**: For processing sequences of elements. 16 | - **Optional**: A container object which may or may not contain a value. 17 | - **New Date and Time API**: For improved date and time manipulation. 18 | - **Default Methods**: Allow methods in interfaces to have implementations. 19 | 20 | ### 5. What is the String pool in Java? 21 | The String pool is a special storage area in the Java heap where String literals are stored. It helps in saving memory and improving performance by reusing instances of String literals. 22 | 23 | ### 6. What is a marker interface and what are some inbuilt marker interfaces in Java? 24 | A marker interface is an interface with no methods or fields, used to signal to the JVM or compiler some special behavior. Examples include: 25 | - **Serializable**: Indicates that a class can be serialized. 26 | - **Cloneable**: Indicates that a class can be cloned. 27 | - **Remote**: Indicates that a class can be used in RMI (Remote Method Invocation). 28 | 29 | ### 7. What is an HTTP POST method? 30 | The HTTP POST method is used to send data to the server to create a resource. The data sent to the server with POST is stored in the request body of the HTTP request. 31 | 32 | ### 8. What is the difference between POST and GET methods? 33 | - **GET**: Requests data from a specified resource, and the data is sent in the URL. 34 | - **POST**: Submits data to be processed to a specified resource, and the data is sent in the request body. 35 | 36 | ### 9. Can you use a try block without a catch block? 37 | Yes, a try block can be used without a catch block if it is followed by a finally block. The finally block will execute regardless of whether an exception occurs or not. 38 | 39 | ### 10. How do you use try with multiple catch blocks? 40 | ```java 41 | try { 42 | // code that may throw exceptions 43 | } catch (IOException e) { 44 | // handle IOException 45 | } catch (SQLException e) { 46 | // handle SQLException 47 | } finally { 48 | // cleanup code 49 | } 50 | ``` 51 | This allows handling different types of exceptions separately. 52 | 53 | ### 11. What is try with resources? 54 | Try with resources is a feature in Java that allows you to declare resources to be closed automatically after the try block. It is used for managing resources such as streams, files, etc. 55 | ```java 56 | try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { 57 | // use br 58 | } catch (IOException e) { 59 | // handle IOException 60 | } 61 | ``` 62 | 63 | ### 12. How do you connect multiple databases in Spring Boot? 64 | You can configure multiple data sources in Spring Boot by defining multiple `DataSource` beans and using `@Primary` to specify the default data source. You also need to configure multiple `EntityManagerFactory` and `TransactionManager` beans for different data sources. 65 | 66 | ### 13. What is the difference between 400 and 403 status codes? 67 | - **400 Bad Request**: Indicates that the server cannot process the request due to client error (e.g., malformed request syntax). 68 | - **403 Forbidden**: Indicates that the client’s request is valid, but the server is refusing action. The client does not have the necessary permissions. 69 | 70 | ### 14. How do you create a singleton class in Java? 71 | ```java 72 | public class Singleton { 73 | private static Singleton instance; 74 | 75 | private Singleton() { 76 | // private constructor 77 | } 78 | 79 | public static Singleton getInstance() { 80 | if (instance == null) { 81 | instance = new Singleton(); 82 | } 83 | return instance; 84 | } 85 | } 86 | ``` 87 | -------------------------------------------------------------------------------- /FSS/FSS.md: -------------------------------------------------------------------------------- 1 | 2 | 1. **Brief about the project:** 3 | - The project is a real-time banking application designed to handle customer transactions and registration. It includes functionalities such as account management, transaction processing, and secure data handling using microservices architecture and deployed on Docker. 4 | 5 | 2. **Steps to deploy microservices to Docker:** 6 | - 1. **Dockerize each microservice** by creating a `Dockerfile`. 7 | - 2. **Build Docker images** using the `docker build` command. 8 | - 3. **Run containers** using `docker run`, specifying network configurations if needed. 9 | - 4. **Configure networking** (optional) with Docker Compose or custom networks. 10 | - 5. **Monitor and scale** using Docker commands or orchestration tools. 11 | 12 | 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:** 13 | ```sql 14 | SELECT c.first_name, c.last_name, c.age, i.item, i.amount 15 | FROM customer c 16 | JOIN item i ON c.customer_id = i.customer_id 17 | WHERE c.age > 25; 18 | ``` 19 | 20 | 4. **Explain Actuator in Spring Boot:** 21 | - Actuator provides production-ready features in Spring Boot, such as monitoring and managing applications via endpoints like health, metrics, and environment information, making it easier to maintain and troubleshoot services. 22 | 23 | 5. **What are Servlet and JSP?** 24 | - **Servlet**: A Java class that handles HTTP requests and generates dynamic web content. 25 | - **JSP (JavaServer Pages)**: A technology that allows embedding Java code into HTML to create dynamic web pages, simplifying web development by separating business logic from presentation. 26 | 27 | 6. **Describe Java Streams and Lambda functions:** 28 | - **Streams**: A sequence of elements supporting functional-style operations to process collections, like filtering and mapping. 29 | - **Lambda Functions**: Anonymous functions used to implement functional interfaces, enabling concise and readable code, especially in stream operations. 30 | 31 | 7. **What are the steps to establish a JDBC connection?** 32 | - 1. **Load the JDBC driver** using `Class.forName()`. 33 | - 2. **Establish a connection** using `DriverManager.getConnection()`. 34 | - 3. **Create a statement object** using `connection.createStatement()`. 35 | - 4. **Execute SQL queries** with `statement.executeQuery()` or `executeUpdate()`. 36 | - 5. **Close the connection** using `connection.close()`. 37 | 38 | 8. **Difference between StringBuffer and StringBuilder:** 39 | - **StringBuffer**: Synchronized and thread-safe but slower due to overhead. 40 | - **StringBuilder**: Non-synchronized, faster, and preferable in single-threaded environments for string manipulation. 41 | 42 | 9. **How to document request and response options using Swagger, and how to convert to YAML?** 43 | - 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. 44 | 45 | 10. **How do you expose REST API call endpoints?** 46 | - Expose endpoints by annotating controller methods with `@GetMapping`, `@PostMapping`, etc., and defining the URI paths in Spring Boot applications. 47 | 48 | 11. **Which mechanism did you use to develop the project?** 49 | - The project was developed using a microservices architecture with Spring Boot for creating RESTful services, Docker for containerization, and a CI/CD pipeline for automated deployments. 50 | 51 | 12. **What are implicit objects in JSP?** 52 | - Implicit objects are pre-defined objects available in JSP for accessing various functionalities like `request`, `response`, `session`, `application`, `out`, and more, without explicit declaration. 53 | 54 | 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:** 55 | 56 | ```java 57 | List list1 = Arrays.asList("java", "aws", "oracle", "python"); 58 | List list2 = Arrays.asList("java", "oracle", "jquery"); 59 | 60 | // Common elements 61 | List common = list1.stream() 62 | .filter(list2::contains) 63 | .collect(Collectors.toList()); 64 | 65 | // Unique elements 66 | List unique = Stream.concat(list1.stream(), list2.stream()) 67 | .distinct() 68 | .filter(e -> !(list1.contains(e) && list2.contains(e))) 69 | .collect(Collectors.toList()); 70 | ``` 71 | -------------------------------------------------------------------------------- /Aspire systems/AspireSystem2.md: -------------------------------------------------------------------------------- 1 | 2 | --- 3 | 4 | ### **1. What is a hash collision?** 5 | - **Answer:** A hash collision occurs when two different keys in a hash-based collection, such as a `HashMap`, produce the same hash code and thus are placed in the same bucket. This can lead to performance degradation as multiple keys have to be stored and managed in the same location. 6 | 7 | ### **2. When does a collision error occur in hash-based collections?** 8 | - **Answer:** A collision error occurs in hash-based collections when multiple keys are mapped to the same hash code, causing them to be stored in the same bucket. This results in a need for the collection to handle the collision, usually through chaining (linked list) or open addressing (probing). 9 | 10 | ### **3. What are the key differences between `Runnable` and `Callable` in Java?** 11 | - **Answer:** 12 | - **`Runnable`:** Does not return a result and cannot throw a checked exception. 13 | - **`Callable`:** Returns a result (`T`) and can throw checked exceptions. 14 | - `Runnable` is executed by `Thread` or `Executor`, while `Callable` is executed by `ExecutorService`. 15 | 16 | ### **4. What is the difference between `map` and `flatMap` in Java Streams?** 17 | - **Answer:** 18 | - **`map`:** Transforms each element in the stream into another form, producing a stream of the same structure. 19 | - **`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. 20 | 21 | ### **5. How does `flatMap` work internally?** 22 | - **Answer:** Internally, `flatMap` applies a function that returns a stream for each element of the original stream. It then flattens these streams into a single stream, effectively concatenating them. This is achieved through a combination of the `map` operation and the `Stream.flatMap` method, which merges the nested streams. 23 | 24 | --- 25 | 26 | ### **6. Find and Insert Target in a Sorted Array:** 27 | 28 | - **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. 29 | 30 | **Example:** 31 | - **Input 1:** 32 | - Array: `[4, 1, 7, 2]` 33 | - Target: `4` 34 | - **Output:** `0` 35 | - **Input 2:** 36 | - Array: `[4, 1, 7, 2]` 37 | - Target: `5` 38 | - **Output:** `3` (because the array becomes `[1, 2, 4, 5, 7]` and `5` is at index `3`) 39 | 40 | - **Answer (Java Code):** 41 | ```java 42 | import java.util.Arrays; 43 | 44 | public class InsertAndFindIndex { 45 | public static int insertAndFindIndex(int[] arr, int target) { 46 | for (int i = 0; i < arr.length; i++) { 47 | if (arr[i] == target) { 48 | return i; 49 | } 50 | } 51 | Arrays.sort(arr); 52 | int index = Arrays.binarySearch(arr, target); 53 | if (index >= 0) { 54 | return index; 55 | } 56 | return -(index + 1); 57 | } 58 | 59 | public static void main(String[] args) { 60 | int[] arr1 = {4, 1, 7, 2}; 61 | int target1 = 4; 62 | System.out.println(insertAndFindIndex(arr1, target1)); // Output: 0 63 | 64 | int[] arr2 = {4, 1, 7, 2}; 65 | int target2 = 5; 66 | System.out.println(insertAndFindIndex(arr2, target2)); // Output: 3 67 | } 68 | } 69 | ``` 70 | 71 | --- 72 | 73 | ### **7. Capitalize and Count Words in a List Using Streams:** 74 | 75 | - **Question:** You are given a list of lowercase strings. Write a Java program that: 76 | - Capitalizes the first letter of each word. 77 | - Counts the occurrences of each word after capitalization. 78 | 79 | **Example:** 80 | - **Input:** 81 | - List: `["hello", "world", "this", "hello"]` 82 | - **Output:** 83 | - Capitalized List: `["Hello", "World", "This", "Hello"]` 84 | - Word Counts: 85 | - `Hello`: 2 86 | - `World`: 1 87 | - `This`: 1 88 | 89 | - **Answer (Java Code):** 90 | ```java 91 | import java.util.*; 92 | import java.util.function.Function; 93 | import java.util.stream.Collectors; 94 | 95 | public class CapitalizeWords { 96 | public static void main(String[] args) { 97 | List words = Arrays.asList("hello", "world", "this", "hello"); 98 | 99 | List capitalizedWords = words.stream() 100 | .map(word -> word.isEmpty() ? word : Character.toUpperCase(word.charAt(0)) + word.substring(1)) 101 | .collect(Collectors.toList()); 102 | 103 | System.out.println("Capitalized List: " + capitalizedWords); 104 | 105 | Map wordCounts = words.stream() 106 | .map(word -> word.isEmpty() ? word : Character.toUpperCase(word.charAt(0)) + word.substring(1)) 107 | .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 108 | 109 | wordCounts.forEach((word, count) -> System.out.println(word + ": " + count)); 110 | } 111 | } 112 | ``` 113 | -------------------------------------------------------------------------------- /Altimetrix/Altimetrix.md: -------------------------------------------------------------------------------- 1 | 2 | ### 1. **What are the key features introduced in Java 8?** 3 | 4 | **Answer:** 5 | - **Lambda Expressions**: Allows for concise representation of instances of single-method interfaces (functional interfaces). 6 | - **Stream API**: Provides a new abstraction for processing sequences of elements, supporting operations like map, filter, and reduce. 7 | - **Optional Class**: A container object which may or may not contain a value, used to avoid null references. 8 | - **Default Methods**: Interfaces can now have methods with a body, allowing for backward compatibility. 9 | - **Method References**: Shortcuts to call methods using the syntax `ClassName::methodName`. 10 | - **New Date and Time API**: A new, comprehensive API for handling dates and times (`java.time` package). 11 | 12 | ### 2. **What are the built-in functional interfaces available in Java 8?** 13 | 14 | **Answer:** 15 | - **`Predicate`**: Represents a boolean-valued function of one argument. 16 | - **`Function`**: Represents a function that takes an argument of type `T` and returns a result of type `R`. 17 | - **`Consumer`**: Represents an operation that accepts a single input argument and returns no result. 18 | - **`Supplier`**: Represents a supplier of results, providing instances of type `T`. 19 | - **`UnaryOperator`**: A specialized form of `Function` that takes a single argument and returns a result of the same type. 20 | - **`BinaryOperator`**: A specialized form of `Function` that takes two arguments of the same type and returns a result of the same type. 21 | 22 | ### 3. **What is a profile in Spring Boot, and how do you use it?** 23 | 24 | **Answer:** 25 | - **Profile**: A feature that allows for the segregation of application configuration based on different environments (e.g., development, testing, production). 26 | - **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`). 27 | 28 | ### 4. **What configurations can be managed within a Spring Boot profile?** 29 | 30 | **Answer:** 31 | - **Data Source Configurations**: Define different database configurations for various environments. 32 | - **Service Endpoints**: Configure different API endpoints or service URLs based on the active profile. 33 | - **Logging Levels**: Set different logging levels or loggers for different environments. 34 | - **Security Settings**: Adjust security configurations such as authentication mechanisms or access controls. 35 | 36 | ### 5. **What are the advantages of using microservices architecture?** 37 | 38 | **Answer:** 39 | - **Scalability**: Individual components can be scaled independently. 40 | - **Flexibility**: Different services can be developed, deployed, and maintained separately. 41 | - **Resilience**: Failure in one service does not necessarily impact others. 42 | - **Technology Agnostic**: Different services can use different technologies or frameworks. 43 | - **Faster Time to Market**: Smaller teams can develop and deploy services more quickly. 44 | 45 | ### 6. **How do you integrate microservices in a project?** 46 | 47 | **Answer:** 48 | - **API Gateway**: Use an API gateway to handle requests and route them to the appropriate microservices. 49 | - **Service Registry**: Use tools like Eureka for service discovery and registration. 50 | - **Inter-Service Communication**: Implement communication between services using REST APIs, messaging queues, or gRPC. 51 | - **Configuration Management**: Use tools like Spring Cloud Config to manage configuration centrally. 52 | - **Monitoring and Logging**: Implement centralized logging and monitoring using tools like ELK stack or Prometheus. 53 | 54 | ### 7. **What is a Eureka Server, and how is it used in microservices?** 55 | 56 | **Answer:** 57 | - **Eureka Server**: A service discovery tool provided by Netflix, part of the Spring Cloud ecosystem. 58 | - **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. 59 | 60 | ### 8. **Can you explain the internal working of a HashMap in Java?** 61 | 62 | **Answer:** 63 | - **HashMap** stores key-value pairs. Internally, it uses an array of buckets, where each bucket is a linked list or a tree (if many entries hash to the same bucket). 64 | - **Hashing**: Keys are hashed to determine their bucket location. 65 | - **Collision Resolution**: If multiple keys hash to the same bucket, they are stored in a linked list or tree structure within that bucket. 66 | - **Resizing**: When the number of entries exceeds a threshold, the HashMap resizes and rehashes all entries. 67 | 68 | ### 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?** 69 | 70 | **Answer:** 71 | ```java 72 | import java.util.Arrays; 73 | import java.util.List; 74 | import java.util.stream.Collectors; 75 | import java.util.stream.IntStream; 76 | 77 | public class MissingNumbers { 78 | public static void main(String[] args) { 79 | List numbers = Arrays.asList(1, 2, 4, 6, 8, 9); 80 | int min = 1; 81 | int max = 9; 82 | 83 | List missingNumbers = IntStream.rangeClosed(min, max) 84 | .filter(n -> !numbers.contains(n)) 85 | .boxed() 86 | .collect(Collectors.toList()); 87 | 88 | System.out.println("Missing numbers: " + missingNumbers); 89 | } 90 | } 91 | ``` 92 | 93 | ### 10. **Given a list of strings ["blue", "green", "red", "pink"], how would you find the longest string and print its length using Java Streams?** 94 | 95 | **Answer:** 96 | ```java 97 | import java.util.Arrays; 98 | import java.util.List; 99 | import java.util.Comparator; 100 | 101 | public class LongestStringLength { 102 | public static void main(String[] args) { 103 | List strings = Arrays.asList("blue", "green", "red", "pink"); 104 | 105 | int maxLength = strings.stream() 106 | .sorted(Comparator.comparingInt(String::length).reversed()) 107 | .findFirst() 108 | .map(String::length) 109 | .orElse(0); 110 | 111 | System.out.println("Length of the longest string: " + maxLength); 112 | } 113 | } 114 | ``` 115 | -------------------------------------------------------------------------------- /IBS Software (walk_in)/IBS.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## **First Round: Pen and Paper (Coding Question)** 4 | 5 | ### **Question 1:** 6 | Given an array, find the number of target element pairs whose sum equals the target value. 7 | 8 | #### **Example** 9 | **Input:** 10 | ``` 11 | arr = [1,3,4,5,1,5,0,-1] 12 | target = 4 13 | ``` 14 | **Pairs:** (1,3), (4,0), (5,-1) → **Output: 3** 15 | 16 | #### **Answer (Java)** 17 | ```java 18 | import java.util.*; 19 | 20 | public class TargetPairCount { 21 | public static int countPairs(int[] arr, int target) { 22 | Set seen = new HashSet<>(); 23 | int count = 0; 24 | for (int num : arr) { 25 | if (seen.contains(target - num)) { 26 | count++; 27 | } 28 | seen.add(num); 29 | } 30 | return count; 31 | } 32 | 33 | public static void main(String[] args) { 34 | int[] arr = {1, 3, 4, 5, 1, 5, 0, -1}; 35 | int target = 4; 36 | System.out.println(countPairs(arr, target)); // Output: 3 37 | } 38 | } 39 | ``` 40 | 41 | --- 42 | 43 | ## **Second Round: Technical Interview** 44 | 45 | ### **Question 2:** 46 | Given an array, replace each element with the **next largest element**. If no larger element exists, replace it with -1. 47 | 48 | #### **Example** 49 | **Input:** `[1,2,0,4,11,0,1]` 50 | **Output:** `[2,4,4,11,-1,1,-1]` 51 | 52 | #### **Answer (Java)** 53 | ```java 54 | import java.util.*; 55 | 56 | public class NextGreaterElement { 57 | public static int[] nextGreater(int[] arr) { 58 | int n = arr.length; 59 | int[] result = new int[n]; 60 | Stack stack = new Stack<>(); 61 | 62 | for (int i = n - 1; i >= 0; i--) { 63 | while (!stack.isEmpty() && stack.peek() <= arr[i]) { 64 | stack.pop(); 65 | } 66 | result[i] = stack.isEmpty() ? -1 : stack.peek(); 67 | stack.push(arr[i]); 68 | } 69 | return result; 70 | } 71 | 72 | public static void main(String[] args) { 73 | int[] arr = {1, 2, 0, 4, 11, 0, 1}; 74 | System.out.println(Arrays.toString(nextGreater(arr))); // Output: [2,4,4,11,-1,1,-1] 75 | } 76 | } 77 | ``` 78 | 79 | ### **Database Questions** 80 | 1. **How can you optimize an SQL query for better performance?** 81 | - Use **indexes** on frequently searched columns. 82 | - Avoid `SELECT *` and fetch only required columns. 83 | - Use **JOINs efficiently** and avoid unnecessary subqueries. 84 | - Use **EXPLAIN PLAN** to analyze query execution. 85 | 86 | 2. **When should you use NoSQL instead of SQL?** 87 | - When working with **unstructured or semi-structured data**. 88 | - When **scalability** is more important than **ACID compliance**. 89 | - For real-time applications like chat apps and recommendation systems. 90 | 91 | 3. **What are the best indexing strategies for improving database performance?** 92 | - Use **B-Tree indexes** for range queries. 93 | - Use **Hash indexes** for exact lookups. 94 | - **Composite indexes** for multi-column searches. 95 | 96 | --- 97 | 98 | ## **Third Round: Technical Interview** 99 | 100 | ### **Question 3:** 101 | Given a list of strings, separate **palindromes** and **non-palindromes**, then **sort each group by length**. 102 | 103 | #### **Example** 104 | **Input:** `"hi oo how are your level comes"` 105 | **Output:** 106 | ``` 107 | Palindromes: [oo, level] 108 | Non-palindromes: [hi, how, comes, are your] (Sorted by length) 109 | ``` 110 | 111 | #### **Answer (Java - Single Stream Approach)** 112 | ```java 113 | import java.util.*; 114 | import java.util.stream.Collectors; 115 | 116 | public class PalindromeSort { 117 | public static void main(String[] args) { 118 | String input = "hi oo how are your level comes"; 119 | 120 | Map> result = Arrays.stream(input.split(" ")) 121 | .collect(Collectors.groupingBy( 122 | word -> word.equals(new StringBuilder(word).reverse().toString()) ? "Palindromes" : "Non-Palindromes", 123 | Collectors.collectingAndThen( 124 | Collectors.toList(), 125 | list -> list.stream() 126 | .sorted(Comparator.comparingInt(String::length)) 127 | .collect(Collectors.toList()) 128 | ) 129 | )); 130 | 131 | System.out.println(result); 132 | } 133 | } 134 | ``` 135 | 136 | ### **Database Question** 137 | - **Which Java Collection is best for this operation?** 138 | **Answer:** `LinkedHashMap>` (to maintain insertion order). 139 | 140 | --- 141 | 142 | ## **Fourth Round: Managerial Interview** 143 | 144 | ### **Question 4:** 145 | Why do we use `List` instead of `ArrayList` when declaring a variable? 146 | ```java 147 | List ans = new ArrayList<>(); 148 | ``` 149 | **Answer:** 150 | - `List` is an **interface** that provides flexibility to switch implementations (`ArrayList`, `LinkedList`, etc.). 151 | - Helps in writing **loosely coupled** and **maintainable** code. 152 | - If later a `LinkedList` or `Vector` is needed, only the object needs to change, **not the variable type**. 153 | 154 | ### **Behavioral Questions:** 155 | 1. **What are your strengths and weaknesses?** 156 | - Strengths: Problem-solving, adaptability, teamwork. 157 | - Weaknesses: Perfectionism (but working on prioritization). 158 | 159 | 2. **How do you learn new concepts?** 160 | - Hands-on practice, online courses, and contributing to open-source projects. 161 | 162 | 3. **Discussion about IBS Software projects.** 163 | - Be prepared to discuss **what you know about IBS Software** and their work in the airline industry. 164 | 165 | --- 166 | 167 | ## **Fifth Round: HR Interview** 168 | 169 | 1. **What is your expected package?** 170 | - Research the industry standard and **negotiate based on your experience**. 171 | 172 | 2. **How do you keep up with new technologies?** 173 | - Reading tech blogs, taking online courses, working on projects. 174 | 175 | 3. **Tell me about your college life and how you got your first job.** 176 | - Share an interesting story or highlight a key **learning experience**. 177 | 178 | --- 179 | 180 | ### **Final Tips for the Interview** 181 | ✔ **Write clean, efficient code** and be ready to explain it. 182 | ✔ **Prepare database optimization strategies** (SQL vs NoSQL). 183 | ✔ **Be confident in behavioral rounds** and talk about **real-life examples**. 184 | -------------------------------------------------------------------------------- /Hire Bridge Consultancy/HireBridgeConsultancy.md: -------------------------------------------------------------------------------- 1 | ### 1. **Explain your project briefly.** 2 | My project involves [describe your project here], utilizing technologies such as Spring Boot, React, microservices, and databases. The core functionality includes [key features], and I was responsible for [your role]. 3 | 4 | --- 5 | 6 | ### 2. **Given an array of integers and a number ‘sum’, print all pairs in the array whose sum equals ‘sum’.** 7 | ```java 8 | public class PairSum { 9 | public static void main(String[] args) { 10 | int[] arr = {1, 5, 7, -1, 5}; 11 | int exp = 6; 12 | Map map=new LinkedHashMap<>(); 13 | for(int i=0;i employeeMap = new HashMap<>(); 121 | employeeMap.put("John", new Employee("John")); 122 | employeeMap.put("Alice", new Employee("Alice")); 123 | // Ensure employee names are unique when inserting into the map. 124 | ``` 125 | 126 | --- 127 | 128 | ### 10. **How do you sort a list of employees based on employee names?** 129 | ```java 130 | List employees = new ArrayList<>(); 131 | employees.add(new Employee("John")); 132 | employees.add(new Employee("Alice")); 133 | 134 | employees.sort(Comparator.comparing(Employee::getName)); 135 | ``` 136 | 137 | --- 138 | 139 | ### 11. **How do you retrieve database data based on a particular page in Spring Boot?** 140 | You can use `Pageable` from Spring Data JPA to retrieve data based on pagination: 141 | ```java 142 | Pageable pageable = PageRequest.of(pageNumber, pageSize); 143 | Page employees = employeeRepository.findAll(pageable); 144 | ``` 145 | 146 | --- 147 | 148 | ### 12. **How do you write a query to get data for a specific page in a database?** 149 | ```sql 150 | SELECT * FROM employees LIMIT 10 OFFSET 20; 151 | ``` 152 | This will fetch 10 records starting from the 21st record (for pagination). 153 | 154 | --- 155 | 156 | ### 13. **How do you deploy your project?** 157 | - Build the project using `mvn clean install`. 158 | - Deploy the generated `.jar` or `.war` file to a server (Tomcat, cloud platform like AWS, or Kubernetes). 159 | - Use CI/CD pipelines for continuous deployment. 160 | 161 | --- 162 | 163 | ### 14. **How do you develop code using a Git repository?** 164 | 1. Clone the repository using `git clone`. 165 | 2. Create a new branch using `git checkout -b new-branch`. 166 | 3. Make changes and commit them using `git commit`. 167 | 4. Push the branch using `git push`. 168 | 5. Create a pull request to merge the changes. 169 | 170 | --- 171 | 172 | ### 15. **How do you handle the `application.properties` file in Spring Boot?** 173 | 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. 174 | 175 | --- 176 | 177 | ### 16. **Which cloud are you using for deployment?** 178 | I am using [AWS/Azure/GCP] for deployment, utilizing services like Elastic Beanstalk, EC2, or Kubernetes for application hosting. 179 | 180 | --- 181 | 182 | ### 17. **How do you communicate between two microservices?** 183 | Microservices can communicate using: 184 | - **REST APIs** (via HTTP requests). 185 | - **Message brokers** like RabbitMQ, Kafka for asynchronous communication. 186 | - **Feign clients** in Spring Boot for simplified HTTP client calls between services. 187 | -------------------------------------------------------------------------------- /Oracle/oracle.md: -------------------------------------------------------------------------------- 1 | ### Oracle Interview Questions 2 | 3 | ## First Round 4 | 1. **Self-introduction** 5 | 2. **Coding Questions** -HackerRank coding 6 | - Code 1-Find higest and lowest Rank of Students 7 | - Code 2- Vending machine Problem 8 | 3. **SQL Queries** 9 | - Query 1- joins Based Query 10 | - Query 2- Pivot Based Query 11 | 12 | ## Second Round 13 | 14 | 15 | ### 1. Self-introduction based on project 16 | - **Answer**: Provide a concise overview of your current project, highlighting key technologies used, your role, and major achievements. 17 | - 18 | ### 2. Write a Spring Boot project for login and register using JWT token through an online Java compiler 19 | - **Answer**: 20 | ```java 21 | @SpringBootApplication 22 | public class JwtDemoApplication { 23 | public static void main(String[] args) { 24 | SpringApplication.run(JwtDemoApplication.class, args); 25 | } 26 | } 27 | 28 | @RestController 29 | @RequestMapping("/auth") 30 | public class AuthController { 31 | 32 | @PostMapping("/register") 33 | public ResponseEntity register(@RequestBody User user) { 34 | // Code to save user 35 | return ResponseEntity.ok("User registered successfully"); 36 | } 37 | 38 | @PostMapping("/login") 39 | public ResponseEntity login(@RequestBody AuthRequest authRequest) { 40 | // Code to authenticate user and generate JWT 41 | return ResponseEntity.ok(new AuthResponse(jwtToken)); 42 | } 43 | } 44 | 45 | @Service 46 | public class JwtService { 47 | public String generateToken(UserDetails userDetails) { 48 | // Code to generate JWT 49 | } 50 | } 51 | ``` 52 | 53 | ### 3. How to handle when microservices fail 54 | - **Answer**: Use fallback mechanisms, retry policies, and circuit breakers to handle microservice failures. Implementing a circuit breaker pattern using libraries like Resilience4j helps isolate failing services and prevent cascading failures. 55 | 56 | ### 4. How to implement circuit breakers in microservices 57 | - **Answer**: Use Resilience4j to implement circuit breakers: 58 | ```java 59 | @Service 60 | public class MyService { 61 | 62 | @CircuitBreaker(name = "myService", fallbackMethod = "fallbackMethod") 63 | public String performOperation() { 64 | // Code that may fail 65 | } 66 | 67 | public String fallbackMethod(Throwable t) { 68 | return "Fallback response"; 69 | } 70 | } 71 | ``` 72 | 73 | ### 5. Write a program to sort a string array without using any sort method or inbuilt functions 74 | - **Answer**: 75 | ```java 76 | public class StringArraySort { 77 | public static void main(String[] args) { 78 | String[] arr = {"banana", "apple", "cherry"}; 79 | for (int i = 0; i < arr.length - 1; i++) { 80 | for (int j = i + 1; j < arr.length; j++) { 81 | if (compareStrings(arr[i], arr[j]) > 0) { 82 | String temp = arr[i]; 83 | arr[i] = arr[j]; 84 | arr[j] = temp; 85 | } 86 | } 87 | } 88 | for (String str : arr) { 89 | System.out.println(str); 90 | } 91 | } 92 | 93 | public static int compareStrings(String s1, String s2) { 94 | int len = Math.min(s1.length(), s2.length()); 95 | for (int i = 0; i < len; i++) { 96 | if (s1.charAt(i) != s2.charAt(i)) { 97 | return s1.charAt(i) - s2.charAt(i); 98 | } 99 | } 100 | return s1.length() - s2.length(); 101 | } 102 | } 103 | ``` 104 | 105 | ### 6. Internal working process of HashMap 106 | - **Answer**: HashMap works on the principle of hashing. It uses an array of buckets to store key-value pairs. The `hashCode()` method determines the bucket index. When collisions occur (i.e., multiple keys hash to the same index), they are stored in a linked list or tree structure within the bucket. When retrieving, the key's hash code and `equals()` method are used to find the correct value. 107 | 108 | ### 7. Scenario where overriding `hashCode` and `equals` is necessary in Java 109 | - **Answer**: When creating a custom object to be used as a key in a HashMap or other hash-based collections, you must override `hashCode` and `equals` to ensure correct behavior. For example: 110 | ```java 111 | public class Employee { 112 | private int id; 113 | private String name; 114 | 115 | @Override 116 | public boolean equals(Object o) { 117 | if (this == o) return true; 118 | if (o == null || getClass() != o.getClass()) return false; 119 | Employee employee = (Employee) o; 120 | return id == employee.id && Objects.equals(name, employee.name); 121 | } 122 | 123 | @Override 124 | public int hashCode() { 125 | return Objects.hash(id, name); 126 | } 127 | } 128 | ``` 129 | 130 | ### 8. Difference between HashMap and Hashtable 131 | - **Answer**: 132 | - **HashMap**: Non-synchronized, allows one null key and multiple null values, generally faster. 133 | - **Hashtable**: Synchronized, does not allow null keys or values, generally slower due to synchronization overhead. 134 | 135 | ### 9. Difference between synchronized and non-synchronized with real-time examples 136 | - **Answer**: 137 | - **Synchronized**: Thread-safe, ensures only one thread can access a resource at a time. Example: `Hashtable` is synchronized. 138 | - **Non-synchronized**: Not thread-safe, multiple threads can access resources simultaneously. Example: `HashMap` is non-synchronized. 139 | 140 | ### 10. Write a program to make a HashMap synchronized 141 | **Answer**: 142 | 143 | ```java 144 | import java.util.Collections; 145 | import java.util.HashMap; 146 | import java.util.Map; 147 | public class SyncHashMapExample { 148 | public static void main(String[] args) { 149 | Map map = new HashMap<>(); 150 | map.put("1", "One"); 151 | map.put("2", "Two"); 152 | Map syncMap = Collections.synchronizedMap(map); 153 | 154 | synchronized (syncMap) { 155 | for (Map.Entry entry : syncMap.entrySet()) { 156 | System.out.println(entry.getKey() + ": " + entry.getValue()); 157 | } 158 | } 159 | } 160 | } 161 | ``` 162 | 163 | ## Final Round 164 | 1. **Self-introduction** 165 | 2. **About qualification** 166 | 3. **About project** 167 | 4. **How you learned coding and family details** 168 | 5. **Which technology you know** 169 | 6. **If we offer you new technology, which technology would you choose?** 170 | 7. **In your developing project, which is your most struggling phase?** 171 | 8. **How did you overcome that?** 172 | ... **Etc...** 173 | -------------------------------------------------------------------------------- /ACL Digital (Paypal,Adobe)/Paypal-new Client.md: -------------------------------------------------------------------------------- 1 | # Techincal L1 2 | 3 | ### Self-Introduction 4 | Hello, my name is-----. I have 3 years of experience as a Java Full Stack Developer, specializing in Java, Spring Boot, Hibernate, Microservices, and ReactJS. I have worked on multiple projects, including customer registration services and banking applications, where I implemented secure transaction handling, API development, and front-end components. I am proficient in writing clean, testable code using JUnit, Mockito, and TDD principles. I am also experienced in deploying applications using cloud platforms. I am eager to leverage my skills to contribute to innovative solutions in my next role. 5 | 6 | --- 7 | 8 | ### Problem 1: Sorting an Array of {-1, 0, 1} in O(n) Time and O(1) Space 9 | #### **Problem Statement:** 10 | Given an array containing only three types of elements (`-1`, `0`, and `1`), sort it in O(n) time and O(1) space complexity. 11 | 12 | #### **Example:** 13 | **Input:** `[1, 0, -1, 0, 1]` 14 | **Output:** `[-1, 0, 0, 1, 1]` 15 | 16 | #### **Java Solution:** 17 | ```java 18 | public class SortThreeElements { 19 | public static void sortArray(int[] arr) { 20 | int low = 0, mid = 0, high = arr.length - 1; 21 | while (mid <= high) { 22 | if (arr[mid] == -1) { 23 | swap(arr, low, mid); 24 | low++; 25 | mid++; 26 | } else if (arr[mid] == 0) { 27 | mid++; 28 | } else { 29 | swap(arr, mid, high); 30 | high--; 31 | } 32 | } 33 | } 34 | 35 | private static void swap(int[] arr, int i, int j) { 36 | int temp = arr[i]; 37 | arr[i] = arr[j]; 38 | arr[j] = temp; 39 | } 40 | 41 | public static void main(String[] args) { 42 | int[] arr = {1, 0, -1, 0, 1}; 43 | sortArray(arr); 44 | System.out.println(Arrays.toString(arr)); 45 | } 46 | } 47 | ``` 48 | 49 | --- 50 | 51 | ### Problem 2: Quantitative Trading Firm Profit Calculation 52 | #### **Problem Statement:** 53 | A quantitative trading firm processes a list of events, each classified into one of four categories: 54 | 55 | 1. **BUY **: Buy `` shares of `` at market price. 56 | 2. **SELL **: Sell `` shares of `` at market price. 57 | 3. **CHANGE **: Change market price of `` by `` (can be positive or negative). 58 | 4. **QUERY**: Return the gross profit/loss from start to present. 59 | 60 | #### **Example:** 61 | **Input:** 62 | ``` 63 | ["BUY googl 20", "BUY aapl 50", "CHANGE googl 6", "QUERY", 64 | "SELL aapl 10", "CHANGE aapl -2", "QUERY"] 65 | ``` 66 | **Output:** 67 | ``` 68 | [120, 40] 69 | ``` 70 | 71 | #### **Java Solution:** 72 | ```java 73 | import java.io.*; 74 | import java.util.*; 75 | 76 | 77 | public class Solution { 78 | public static void main(String[] args) throws IOException { 79 | List events = Arrays.asList( 80 | "BUY googl 20", "BUY aapl 50", "CHANGE googl 6", 81 | "QUERY", "SELL aapl 10", "CHANGE aapl -2", "QUERY" 82 | ); 83 | 84 | List result = Result.getNetProfit(events); 85 | for (Long value : result) { 86 | System.out.println(value); 87 | } 88 | } 89 | } 90 | class Result { 91 | public static List getNetProfit(List events) { 92 | List ansList = new ArrayList<>(); 93 | Map portfolio = new HashMap<>(); 94 | long query = 0; 95 | 96 | for (String event : events) { 97 | String[] word = event.split(" "); 98 | String type = word[0]; 99 | 100 | if (type.equals("QUERY")) { 101 | ansList.add(query); 102 | } else { 103 | String company = word[1]; 104 | long unit = Long.parseLong(word[2]); 105 | 106 | switch (type) { 107 | case "BUY": 108 | portfolio.put(company, portfolio.getOrDefault(company, 0L) + unit); 109 | break; 110 | case "SELL": 111 | portfolio.put(company, portfolio.getOrDefault(company, 0L) - unit); 112 | break; 113 | case "CHANGE": 114 | if (portfolio.containsKey(company)) { 115 | query += portfolio.get(company) * unit; 116 | } 117 | break; 118 | } 119 | } 120 | } 121 | return ansList; 122 | } 123 | } 124 | ``` 125 | 126 | --- 127 | 128 | ### Problem 3: Another Trading Firm Example 129 | #### **Example:** 130 | **Input:** 131 | ``` 132 | 6 133 | BUY stock2 2 134 | BUY stock1 4 135 | CHANGE stock2 -8 136 | SELL stock1 2 137 | BUY stock3 3 138 | QUERY 139 | ``` 140 | **Output:** 141 | ``` 142 | -16 143 | ``` 144 | 145 | #### **Explanation:** 146 | - The price of `stock2` dropped by `-8`, affecting overall profit calculations. 147 | - Final profit/loss calculation after all events is `16`. 148 | 149 | 150 | # Techincal L2 151 | 152 | ### Self-Introduction 153 | Hello, my name is-----. I have 3 years of experience as a Java Full Stack Developer, specializing in Java, Spring Boot, Hibernate, Microservices, and ReactJS. I have worked on multiple projects, including customer registration services and banking applications, where I implemented secure transaction handling, API development, and front-end components. I am proficient in writing clean, testable code using JUnit, Mockito, and TDD principles. I am also experienced in deploying applications using cloud platforms. I am eager to leverage my skills to contribute to innovative solutions in my next role. 154 | 155 | --- 156 | ### **Question:** 157 | Find the minimum element in a rotated sorted array. 158 | A rotated sorted array is an array that was originally sorted in increasing order but then rotated at some pivot. Your task is to find the minimum element in the given array in O(log N) time complexity. 159 | 160 | #### **Example Input & Output:** 161 | ##### **Example 1:** 162 | **Input:** `[100,105,110,90,95]` 163 | **Output:** `90` 164 | 165 | ##### **Example 2:** 166 | **Input:** `[3,4,5,6,7,8,9,10,1,2]` 167 | **Output:** `1` 168 | 169 | ##### **Example 3:** 170 | **Input:** `[1,2,3,4,5,6,7,8,9,10]` 171 | **Output:** `1` 172 | 173 | ##### **Example 4:** 174 | **Input:** `[5,4,3,2,1]` 175 | **Output:** `1` 176 | 177 | --- 178 | 179 | ### **Java Code Solution:** 180 | 181 | ```java 182 | public class RotatedSortedArray { 183 | public static int findMin(int[] nums) { 184 | int left = 0, right = nums.length - 1; 185 | 186 | while (left < right) { 187 | int mid = left + (right - left) / 2; 188 | 189 | if (nums[mid] > nums[right]) { 190 | left = mid + 1; 191 | } else { 192 | right = mid; 193 | } 194 | } 195 | return nums[left]; 196 | } 197 | 198 | public static void main(String[] args) { 199 | int[][] testCases = { 200 | {100, 105, 110, 90, 95}, 201 | {3, 4, 5, 6, 7, 8, 9, 10, 1, 2}, 202 | {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 203 | {5, 4, 3, 2, 1} 204 | }; 205 | 206 | for (int[] testCase : testCases) { 207 | System.out.println("Minimum Element: " + findMin(testCase)); 208 | } 209 | } 210 | } 211 | ``` 212 | 213 | ### **Time Complexity:** 214 | - The solution uses **binary search**, making it **O(log N)**. 215 | -------------------------------------------------------------------------------- /Altimetrix/Altimetrix_Interview.md: -------------------------------------------------------------------------------- 1 | # Altimetrix Company 2 | 3 | 1. **Briefly explain the project you are currently working on.** 4 | - I am currently working on a microservices-based banking application that handles user registration and transaction data. The project uses Spring Boot for the backend, ReactJS for the frontend, and JPA for database interactions. We also implement security using Spring Security and JWT for authentication. 5 | 6 | 2. **What is Jenkins, and how do you use it in your project?** 7 | - Jenkins is a continuous integration/continuous deployment (CI/CD) tool used to automate the build and deployment process. In my project, Jenkins is configured to build the application automatically whenever there is a new commit to the Git repository. It also runs unit tests, integration tests, and deploys the application to the staging/production environment. 8 | 9 | 3. **Which tools do you use for monitoring purposes in Spring Boot?** 10 | - We use tools like **Prometheus** and **Grafana** for monitoring metrics, **Spring Boot Actuator** for exposing health and metrics endpoints, and **ELK Stack (Elasticsearch, Logstash, Kibana)** for logging and real-time monitoring. 11 | 12 | 4. **What Git commands do you commonly use in your project?** 13 | - Common Git commands include: 14 | - `git clone`: Clone a repository 15 | - `git pull`: Fetch and merge changes from the remote repository 16 | - `git push`: Push local changes to the remote repository 17 | - `git branch`: Create, list, or switch branches 18 | - `git checkout`: Switch between branches or restore files 19 | - `git merge`: Merge branches 20 | - `git commit -m "message"`: Commit changes with a message 21 | - `git stash`: Temporarily save changes not ready to commit 22 | 23 | 5. **What is Agile methodology? Explain your experience working in Agile.** 24 | - Agile methodology is an iterative approach to software development where requirements and solutions evolve through collaboration between cross-functional teams. I have experience working in Agile, specifically using **Scrum**. We follow sprints, conduct daily standups, sprint planning, and retrospective meetings. This approach allows us to quickly adapt to changes and deliver incremental updates. 25 | 26 | 6. **What is the difference between shallow copy and deep copy?** 27 | - **Shallow Copy**: Creates a new object, but copies the references to the same memory addresses of the objects inside. Changes to the internal objects affect both copies. 28 | - **Deep Copy**: Creates a new object and recursively copies all objects within it, meaning both the original and copied objects are independent of each other. 29 | 30 | 7. **How many ways can you create an object in Java?** 31 | - There are several ways to create an object in Java: 32 | 1. Using the `new` keyword. 33 | 2. Using reflection (`Class.newInstance()` or `Constructor.newInstance()`). 34 | 3. Using **clone()** (if the class implements `Cloneable`). 35 | 4. Using **serialization** and **deserialization**. 36 | 5. Using the `Factory` or `Builder` design pattern. 37 | 38 | 8. **Why is the main method in Java static?** 39 | - The main method is static because it can be called without creating an instance of the class. This allows the JVM to call it directly to start the program. 40 | 41 | 9. **What is a deadlock in Java?** 42 | - A deadlock occurs when two or more threads are blocked forever, waiting for each other to release a lock they need to proceed. Each thread holds a resource the other thread requires, leading to a cycle of dependency. 43 | 44 | 10. **How can we avoid deadlock in Java?** 45 | - To avoid deadlock: 46 | 1. Always acquire locks in a consistent order. 47 | 2. Use a **timeout** for acquiring locks. 48 | 3. Use fewer synchronized blocks or locks, and keep them as short as possible. 49 | 4. Use **lock hierarchy** or **deadlock detection algorithms**. 50 | 51 | 11. **Do you know any design patterns?** 52 | - Yes, I am familiar with several design patterns like **Singleton**, **Factory**, **Builder**, **Observer**, **Strategy**, and **Decorator**. 53 | 54 | 12. **What is the Factory Design Pattern?** 55 | - The **Factory Design Pattern** is a creational pattern that provides an interface for creating objects in a super class, but allows subclasses to alter the type of objects that will be created. It promotes loose coupling and is used when the object creation process involves some logic. 56 | 57 | 13. **Check if a given string containing brackets is balanced.** 58 | - Approach: Use a stack to track the open brackets and check for matching closing brackets. 59 | ```java 60 | public boolean isBalanced(String str) { 61 | Stack stack = new Stack<>(); 62 | for (char ch : str.toCharArray()) { 63 | if (ch == '(' || ch == '{' || ch == '[') { 64 | stack.push(ch); 65 | } else if (ch == ')' && (stack.isEmpty() || stack.pop() != '(')) { 66 | return false; 67 | } else if (ch == '}' && (stack.isEmpty() || stack.pop() != '{')) { 68 | return false; 69 | } else if (ch == ']' && (stack.isEmpty() || stack.pop() != '[')) { 70 | return false; 71 | } 72 | } 73 | return stack.isEmpty(); 74 | } 75 | ``` 76 | 77 | 14. **Find the most repeated IP address.** 78 | - Approach: Use a HashMap to count the occurrences of each IP. 79 | ```java 80 | public String findMostRepeatedIP(List logs) { 81 | Map ipCount = new HashMap<>(); 82 | for (String log : logs) { 83 | String ip = log.split(" ")[0]; 84 | ipCount.put(ip, ipCount.getOrDefault(ip, 0) + 1); 85 | } 86 | return Collections.max(ipCount.entrySet(), Map.Entry.comparingByValue()).getKey(); 87 | } 88 | ``` 89 | 90 | 15. **How do you communicate between two microservices?** 91 | - Communication between microservices can be done using **REST APIs** (synchronous) or **message brokers** like RabbitMQ or Kafka (asynchronous). REST APIs use HTTP requests, while message brokers allow communication through event-driven architecture. 92 | 93 | 16. **How do you secure communication between microservices?** 94 | - You can secure communication using: 95 | 1. **JWT** (JSON Web Tokens) for authentication and authorization. 96 | 2. **OAuth2** for secure access delegation. 97 | 3. **SSL/TLS** for encrypted communication. 98 | 4. **API Gateway** with security filters to control traffic and access. 99 | 100 | 17. **Have you worked with JPA (Java Persistence API)?** 101 | - Yes, I have used JPA in my projects for managing database entities, relationships, and queries using **Hibernate** as the JPA provider. I also work with annotations like `@Entity`, `@OneToMany`, `@ManyToOne`, and `@Query`. 102 | 103 | 18. **What is the N+1 select problem in JPA, and how do you handle it?** 104 | - 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: 105 | - **FetchType.LAZY** or **FetchType.EAGER**. 106 | - Using **JOIN FETCH** queries to load related entities in a single query. 107 | 108 | 19. **Have you worked on writing unit test cases? How do you approach it?** 109 | - 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. 110 | 111 | 20. **How do you mock private methods in unit testing?** 112 | - Private methods can be mocked using **PowerMock** along with Mockito, which allows for mocking private, static, and final methods. 113 | 114 | # Altimetrix Client L1 115 | ___soon 116 | -------------------------------------------------------------------------------- /ZOHO (walk_in)/zoho.md: -------------------------------------------------------------------------------- 1 | 2 | --- 3 | 4 | # **Zoho Interview:** 5 | 6 | ## **1st Round: Factorial Sum (Avoiding Repeated Calculations)** 7 | #### **Question:** 8 | Given a number, find the sum of the factorials of its digits without recalculating previously computed factorials. 9 | 10 | #### **Example:** 11 | **Input:** `145` 12 | **Output:** `1! + 4! + 5! = 1 + 24 + 120 = 145` 13 | 14 | #### **Optimized Java Solution:** 15 | ```java 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | public class FactorialSum { 20 | private static final Map factorialCache = new HashMap<>(); 21 | 22 | public static void main(String[] args) { 23 | int num = 145; 24 | System.out.println("Factorial Sum: " + factorialSum(num)); 25 | } 26 | 27 | public static int factorialSum(int num) { 28 | int sum = 0; 29 | while (num > 0) { 30 | int digit = num % 10; 31 | sum += factorial(digit); 32 | num /= 10; 33 | } 34 | return sum; 35 | } 36 | 37 | private static int factorial(int n) { 38 | if (!factorialCache.containsKey(n)) { 39 | factorialCache.put(n, (n == 0 || n == 1) ? 1 : n * factorial(n - 1)); 40 | } 41 | return factorialCache.get(n); 42 | } 43 | } 44 | ``` 45 | ✅ **Avoids recalculating factorial using a HashMap.** 46 | 47 | --- 48 | 49 | ## **2nd Round: Character Occurrence Sorting** 50 | #### **Question:** 51 | Given a string, count the occurrences of each character and sort by frequency in descending order. 52 | 53 | #### **Example:** 54 | **Input:** `"zoho"` 55 | **Output:** `"o:2, z:1, h:1"` 56 | 57 | #### **Optimized Java Solution:** 58 | ```java 59 | import java.util.*; 60 | import java.util.stream.Collectors; 61 | 62 | public class CharacterFrequencySort { 63 | public static void main(String[] args) { 64 | String input = "zoho"; 65 | System.out.println(sortByFrequency(input)); 66 | } 67 | 68 | public static String sortByFrequency(String s) { 69 | Map frequencyMap = s.chars() 70 | .mapToObj(c -> (char) c) 71 | .collect(Collectors.groupingBy(c -> c, Collectors.counting())); 72 | 73 | return frequencyMap.entrySet().stream() 74 | .sorted((a, b) -> Long.compare(b.getValue(), a.getValue())) // Sort by frequency descending 75 | .map(e -> e.getKey() + ":" + e.getValue()) 76 | .collect(Collectors.joining(", ")); 77 | } 78 | } 79 | ``` 80 | ✅ **Uses Java Streams for efficient sorting and counting.** 81 | 82 | --- 83 | 84 | ## **3rd Round: Matrix Rotation Validation** 85 | #### **Question:** 86 | Check if a given matrix is a rotated version of itself. 87 | 88 | #### **Example:** 89 | **Valid Rotation:** 90 | ```text 91 | [ 92 | [1,2,3] 93 | [3,1,2] 94 | [2,3,1] 95 | ] 96 | ``` 97 | **Invalid Rotation:** 98 | ```text 99 | [ 100 | [1,2,3] 101 | [3,1,2] 102 | [1,2,3] 103 | ] 104 | ``` 105 | 106 | #### **Optimized Java Solution:** 107 | ```java 108 | import java.util.Arrays; 109 | 110 | public class MatrixRotation { 111 | public static void main(String[] args) { 112 | int[][] matrix1 = { 113 | {1, 2, 3}, 114 | {3, 1, 2}, 115 | {2, 3, 1} 116 | }; 117 | 118 | int[][] matrix2 = { 119 | {1, 2, 3}, 120 | {3, 1, 2}, 121 | {1, 2, 3} 122 | }; 123 | 124 | System.out.println(isRotatedMatrix(matrix1)); // true 125 | System.out.println(isRotatedMatrix(matrix2)); // false 126 | } 127 | 128 | public static boolean isRotatedMatrix(int[][] matrix) { 129 | int n = matrix.length; 130 | for (int i = 1; i < n; i++) { 131 | if (!Arrays.equals(matrix[i], rotateRow(matrix[i - 1]))) { 132 | return false; 133 | } 134 | } 135 | return true; 136 | } 137 | 138 | private static int[] rotateRow(int[] row) { 139 | int n = row.length; 140 | int[] rotated = new int[n]; 141 | System.arraycopy(row, 1, rotated, 0, n - 1); 142 | rotated[n - 1] = row[0]; 143 | return rotated; 144 | } 145 | } 146 | ``` 147 | ✅ **Checks each row’s rotation efficiently.** 148 | 149 | --- 150 | 151 | ## **4th Round: Cipher Text Encryption** 152 | #### **Question:** 153 | Encrypt a given string by shifting characters forward based on a given number. 154 | 155 | #### **Example:** 156 | **Input:** `("zoho", 2)` 157 | **Output:** `"bqjq"` 158 | 159 | --- 160 | 161 | ### **Optimized Java Solution:** 162 | ```java 163 | public class CipherText { 164 | public static void main(String[] args) { 165 | String input = "zoho"; 166 | int shift = 2; 167 | System.out.println(encrypt(input, shift)); 168 | } 169 | 170 | public static String encrypt(String text, int shift) { 171 | StringBuilder encrypted = new StringBuilder(); 172 | 173 | for (char ch : text.toCharArray()) { 174 | if (Character.isLetter(ch)) { 175 | char base = Character.isUpperCase(ch) ? 'A' : 'a'; 176 | encrypted.append((char) ((ch - base + shift) % 26 + base)); 177 | } else { 178 | encrypted.append(ch); 179 | } 180 | } 181 | return encrypted.toString(); 182 | } 183 | } 184 | ``` 185 | --- 186 | 187 | ## **5th Round: Zig-Zag String Transformation** 188 | #### **Question:** 189 | Given a string and number of rows, convert it into a Zig-Zag pattern. 190 | 191 | #### **Example:** 192 | **Input:** `"PAYPALISHIRING"`, `Rows = 3` 193 | **Output:** `"PAHNAPLSIIGYIR"` 194 | 195 | #### **Optimized Java Solution:** 196 | ```java 197 | public class ZigZagConversion { 198 | public static void main(String[] args) { 199 | String s = "PAYPALISHIRING"; 200 | int numRows = 3; 201 | System.out.println(convertZigZag(s, numRows)); 202 | } 203 | 204 | public static String convertZigZag(String s, int numRows) { 205 | if (numRows == 1) return s; 206 | 207 | StringBuilder[] rows = new StringBuilder[numRows]; 208 | for (int i = 0; i < numRows; i++) { 209 | rows[i] = new StringBuilder(); 210 | } 211 | 212 | int i = 0, step = 1; 213 | for (char c : s.toCharArray()) { 214 | rows[i].append(c); 215 | if (i == 0) step = 1; 216 | if (i == numRows - 1) step = -1; 217 | i += step; 218 | } 219 | 220 | return Arrays.stream(rows).map(StringBuilder::toString).collect(Collectors.joining()); 221 | } 222 | } 223 | ``` 224 | ✅ **Uses an efficient approach with `StringBuilder` arrays.** 225 | 226 | --- 227 | 228 | ## **6th Round: Database Questions** 229 | 230 | ### **1. Full Stack Application Data Flow** 231 | Explain data flow from frontend to backend and database. 232 | 233 | ### **2. SQL Queries for Employee Table** 234 | Example: 235 | ```sql 236 | SELECT * FROM employees WHERE department = 'HR'; 237 | ``` 238 | 239 | ### **3. Fetching Data from Multiple Tables** 240 | **Example Using JOIN:** 241 | ```sql 242 | SELECT e.name, d.department_name 243 | FROM employees e 244 | JOIN departments d ON e.department_id = d.id; 245 | ``` 246 | 247 | ### **4. Primary Key vs Foreign Key** 248 | - **Primary Key**: Unique identifier in a table. 249 | - **Foreign Key**: References another table’s primary key. 250 | 251 | ### **5. Types of Joins with Example** 252 | ```sql 253 | -- INNER JOIN 254 | SELECT e.name, d.department_name 255 | FROM employees e 256 | INNER JOIN departments d ON e.department_id = d.id; 257 | 258 | -- LEFT JOIN 259 | SELECT e.name, d.department_name 260 | FROM employees e 261 | LEFT JOIN departments d ON e.department_id = d.id; 262 | ``` 263 | 264 | ### **6. Subqueries vs Joins** 265 | - **Joins** are used for merging tables. 266 | - **Subqueries** are nested queries. 267 | 268 | ✅ **Database concepts covered efficiently.** 269 | 270 | --- 271 | - **Expected Package** discussion. 272 | - **How do you keep up with new technologies?** 273 | - **College life & how you got your first job.** 274 | 275 | -------------------------------------------------------------------------------- /HCL/hcl.md: -------------------------------------------------------------------------------- 1 | 1. **What are the main features introduced in Java 8?** 2 | - Lambda Expressions 3 | - Functional Interfaces 4 | - Streams API 5 | - Default Methods in Interfaces 6 | - Optional Class 7 | - New Date and Time API (java.time) 8 | - Nashorn JavaScript Engine 9 | - Method References 10 | 11 | 2. **What are the key differences between an interface and an abstract class in Java?** 12 | - 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. 13 | - A class can implement multiple interfaces but can inherit from only one abstract class. 14 | - Interfaces cannot have instance variables, while abstract classes can. 15 | - Interfaces provide a form of multiple inheritance; abstract classes provide a form of single inheritance. 16 | 17 | 3. **How do you implement Executor Services in Java?** 18 | ```java 19 | import java.util.concurrent.ExecutorService; 20 | import java.util.concurrent.Executors; 21 | 22 | public class ExecutorServiceExample { 23 | public static void main(String[] args) { 24 | ExecutorService executor = Executors.newFixedThreadPool(5); 25 | 26 | for (int i = 0; i < 10; i++) { 27 | Runnable worker = new WorkerThread("" + i); 28 | executor.execute(worker); 29 | } 30 | executor.shutdown(); 31 | while (!executor.isTerminated()) { 32 | } 33 | System.out.println("Finished all threads"); 34 | } 35 | } 36 | 37 | class WorkerThread implements Runnable { 38 | private String command; 39 | 40 | public WorkerThread(String s) { 41 | this.command = s; 42 | } 43 | 44 | @Override 45 | public void run() { 46 | System.out.println(Thread.currentThread().getName() + " Start. Command = " + command); 47 | processCommand(); 48 | System.out.println(Thread.currentThread().getName() + " End."); 49 | } 50 | 51 | private void processCommand() { 52 | try { 53 | Thread.sleep(5000); 54 | } catch (InterruptedException e) { 55 | e.printStackTrace(); 56 | } 57 | } 58 | } 59 | ``` 60 | 61 | 4. **Which databases have you used in your projects, and what was your experience with them?** 62 | - **MySQL:** Used for web applications; strong support for transactions and data integrity. 63 | - **PostgreSQL:** Preferred for complex queries and large datasets; excellent support for JSON data types and extensions. 64 | - **MongoDB:** Utilized for handling unstructured data and fast prototyping; great for horizontal scaling. 65 | - **Oracle:** Employed in enterprise-level applications requiring robust security and advanced features. 66 | 67 | 5. **How can you declare and use functional programming constructs in Java?** 68 | ```java 69 | // Lambda Expression 70 | List names = Arrays.asList("John", "Jane", "Jack"); 71 | names.forEach(name -> System.out.println(name)); 72 | 73 | // Functional Interface Example 74 | @FunctionalInterface 75 | interface MathOperation { 76 | int operation(int a, int b); 77 | } 78 | 79 | MathOperation addition = (a, b) -> a + b; 80 | System.out.println("10 + 5 = " + addition.operation(10, 5)); 81 | ``` 82 | 83 | 6. **What are the differences between `@RestController` and `@Controller` in Spring Boot?** 84 | - `@RestController` is a combination of `@Controller` and `@ResponseBody`. It automatically serializes return objects into JSON or XML and writes them into the HTTP response. 85 | - `@Controller` is used to mark classes as Spring MVC controllers. Methods in these classes typically return view names and are resolved by view resolvers. 86 | 87 | 7. **How do you schedule tasks in Spring Boot?** 88 | ```java 89 | import org.springframework.scheduling.annotation.Scheduled; 90 | import org.springframework.stereotype.Component; 91 | 92 | @Component 93 | public class ScheduledTasks { 94 | 95 | @Scheduled(fixedRate = 5000) 96 | public void reportCurrentTime() { 97 | System.out.println("The time is now " + new Date()); 98 | } 99 | } 100 | ``` 101 | 102 | 8. **How is Jenkins integrated with Spring Boot? What dependencies or configuration files are needed?** 103 | - **Jenkinsfile:** 104 | ```groovy 105 | pipeline { 106 | agent any 107 | stages { 108 | stage('Build') { 109 | steps { 110 | sh './mvnw clean package' 111 | } 112 | } 113 | stage('Test') { 114 | steps { 115 | sh './mvnw test' 116 | } 117 | } 118 | stage('Deploy') { 119 | steps { 120 | sh 'docker build -t spring-boot-app .' 121 | sh 'docker run -d -p 8080:8080 spring-boot-app' 122 | } 123 | } 124 | } 125 | } 126 | ``` 127 | - **Dependencies:** 128 | - Jenkins server 129 | - Maven or Gradle for build automation 130 | - Docker for containerization (if deploying with Docker) 131 | 132 | 9. **What is the difference between `HashMap` and `ConcurrentHashMap` in Java?** 133 | - `HashMap` is not synchronized and is not thread-safe. 134 | - `ConcurrentHashMap` is thread-safe and allows concurrent access to its segments. 135 | 136 | 10. **What are the key classes and interfaces in the `java.util.concurrent` package?** 137 | - **Key Classes:** `ExecutorService`, `ScheduledExecutorService`, `Future`, `CountDownLatch`, `CyclicBarrier`, `Semaphore`, `ConcurrentHashMap`, `CopyOnWriteArrayList` 138 | - **Key Interfaces:** `Executor`, `Callable`, `Future`, `BlockingQueue` 139 | 140 | 11. **Describe the collections framework in Java.** 141 | - **Core Interfaces:** `Collection`, `List`, `Set`, `Queue`, `Map` 142 | - **Implementations:** `ArrayList`, `LinkedList`, `HashSet`, `TreeSet`, `PriorityQueue`, `HashMap`, `TreeMap` 143 | - **Utilities:** `Collections`, `Arrays` 144 | 145 | 12. **How do you use profiles in Spring Boot?** 146 | ```yaml 147 | # application.yml 148 | spring: 149 | profiles: 150 | active: dev 151 | --- 152 | # application-dev.yml 153 | server: 154 | port: 8081 155 | --- 156 | # application-prod.yml 157 | server: 158 | port: 8082 159 | ``` 160 | 161 | 13. **If both `application.properties` and `application.yaml` are present in a Spring Boot application, which one takes precedence?** 162 | - `application.properties` takes precedence over `application.yaml`. 163 | 164 | 14. **Explain the `@Autowired` annotation in Spring.** 165 | - `@Autowired` is used for automatic dependency injection. Spring's dependency injection mechanism uses this annotation to resolve and inject collaborating beans into the desired bean. 166 | 167 | 15. **Using a lambda expression, write a Java program to sum the elements of an array.** 168 | ```java 169 | import java.util.Arrays; 170 | public class SumArray { 171 | public static void main(String[] args) { 172 | int[] array = {1, 2, 3, 4, 5}; 173 | 174 | // Using a lambda expression with Stream API 175 | int sum = Arrays.stream(array) 176 | .reduce(0, (a, b) -> a + b); 177 | 178 | System.out.println("Sum: " + sum); 179 | } 180 | } 181 | ``` 182 | 183 | 16. **Write a Java program to generate all permutations of an array using lambda expressions.** 184 | ```java 185 | import java.util.ArrayList; 186 | import java.util.List; 187 | import java.util.stream.Collectors; 188 | import java.util.stream.IntStream; 189 | 190 | public class Permutations { 191 | public static void main(String[] args) { 192 | int[] array = {1, 2, 3}; 193 | List> result = permute(array); 194 | result.forEach(System.out::println); 195 | } 196 | 197 | public static List> permute(int[] nums) { 198 | return permute(IntStream.range(0, nums.length).boxed().collect(Collectors.toList()), nums); 199 | } 200 | 201 | private static List> permute(List indices, int[] nums) { 202 | if (indices.isEmpty()) { 203 | List perm = new ArrayList<>(); 204 | for (int num : nums) { 205 | perm.add(num); 206 | } 207 | return List.of(perm); 208 | } 209 | 210 | return indices.stream() 211 | .flatMap(i -> { 212 | List remaining = new ArrayList<>(indices); 213 | remaining.remove(Integer.valueOf(i)); 214 | return permute(remaining, swap(nums, i)).stream(); 215 | }) 216 | .collect(Collectors.toList()); 217 | } 218 | 219 | private static int[] swap(int[] array, int i) { 220 | int[] newArray = array.clone(); 221 | int temp = newArray[i]; 222 | newArray[i] = newArray[0]; 223 | newArray[0] = temp; 224 | return newArray; 225 | } 226 | } 227 | ``` 228 | **Etc...** 229 | -------------------------------------------------------------------------------- /Tech Mahindra/TechMahindra.md: -------------------------------------------------------------------------------- 1 | 2 | # Tech Mahindra 3 | ## Java Questions 4 | 5 | ### 1. What are the new features in Java 8? 6 | - Lambda Expressions 7 | - Stream API 8 | - Optional Class 9 | - Default Methods in Interfaces 10 | - Method References 11 | - New Date and Time API (java.time) 12 | - Nashorn JavaScript Engine 13 | 14 | ### 2. What is batch processing in Java? 15 | - Batch processing refers to executing a series of jobs without manual intervention. It can be implemented using frameworks like Spring Batch, which provides reusable functions that process large volumes of data. 16 | 17 | ### 3. What is job scheduling in Java? 18 | - Job scheduling involves setting up tasks to run at specified times or intervals. Java provides APIs like `java.util.Timer` and `java.util.concurrent.ScheduledExecutorService`. Additionally, libraries like Quartz Scheduler offer more advanced features. 19 | 20 | ### 4. What are the inbuilt Java functional interfaces? 21 | - `Predicate` 22 | - `Function` 23 | - `Supplier` 24 | - `Consumer` 25 | - `BiFunction` 26 | 27 | ### 5. What is the difference between an interface and a functional interface? 28 | - An interface can have any number of abstract methods. 29 | - A functional interface has exactly one abstract method and can have any number of default or static methods. It is used as the assignment target for lambda expressions. 30 | 31 | ### 6. Explain the Singleton design pattern. 32 | - The Singleton design pattern ensures that a class has only one instance and provides a global point of access to it. It is typically implemented by making the constructor private and providing a static method that returns the instance. 33 | 34 | ### 7. How can you break the Singleton design pattern? 35 | - Using reflection to call the private constructor. 36 | - Using serialization and deserialization. 37 | - Using cloning. 38 | 39 | ### 8. What is a default method in Java and what is its use? 40 | - A default method in an interface provides a default implementation that can be overridden by implementing classes. It allows interfaces to evolve without breaking existing implementations. 41 | 42 | ### 9. How do you handle errors in Java? 43 | - Using try-catch blocks to catch and handle exceptions. 44 | - Using `throws` keyword to declare exceptions. 45 | - Using custom exception classes for specific error handling. 46 | 47 | ### 10. **How many types of exceptions are there in Java? 48 | - Checked exceptions (subclasses of `Exception` except `RuntimeException`) 49 | - Unchecked exceptions (subclasses of `RuntimeException`) 50 | - Errors (subclasses of `Error`) 51 | 52 | ### 11. Explain checked and unchecked exceptions. 53 | - Checked exceptions must be declared in a method or constructor's `throws` clause if they can be thrown by the execution of the method or constructor and propagated outside the method or constructor boundary. 54 | - Unchecked exceptions do not need to be declared in a `throws` clause and can be thrown at any time during the execution of the program. 55 | 56 | ### 12. What is the difference between shallow copy and deep copy? 57 | - 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. 58 | - Deep copy creates a new instance of each object, recursively copying all nested objects. 59 | 60 | ### 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? 61 | - 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. 62 | 63 | ### 14. What is serialization and deserialization? 64 | - Serialization is the process of converting an object into a byte stream for storage or transmission. 65 | - Deserialization is the process of converting a byte stream back into an object. 66 | 67 | 15. Implement a generic double linked list with a method to remove an element based on the index in Java. 68 | ```java 69 | public class DoublyLinkedList { 70 | class Node { 71 | T data; 72 | Node prev, next; 73 | 74 | Node(T data) { 75 | this.data = data; 76 | } 77 | } 78 | 79 | private Node head, tail; 80 | 81 | public void remove(int index) { 82 | if (index < 0) return; 83 | Node current = head; 84 | for (int i = 0; i < index && current != null; i++) { 85 | current = current.next; 86 | } 87 | if (current == null) return; 88 | 89 | if (current.prev != null) { 90 | current.prev.next = current.next; 91 | } else { 92 | head = current.next; 93 | } 94 | if (current.next != null) { 95 | current.next.prev = current.prev; 96 | } else { 97 | tail = current.prev; 98 | } 99 | } 100 | } 101 | ``` 102 | 103 | ### 16. Given two arrays, combine them into a single sorted array. 104 | ```java 105 | int[] solution(int[] list1, int[] list2) { 106 | 107 | int i = 0, j = 0, a = list1.length - 1, b = list2.length - 1; 108 | int[] ans = new int[a+1 + b+1]; 109 | int k = 0; 110 | while (i <= a || j <= b) { 111 | if (i <= a && j <= b) { 112 | if (list1[i] <= list2[j]) { 113 | ans[k++] = list1[i++]; 114 | } else { 115 | ans[k++] = list2[j++]; 116 | } 117 | } else if (i <= a) { 118 | ans[k++] = list1[i++]; 119 | } else if (j <= b) { 120 | ans[k++] = list2[j++]; 121 | } 122 | } 123 | return ans; 124 | } 125 | 126 | ``` 127 | 128 | ### 17. Ladder array code in Java. 129 | ```java 130 | public void printLadderArray(int n) { 131 | int[][] ladder = new int[n][]; 132 | for (int i = 0; i < n; i++) { 133 | ladder[i] = new int[i + 1]; 134 | for (int j = 0; j < i + 1; j++) { 135 | ladder[i][j] = j + 1; 136 | } 137 | } 138 | for (int[] row : ladder) { 139 | System.out.println(Arrays.toString(row)); 140 | } 141 | } 142 | ``` 143 | 144 | ## Spring Boot Questions 145 | 146 | ### 1. What are profiles in Spring Boot? 147 | - Profiles in Spring Boot are a way to segregate parts of your application configuration and make it only available in certain environments. You can activate profiles using the `--spring.profiles.active` command-line argument or by setting the `spring.profiles.active` property in application properties. 148 | 149 | ### 2. How do you provide security in Spring Boot? 150 | - By using Spring Security, which provides authentication and authorization. Common methods include in-memory authentication, JDBC authentication, and LDAP authentication. 151 | 152 | ### 3. Explain the process of JWT token-based authentication. 153 | - The client sends a login request with credentials. 154 | - The server validates the credentials and generates a JWT token. 155 | - The client stores the token and includes it in the Authorization header of subsequent requests. 156 | - The server validates the token and processes the request if the token is valid. 157 | 158 | ### 4. What classes do you use in JWT token security? 159 | - `JwtTokenProvider` for token generation and validation. 160 | - `JwtAuthenticationFilter` to filter and validate requests. 161 | - `JwtAuthenticationEntryPoint` for handling authentication errors. 162 | 163 | ### 5. Why do you need the UserDetails class in Spring Security? 164 | - The `UserDetails` class represents a core user information. It provides necessary information like username, password, and authorities for authentication and authorization. 165 | 166 | ### 6. How do you handle exceptions in Spring Boot? 167 | - Using `@ControllerAdvice` and `@ExceptionHandler` to handle exceptions globally. 168 | - Customizing the error response by defining a `ResponseEntity` with appropriate status and message. 169 | 170 | ## Microservices Questions 171 | 172 | ### 1. What is fault tolerance in microservices? 173 | - Fault tolerance is the ability of a system to continue operating properly in the event of the failure of some of its components. This can be achieved using patterns like circuit breaker, retry mechanisms, and fallback methods. 174 | 175 | ### 2. What is logging and distributed tracing in microservices? 176 | - Logging involves recording information about the system's operation. Distributed tracing helps in tracking and analyzing requests as they propagate through a distributed system. Tools like ELK stack, Zipkin, and Jaeger are used for this purpose. 177 | 178 | ### 3. How do you communicate between one microservice and another microservice? 179 | - Using REST APIs over HTTP. 180 | - Using messaging queues like RabbitMQ or Kafka. 181 | - Using gRPC for efficient communication. 182 | 183 | ### 4. How do you limit requests in microservices? 184 | - Using rate limiting techniques, such as token bucket algorithm or leaky bucket algorithm. 185 | - Implementing API gateway tools like Netflix Zuul or Spring Cloud Gateway to enforce rate limiting. 186 | 187 | ### 5. What is a Kafka server? 188 | - Kafka is a distributed event streaming platform capable of handling high throughput and low-latency data streams. It is used for building real-time data pipelines and streaming applications. 189 | 190 | ### 6. Explain Jenkins and its use in microservices. 191 | - Jenkins is a continuous integration and continuous delivery tool. It automates the building, testing, and deploying of applications. In microservices, Jenkins can manage the pipelines for each microservice, ensuring that changes are integrated and deployed smoothly. 192 | -------------------------------------------------------------------------------- /TCS/TCS.md: -------------------------------------------------------------------------------- 1 | # Telepone Interview 2 | 3 | --- 4 | 5 | ### **Java 8 & Streams:** 6 | 7 | 1. **How do Java 8 Futures work?** 8 | **Answer:** 9 | Java 8 `Future` represents the result of an asynchronous computation. You can use `CompletableFuture` for non-blocking asynchronous tasks. 10 | **Example:** 11 | ```java 12 | import java.util.concurrent.*; 13 | 14 | public class FutureExample { 15 | public static void main(String[] args) throws ExecutionException, InterruptedException { 16 | ExecutorService executor = Executors.newSingleThreadExecutor(); 17 | Future future = executor.submit(() -> { 18 | Thread.sleep(2000); // Simulate long computation 19 | return 123; 20 | }); 21 | System.out.println("Result: " + future.get()); // Blocks until the result is available 22 | executor.shutdown(); 23 | } 24 | } 25 | ``` 26 | 27 | 2. **What is the difference between `parallel` and `parallelStream` in Java Streams?** 28 | **Answer:** 29 | `parallel` is a method available on a collection, while `parallelStream` is a method on the `Stream` interface. Both allow parallel processing of data but `parallelStream` is more convenient for stream-based operations. 30 | **Example:** 31 | ```java 32 | List numbers = Arrays.asList(1, 2, 3, 4, 5); 33 | 34 | // Using parallelStream 35 | numbers.parallelStream().forEach(num -> System.out.println(num + " - " + Thread.currentThread().getName())); 36 | 37 | // Using parallel (with forEach) 38 | numbers.forEach(num -> System.out.println(num + " - " + Thread.currentThread().getName())); 39 | ``` 40 | 41 | 3. **You have two lists: one to find even numbers and one to find odd numbers. How would you solve this using parallel streams?** 42 | **Answer:** 43 | We can use `parallelStream` to process both lists in parallel and then combine the results. 44 | **Example:** 45 | ```java 46 | List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); 47 | 48 | List evens = numbers.parallelStream() 49 | .filter(num -> num % 2 == 0) 50 | .collect(Collectors.toList()); 51 | List odds = numbers.parallelStream() 52 | .filter(num -> num % 2 != 0) 53 | .collect(Collectors.toList()); 54 | 55 | System.out.println("Even numbers: " + evens); 56 | System.out.println("Odd numbers: " + odds); 57 | ``` 58 | 59 | 4. **Can we implement a method in an interface?** 60 | **Answer:** 61 | Yes, starting from Java 8, interfaces can have default and static methods, which can contain a method body. 62 | **Example:** 63 | ```java 64 | interface MyInterface { 65 | default void printMessage() { 66 | System.out.println("Hello from interface!"); 67 | } 68 | } 69 | ``` 70 | 71 | 5. **What loads first: static block or static method, and why? Why doesn't the `main` method load first, even though it's static?** 72 | **Answer:** 73 | The static block is executed first, before the `main` method, because it is used to initialize the class. The `main` method is executed when the class is invoked by the JVM. 74 | **Example:** 75 | ```java 76 | class Test { 77 | static { 78 | System.out.println("Static block executed"); 79 | } 80 | public static void main(String[] args) { 81 | System.out.println("Main method executed"); 82 | } 83 | } 84 | ``` 85 | 86 | --- 87 | 88 | ### **Microservices & Exception Handling:** 89 | 90 | 1. **How should we handle exceptions in microservices, especially with so many services?** 91 | **Answer:** 92 | We can handle exceptions globally using `@ControllerAdvice` or by using a centralized logging service like ELK stack (Elasticsearch, Logstash, Kibana). 93 | **Example:** 94 | ```java 95 | @ControllerAdvice 96 | public class GlobalExceptionHandler { 97 | @ExceptionHandler(ResourceNotFoundException.class) 98 | public ResponseEntity handleResourceNotFound(ResourceNotFoundException ex) { 99 | return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND); 100 | } 101 | } 102 | ``` 103 | 104 | 2. **What is the difference between `@ControllerAdvice` and `@ExceptionHandler`?** 105 | **Answer:** 106 | `@ControllerAdvice` is a global exception handler for controllers, whereas `@ExceptionHandler` handles exceptions for a specific controller or method. 107 | **Example:** 108 | ```java 109 | @ControllerAdvice 110 | public class GlobalExceptionHandler { 111 | @ExceptionHandler(Exception.class) 112 | public ResponseEntity handleGlobalException(Exception ex) { 113 | return new ResponseEntity<>("Global exception occurred", HttpStatus.INTERNAL_SERVER_ERROR); 114 | } 115 | } 116 | ``` 117 | 118 | 3. **What is the difference between global exceptions and normal exceptions?** 119 | **Answer:** 120 | Global exceptions are handled globally across all controllers (using `@ControllerAdvice`), while normal exceptions are handled within the specific controller method using `@ExceptionHandler`. 121 | 122 | 4. **If two APIs are there and one fails, how should we know the API failed?** 123 | **Answer:** 124 | You can check the HTTP status code. If one API fails, the status code will be in the 4xx or 5xx range, which indicates a failure. 125 | **Example:** 126 | ```java 127 | ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, request, String.class); 128 | if (response.getStatusCode().is4xxClientError() || response.getStatusCode().is5xxServerError()) { 129 | System.out.println("API call failed"); 130 | } 131 | ``` 132 | 133 | 5. **If one service calls another service and the second service fails, how should we handle it? Explain with code.** 134 | **Answer:** 135 | Use a retry mechanism, circuit breakers (e.g., using Spring Cloud Circuit Breaker), or fallback methods. 136 | **Example:** 137 | ```java 138 | @CircuitBreaker(fallbackMethod = "fallbackMethod") 139 | public String callService() { 140 | return restTemplate.getForObject("http://service-url", String.class); 141 | } 142 | 143 | public String fallbackMethod(Exception e) { 144 | return "Service unavailable"; 145 | } 146 | ``` 147 | 148 | 6. **What is fallback mechanism in microservices?** 149 | **Answer:** 150 | A fallback mechanism ensures that if a service fails, a default response or an alternative method is executed to handle the failure gracefully. This can be achieved using tools like Hystrix or Resilience4j. 151 | 152 | --- 153 | 154 | ### **Functional Interfaces & Annotations:** 155 | 156 | 1. **What is a marker interface? What is its use and why is it used?** 157 | **Answer:** 158 | A marker interface is an interface with no methods. It's used to signal to the JVM or a framework that a class has a specific property or behavior. 159 | **Example:** 160 | `Serializable` is a marker interface used to indicate that a class can be serialized. 161 | 162 | 2. **What is a functional interface and why is it used?** 163 | **Answer:** 164 | A functional interface is an interface with a single abstract method, used primarily for lambda expressions. 165 | **Example:** 166 | ```java 167 | @FunctionalInterface 168 | interface MyFunctionalInterface { 169 | void myMethod(); 170 | } 171 | ``` 172 | 173 | 3. **What is the difference between `@Configuration` and `@Component`?** 174 | **Answer:** 175 | `@Configuration` is used for classes that define Spring beans and contain bean definitions, whereas `@Component` is a generic annotation for Spring beans. 176 | **Example:** 177 | ```java 178 | @Configuration 179 | public class AppConfig { 180 | @Bean 181 | public MyBean myBean() { 182 | return new MyBean(); 183 | } 184 | } 185 | ``` 186 | 187 | 4. **What is the difference between `@Bean` and `@Configuration`?** 188 | **Answer:** 189 | `@Bean` is used to define a single bean, whereas `@Configuration` indicates that a class contains bean definitions. 190 | **Example:** 191 | `@Configuration` can contain multiple `@Bean` methods. 192 | 193 | 5. **Can we use `@Component` instead of `@Repository`?** 194 | **Answer:** 195 | Yes, `@Repository` is a specialization of `@Component` with additional behavior like exception translation. You can use `@Component` but `@Repository` is more semantically appropriate for persistence layers. 196 | 197 | --- 198 | 199 | ### **SQL:** 200 | 201 | 1. **How would you update the salary by 10% extra and 10% less in the same SQL query based on a condition?** 202 | **Answer:** 203 | ```sql 204 | UPDATE employees 205 | SET salary = CASE 206 | WHEN condition = 'increase' THEN salary * 1.10 207 | WHEN condition = 'decrease' THEN salary * 0.90 208 | ELSE salary 209 | END; 210 | ``` 211 | 212 | 2. **Can we use aggregate functions with `GROUP BY` in SQL?** 213 | **Answer:** 214 | Yes, aggregate functions like `SUM()`, `COUNT()`, `AVG()`, etc., can be used with `GROUP BY` to group the results by specific columns. 215 | **Example:** 216 | ```sql 217 | SELECT department, COUNT(*) 218 | FROM employees 219 | GROUP BY department; 220 | ``` 221 | 222 | 3. **What are aggregate functions in SQL?** 223 | **Answer:** 224 | Aggregate functions perform calculations on a set of values and return a single value. Examples include `COUNT()`, `SUM()`, `AVG()`, `MIN()`, and `MAX()`. 225 | 226 | 4. **How do we filter data using `GROUP BY` in SQL?** 227 | **Answer:** 228 | We can use the `HAVING` clause to filter the results after applying `GROUP BY`. 229 | **Example:** 230 | ```sql 231 | SELECT department, COUNT(*) 232 | FROM employees 233 | GROUP BY department 234 | HAVING COUNT(*) > 5; 235 | ``` 236 | 237 | --- 238 | -------------------------------------------------------------------------------- /Ford Motor/FordReference.md: -------------------------------------------------------------------------------- 1 | ## Assessment 2 | ### Spring Boot App - HackerRank Assessment 3 | ### 5 Multiple Choice Questions (MCQs) 4 | 5 | ## First Round Interview 6 | 7 | ### 1. Explain the concept of OOP (Object-Oriented Programming) in Java. 8 | - **Answer:** OOP in Java is a programming paradigm based on the concept of objects, which can contain data and code. The four main principles of OOP are encapsulation, inheritance, polymorphism, and abstraction. 9 | 10 | ### 2. What are the differences between `==` and `equals()` in Java? 11 | - **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. 12 | 13 | ### 3. How does Java handle memory management? 14 | - **Answer:** Java uses an automatic garbage collection mechanism to manage memory. It allocates memory on the heap for new objects and reclaims memory from objects that are no longer referenced. 15 | 16 | ### 4. How do you handle exceptions in Java? 17 | - **Answer:** Exceptions in Java are handled using try-catch blocks, where code that might throw an exception is placed inside the try block and exception handling code is placed inside the catch block. 18 | 19 | ### 5. What are checked and unchecked exceptions in Java? 20 | - **Answer:** Checked exceptions are exceptions that must be either caught or declared in the method signature using the `throws` keyword. Unchecked exceptions are exceptions that do not need to be explicitly handled, typically subclasses of `RuntimeException`. 21 | 22 | ### 6. How do you handle exceptions in Spring Boot applications? 23 | - **Answer:** Spring Boot provides the `@ExceptionHandler` annotation to handle exceptions in a controller. Additionally, `@ControllerAdvice` can be used to define global exception handlers for the entire application. 24 | 25 | ### 7. Given a list of employees, find the list of employees based on gender. Result should be - Male, [e1, e2, e3] Female, [e4, e5]. 26 | - **Answer:** 27 | ```java 28 | Map> employeesByGender = employees.stream() 29 | .collect(Collectors.groupingBy(Employee::getGender)); 30 | ``` 31 | 32 | ### 8. Explain the basics of Spring Boot. 33 | - **Answer:** Spring Boot simplifies the development of Spring applications by providing a set of tools and libraries for rapid application development. It offers features like auto-configuration, standalone application configuration, and embedded servers. 34 | 35 | ### 9. Write a code example for a JPA repository and a derived query. 36 | - **Answer:** 37 | ```java 38 | @Repository 39 | public interface EmployeeRepository extends JpaRepository { 40 | List findByGender(String gender); 41 | } 42 | ``` 43 | 44 | ### 10. Explain thread pools and their use in Java. 45 | - **Answer:** Thread pools manage a collection of reusable threads for executing tasks, which improves application performance by reducing the overhead of creating and destroying threads. Java provides `ExecutorService` to manage thread pools. 46 | 47 | ### 11. Configure HikariCP in a Spring Boot application. 48 | - **Answer:** 49 | ```yaml 50 | spring: 51 | datasource: 52 | url: jdbc:mysql://localhost:3306/db 53 | username: user 54 | password: pass 55 | hikari: 56 | maximum-pool-size: 10 57 | ``` 58 | 59 | 60 | ### 12. Explain Hibernate queries and entity graphs. 61 | - **Answer:** Hibernate queries can be written using HQL or Criteria API. Entity graphs optimize queries by defining which related entities should be fetched, reducing the number of queries executed and improving performance. 62 | 63 | ### 13. How do you write test cases differently for controller, data, and service layers? 64 | - **Answer:** 65 | ```java 66 | // Controller Test 67 | @WebMvcTest(EmployeeController.class) 68 | public class EmployeeControllerTest { 69 | @Autowired 70 | private MockMvc mockMvc; 71 | 72 | @MockBean 73 | private EmployeeService employeeService; 74 | 75 | @Test 76 | public void testGetEmployee() throws Exception { 77 | mockMvc.perform(get("/employees/1")) 78 | .andExpect(status().isOk()) 79 | .andExpect(jsonPath("$.name").value("John")); 80 | } 81 | } 82 | 83 | // Service Test 84 | @ExtendWith(MockitoExtension.class) 85 | public class EmployeeServiceTest { 86 | @Mock 87 | private EmployeeRepository employeeRepository; 88 | 89 | @InjectMocks 90 | private EmployeeService employeeService; 91 | 92 | @Test 93 | public void testFindEmployeeById() { 94 | when(employeeRepository.findById(1L)).thenReturn(Optional.of(new Employee("John"))); 95 | Employee employee = employeeService.findEmployeeById(1L); 96 | assertEquals("John", employee.getName()); 97 | } 98 | } 99 | 100 | // Repository Test 101 | @DataJpaTest 102 | public class EmployeeRepositoryTest { 103 | @Autowired 104 | private EmployeeRepository employeeRepository; 105 | 106 | @Test 107 | public void testFindByGender() { 108 | List employees = employeeRepository.findByGender("Male"); 109 | assertEquals(3, employees.size()); 110 | } 111 | } 112 | ``` 113 | 114 | ### 14. Explain code coverage and tools like SonarQube. 115 | - **Answer:** Code coverage measures how much of the code is tested by unit tests. Tools like SonarQube analyze code quality, including code coverage, and provide reports to help improve code reliability and maintainability. 116 | 117 | ### 15. What are deployment tools and how do they work? 118 | - **Answer:** - **Answer:** Deployment tools like Jenkins, Docker, and Kubernetes automate the process of deploying applications, ensuring consistent environments and simplifying scaling and management. 119 | 120 | ### 16. Difference between vanilla JavaScript and React. 121 | - **Answer:** Vanilla JavaScript is a plain JavaScript without any libraries or frameworks. React is a library for building user interfaces, offering components, state management, and virtual DOM for efficient updates. 122 | 123 | ### 17. Explain useState and useEffect hooks in React. 124 | - **Answer:** `useState` is a hook that lets you add state to functional components. `useEffect` is a hook for performing side effects, such as data fetching or updating the DOM, in functional components. 125 | 126 | ### 18. Write a basic API call using React. 127 | - **Answer:** 128 | ```javascript 129 | useEffect(() => { 130 | fetch('https://api.example.com/data') 131 | .then(response => response.json()) 132 | .then(data => setData(data)); 133 | }, []); 134 | ``` 135 | 136 | ### 19. Transform an IP address from `192.62.255.31` to `291.26.552.13`. 137 | - **Answer:** 138 | ```javascript 139 | function transformIP(ip) { 140 | return ip.split('.').map(octet => { 141 | return octet.split('').reverse().join(''); 142 | }).join('.'); 143 | } 144 | console.log(transformIP('192.62.255.31')); // 291.26.552.13 145 | ``` 146 | ## Second Round Interview: Pair Programming 147 | ### 1. Develop a UI page to show a list of items in the search page using React. 148 | - **Answer:** 149 | ```javascript 150 | import React, { useState, useEffect } from 'react'; 151 | 152 | const ItemList = () => { 153 | const [items, setItems] = useState([]); 154 | const [searchTerm, setSearchTerm] = useState(''); 155 | 156 | useEffect(() => { 157 | fetch('http://localhost:8080/api/items') 158 | .then(response => response.json()) 159 | .then(data => setItems(data)); 160 | }, []); 161 | 162 | const filteredItems = items.filter(item => item.name.includes(searchTerm)); 163 | 164 | return ( 165 |
166 | setSearchTerm(e.target.value)} 171 | /> 172 |
    173 | {filteredItems.map(item => ( 174 |
  • {item.name}
  • 175 | ))} 176 |
177 |
178 | ); 179 | }; 180 | 181 | export default ItemList; 182 | ``` 183 | 184 | ### 2. Write an API with Spring Boot and use the API endpoint in React to show the list. 185 | - **Spring Boot API:** 186 | ```java 187 | @RestController 188 | @RequestMapping("/api/items") 189 | public class ItemController { 190 | @Autowired 191 | private ItemService itemService; 192 | 193 | @GetMapping 194 | public List getAllItems() { 195 | return itemService.getAllItems(); 196 | } 197 | } 198 | 199 | @Service 200 | public class ItemService { 201 | @Autowired 202 | private ItemRepository itemRepository; 203 | 204 | public List getAllItems() { 205 | return itemRepository.findAll(); 206 | } 207 | } 208 | 209 | @Repository 210 | public interface ItemRepository extends JpaRepository {} 211 | 212 | @Entity 213 | public class Item { 214 | @Id 215 | @GeneratedValue(strategy = GenerationType.IDENTITY) 216 | private Long id; 217 | private String name; 218 | 219 | // getters and setters 220 | } 221 | ``` 222 | 223 | - **React Integration:** 224 | ```javascript 225 | import React, { useState, useEffect } from 'react'; 226 | 227 | const ItemList = () => { 228 | const [items, setItems] = useState([]); 229 | 230 | useEffect(() => { 231 | fetch('http://localhost:8080/api/items') 232 | .then(response => response.json()) 233 | .then(data => setItems(data)); 234 | }, []); 235 | 236 | return ( 237 |
    238 | {items.map(item => ( 239 |
  • {item.name}
  • 240 | ))} 241 |
242 | ); 243 | }; 244 | 245 | export default ItemList; 246 | ``` 247 | -------------------------------------------------------------------------------- /Ford Motor/Foad Interview_1.md: -------------------------------------------------------------------------------- 1 | 2 | # Ford Interview 3 | ## Java/Spring Boot 4 | ### 1. Explain CSR (Cross-Site Request) and how you handle it in your applications. 5 | 6 | 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. 7 | 8 | ```java 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 11 | 12 | public class SecurityConfig extends WebSecurityConfigurerAdapter { 13 | @Override 14 | protected void configure(HttpSecurity http) throws Exception { 15 | http 16 | .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) 17 | .and() 18 | .authorizeRequests() 19 | .anyRequest().authenticated(); 20 | } 21 | } 22 | ``` 23 | 24 | ### 2. What is JWT Security, and how do you implement it? 25 | 26 | 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). 27 | Implementing JWT Security in Spring Boot 28 | #### To implement JWT security in a Spring Boot application, you typically follow these steps: 29 | **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. 30 | 31 | **Configure Spring Security:** Configure Spring Security to intercept requests and ensure only authenticated users can access certain endpoints. This involves setting up a security configuration class. 32 | 33 | **Create JWT Utility Class:** This class will handle JWT creation, validation, and parsing. It includes methods to generate tokens, extract claims, and validate tokens. 34 | 35 | **Create Authentication Filter:** Implement a filter that intercepts incoming requests and checks for a valid JWT in the Authorization header. This filter will use the JWT utility class to validate the token and set the authentication context. 36 | 37 | **User Authentication and Authorization:** Implement user authentication by overriding the UserDetailsService to load user-specific data. Use the AuthenticationManager to authenticate users and generate a JWT for authenticated users. 38 | 39 | 40 | ### 3. Describe OAuth2 and how it is used in your applications. 41 | 42 | OAuth2 (Open Authorization) is an authorization framework that allows applications to obtain limited access to user accounts on an HTTP service, such as Facebook, GitHub, or Google. It works by delegating user authentication to the service that hosts the user account and authorizing third-party applications to access the user account. 43 | 44 | ### 4. How do you implement paging to get data in Spring Boot? 45 | 46 | You can use Spring Data JPA’s `Pageable` interface to implement paging. 47 | 48 | ```java 49 | import org.springframework.data.domain.Page; 50 | import org.springframework.data.domain.Pageable; 51 | 52 | public interface UserRepository extends JpaRepository { 53 | Page findAll(Pageable pageable); 54 | } 55 | 56 | // Service 57 | public Page getUsers(Pageable pageable) { 58 | return userRepository.findAll(pageable); 59 | } 60 | 61 | // Controller 62 | @GetMapping("/users") 63 | public Page listUsers(Pageable pageable) { 64 | return userService.getUsers(pageable); 65 | } 66 | ``` 67 | 68 | ### 5. How do you sort data based on a property in Spring Boot? 69 | 70 | You can use Spring Data JPA’s `Sort` class to sort data. 71 | 72 | ```java 73 | import org.springframework.data.domain.Sort; 74 | 75 | public List getUsers() { 76 | return userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); 77 | } 78 | ``` 79 | 80 | ### 6. What is an API Gateway, and why is it used? 81 | 82 | 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. 83 | 84 | ### 7. How do you implement load balancing in your applications? 85 | 86 | You can implement load balancing using tools like Ribbon or Spring Cloud LoadBalancer in a Spring Boot application. 87 | 88 | ```java 89 | import org.springframework.cloud.client.loadbalancer.LoadBalanced; 90 | import org.springframework.context.annotation.Bean; 91 | import org.springframework.web.client.RestTemplate; 92 | 93 | @Bean 94 | @LoadBalanced 95 | public RestTemplate restTemplate() { 96 | return new RestTemplate(); 97 | } 98 | ``` 99 | 100 | ### 8. Explain the difference between Monolithic and Microservices architectures. 101 | 102 | - **Monolithic Architecture:** A single unified codebase where all the components and services are tightly coupled and run as a single service. 103 | - **Microservices Architecture:** An approach where an application is composed of loosely coupled services, each running in its own process and communicating through lightweight mechanisms like HTTP or messaging queues. 104 | 105 | ### 9. What is Kubernetes, and how do you use it in your applications? 106 | 107 | Kubernetes is an open-source container orchestration platform that automates the deployment, scaling, and management of containerized applications. You can use it to deploy, manage, and scale your microservices. 108 | 109 | ### 10. How do you connect one microservice to another? 110 | 111 | You can use REST APIs, messaging queues (like RabbitMQ), or service discovery tools (like Eureka) to connect microservices. 112 | 113 | ### 11. What is the difference between @RestController and @Controller in Spring Boot? 114 | 115 | - **@RestController:** Combines @Controller and @ResponseBody, used to create RESTful web services. 116 | - **@Controller:** Used to define a controller and is typically used with view templates to render HTML. 117 | 118 | ### 12. How do you perform code quality analysis in your projects? 119 | 120 | You can use tools like SonarQube for static code analysis, which helps in identifying code smells, bugs, and security vulnerabilities. 121 | 122 | ### 13. What is the difference between authentication and authorization? 123 | 124 | - **Authentication:** The process of verifying the identity of a user. 125 | - **Authorization:** The process of verifying what resources an authenticated user has access to. 126 | 127 | ### 14. How do you scale your application? 128 | 129 | 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. 130 | 131 | ### 15. What are profiles in Spring Boot, and how do you use them? 132 | 133 | Profiles in Spring Boot allow you to configure different environments (e.g., development, testing, production). You can specify different configurations in `application-{profile}.properties` files. 134 | 135 | ```java 136 | // application-dev.properties 137 | spring.datasource.url=jdbc:h2:mem:devdb 138 | 139 | // application-prod.properties 140 | spring.datasource.url=jdbc:mysql://localhost/proddb 141 | 142 | // Main application 143 | @SpringBootApplication 144 | @PropertySource("classpath:application-${spring.profiles.active}.properties") 145 | public class MyApp { 146 | public static void main(String[] args) { 147 | SpringApplication.run(MyApp.class, args); 148 | } 149 | } 150 | ``` 151 | 152 | ## React 153 | 154 | ### 1. What is middleware in ReactJS, and how do you use it? 155 | 156 | 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. 157 | 158 | ```javascript 159 | const loggerMiddleware = store => next => action => { 160 | console.log('Dispatching:', action); 161 | let result = next(action); 162 | console.log('Next state:', store.getState()); 163 | return result; 164 | }; 165 | 166 | const store = createStore( 167 | rootReducer, 168 | applyMiddleware(loggerMiddleware) 169 | ); 170 | ``` 171 | 172 | ### 2. Explain the Context API and Redux. How do they differ, and when do you use each? 173 | 174 | - **Context API:** Built-in feature of React for prop drilling and global state management. Best for small to medium applications. 175 | - **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. 176 | 177 | ### 3. How do you write unit tests in React? 178 | 179 | You can use testing libraries like Jest and React Testing Library to write unit tests. 180 | 181 | ```javascript 182 | import { render, screen } from '@testing-library/react'; 183 | import App from './App'; 184 | 185 | test('renders learn react link', () => { 186 | render(); 187 | const linkElement = screen.getByText(/learn react/i); 188 | expect(linkElement).toBeInTheDocument(); 189 | }); 190 | ``` 191 | 192 | ### 4. Have you worked on reusable components in React? Give an example. 193 | 194 | Yes, for example, a Button component that can be reused across the application. 195 | 196 | ```javascript 197 | const Button = ({ label, onClick }) => ( 198 | 201 | ); 202 | 203 | // Usage 204 | 104 | 105 |
This text will change color when data is posted.
106 | 107 | ); 108 | }; 109 | 110 | export default ChangeTextColor; 111 | ``` 112 | 113 | ## Java Questions 114 | 16. **Which version of Java are you using? (Java 8, familiar with Java 17)** 115 | - I am using Java 8 and familiar with Java 17. 116 | 117 | 17. **Write a custom exception in Java and use it.** 118 | ```java 119 | public class CustomException extends Exception { 120 | public CustomException(String message) { 121 | super(message); 122 | } 123 | } 124 | 125 | public class TestCustomException { 126 | public static void main(String[] args) { 127 | try { 128 | validateAge(15); 129 | } catch (CustomException e) { 130 | e.printStackTrace(); 131 | } 132 | } 133 | 134 | static void validateAge(int age) throws CustomException { 135 | if (age < 18) { 136 | throw new CustomException("Age is not valid"); 137 | } 138 | } 139 | } 140 | ``` 141 | 142 | 18. **Implement a method in Java to check if a string is present in a list.** 143 | ```java 144 | import java.util.List; 145 | 146 | public class StringChecker { 147 | public static boolean isStringPresent(List list, String str) { 148 | return list.contains(str); 149 | } 150 | } 151 | ``` 152 | 153 | 19. **Write Java code to remove repeated strings from a list.** 154 | ```java 155 | import java.util.ArrayList; 156 | import java.util.HashSet; 157 | import java.util.List; 158 | import java.util.Set; 159 | 160 | public class RemoveDuplicates { 161 | public static List removeDuplicates(List list) { 162 | Set set = new HashSet<>(list); 163 | return new ArrayList<>(set); 164 | } 165 | } 166 | ``` 167 | 168 | 20. **How do you provide security in Spring Boot?** 169 | - Security in Spring Boot is provided through Spring Security, which offers authentication, authorization, and other security features. It can be configured using Java configuration and annotations. 170 | 171 | 21. **Explain how JWT token-based authentication works briefly.** 172 | - JWT token-based authentication works by generating a token after a user successfully logs in. This token is then sent with each subsequent request in the Authorization header. The server validates the token to authenticate the user. 173 | 174 | 22. **What is the use of the `@Transactional` annotation in Spring Data?** 175 | - The `@Transactional` annotation in Spring Data is used to manage transactions declaratively. It ensures that a method runs within a transaction and manages commit or rollback based on the method’s execution. 176 | 177 | 23. **Have you used threads in your project?** 178 | - Yes, I have used threads in my project to handle concurrent processing tasks like processing multiple requests simultaneously. 179 | 180 | 24. **How do you limit API calls in Spring Boot?** 181 | - API calls in Spring Boot can be limited using rate-limiting libraries like Bucket4j or implementing custom rate-limiting logic using interceptors. 182 | 183 | 25. **Have you created any custom annotations in Spring Boot?** 184 | - Yes, I have created custom annotations to encapsulate repetitive logic and apply cross-cutting concerns. 185 | 186 | 26. **Create a Age validation custom annotation.** 187 | - Steps 188 | 1. **Create the Annotation Interface** 189 | 2. **Create the Validator Class** 190 | 3. **Apply the Custom Annotation** 191 | 192 | #### 1. Create the Annotation Interface 193 | 194 | First, create a custom annotation interface for DOB validation. 195 | 196 | ```java 197 | import javax.validation.Constraint; 198 | import javax.validation.Payload; 199 | import java.lang.annotation.Documented; 200 | import java.lang.annotation.ElementType; 201 | import java.lang.annotation.Retention; 202 | import java.lang.annotation.RetentionPolicy; 203 | import java.lang.annotation.Target; 204 | 205 | @Documented 206 | @Constraint(validatedBy = DOBValidator.class) 207 | @Target({ ElementType.METHOD, ElementType.FIELD }) 208 | @Retention(RetentionPolicy.RUNTIME) 209 | public @interface ValidDOB { 210 | String message() default "Invalid Date of Birth"; 211 | Class[] groups() default {}; 212 | Class[] payload() default {}; 213 | } 214 | ``` 215 | 216 | #### 2. Create the Validator Class 217 | 218 | Next, implement the validator class that will contain the logic for validating the DOB. 219 | 220 | ```java 221 | import javax.validation.ConstraintValidator; 222 | import javax.validation.ConstraintValidatorContext; 223 | import java.time.LocalDate; 224 | 225 | public class DOBValidator implements ConstraintValidator { 226 | 227 | @Override 228 | public void initialize(ValidDOB constraintAnnotation) { 229 | // Initialization code if necessary 230 | } 231 | 232 | @Override 233 | public boolean isValid(LocalDate dob, ConstraintValidatorContext context) { 234 | if (dob == null) { 235 | return false; // or true, based on whether null is considered valid 236 | } 237 | // Check if the DOB is in the past 238 | return dob.isBefore(LocalDate.now()); 239 | } 240 | } 241 | ``` 242 | 243 | 244 | 27. **Have you used a logger in your Spring Boot project?** 245 | - Yes, I have used SLF4J with Logback for logging in my Spring Boot project. 246 | 247 | 28. **How can you see which controller API methods are running?** 248 | - 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. 249 | 250 | 29. **How do you create a Spring Boot project?** 251 | - A Spring Boot project can be created using Spring Initializr, which generates a project structure with the necessary dependencies and configurations. 252 | 253 | 30. **What does Spring Starter provide?** 254 | - Spring Starter provides pre-configured templates for specific functionalities like web, security, JPA, etc., making it easier to set up a Spring Boot project. 255 | 256 | 31. **Which dependencies do you commonly use in Spring Boot?** 257 | - Common dependencies include Spring Boot Starter Web, Spring Boot Starter Data JPA, Spring Boot Starter Security, and Spring Boot Starter Test. 258 | 259 | 32. **Which annotations do you use in Spring Boot?** 260 | - Common annotations include `@SpringBootApplication`, `@RestController`, `@RequestMapping`, `@Autowired`, `@Entity`, `@Repository`, and `@Service`. 261 | 262 | 33. **Which annotations do you use in JUnit tests?** 263 | - Common annotations include `@Test`, `@BeforeEach`, `@AfterEach`, `@Mock`, `@InjectMocks`, and `@RunWith`. 264 | 265 | 34. **Which libraries do you use for JUnit tests?** 266 | - Common libraries include JUnit 5, Mockito, and Spring Boot Test. 267 | -------------------------------------------------------------------------------- /PayPal/PayPal.md: -------------------------------------------------------------------------------- 1 | ### **HackerRank Coding Assessment - PayPal** 2 | 1. **Java.Inventory Clearance Sale** 3 | 2. **Item Purchase** 4 | 3. **Minimum Total Weight** 5 | 6 | --- 7 | 8 | ### **PayPal Technical L1 Interview - Coding Questions** 9 | 10 | #### **1. Find the longest substring with non-repeating characters** 11 | **Question:** 12 | Write a function that takes a string and returns the longest substring that contains only unique (non-repeating) characters. 13 | 14 | **Example Input & Output:** 15 | **Input:** `"abcabcbb"` 16 | **Output:** `3` (`"abc"`) 17 | 18 | **Input:** `"bbbbb"` 19 | **Output:** `1` (`"b"`) 20 | 21 | **Input:** `"pwwkew"` 22 | **Output:** `3` (`"wke"`) 23 | 24 | **Java Code:** 25 | ```java 26 | import java.util.HashSet; 27 | 28 | public class LongestSubstring { 29 | public static int lengthOfLongestSubstring(String s) { 30 | int left = 0, right = 0, maxLength = 0; 31 | HashSet set = new HashSet<>(); 32 | 33 | while (right < s.length()) { 34 | if (!set.contains(s.charAt(right))) { 35 | set.add(s.charAt(right)); 36 | maxLength = Math.max(maxLength, right - left + 1); 37 | right++; 38 | } else { 39 | set.remove(s.charAt(left)); 40 | left++; 41 | } 42 | } 43 | return maxLength; 44 | } 45 | 46 | public static void main(String[] args) { 47 | System.out.println(lengthOfLongestSubstring("abcabcbb")); // Output: 3 48 | System.out.println(lengthOfLongestSubstring("bbbbb")); // Output: 1 49 | System.out.println(lengthOfLongestSubstring("pwwkew")); // Output: 3 50 | } 51 | } 52 | ``` 53 | 54 | --- 55 | 56 | #### **2. Find the maximum water trapped between bars** 57 | **Question:** 58 | Given an array where each element represents the height of a bar, find the maximum amount of water that can be trapped between the bars after rainfall. 59 | 60 | **Example Input & Output:** 61 | **Input:** `[0,1,0,2,1,0,1,3,2,1,2,1]` 62 | **Output:** `6` 63 | 64 | **Input:** `[4,2,0,3,2,5]` 65 | **Output:** `9` 66 | 67 | **Java Code:** 68 | ```java 69 | public class TrappingRainWater { 70 | public static int trap(int[] height) { 71 | if (height == null || height.length == 0) return 0; 72 | 73 | int left = 0, right = height.length - 1; 74 | int leftMax = 0, rightMax = 0, trappedWater = 0; 75 | 76 | while (left < right) { 77 | if (height[left] < height[right]) { 78 | if (height[left] >= leftMax) { 79 | leftMax = height[left]; 80 | } else { 81 | trappedWater += (leftMax - height[left]); 82 | } 83 | left++; 84 | } else { 85 | if (height[right] >= rightMax) { 86 | rightMax = height[right]; 87 | } else { 88 | trappedWater += (rightMax - height[right]); 89 | } 90 | right--; 91 | } 92 | } 93 | return trappedWater; 94 | } 95 | 96 | public static void main(String[] args) { 97 | System.out.println(trap(new int[]{0,1,0,2,1,0,1,3,2,1,2,1})); // Output: 6 98 | System.out.println(trap(new int[]{4,2,0,3,2,5})); // Output: 9 99 | } 100 | } 101 | ``` 102 | 103 | --- 104 | ### **PayPal Technical L2 Interview - Coding Questions** 105 | 106 | ### **Peer-to-Peer Payment System Design** 107 | We will design two APIs: 108 | 1. **Send Payment API** – Allows a user to send money to another user. 109 | 2. **Request Payment API** – Allows a user to request money from another user. 110 | 111 | ### **Design Considerations** 112 | - Each user will have a **User ID** and **Balance**. 113 | - Sending money requires checking the sender’s balance. 114 | - Requesting money creates a pending request. 115 | 116 | --- 117 | 118 | ### **Implementation Plan** 119 | 1. **User Class**: Represents a user with an ID and balance. 120 | 2. **Transaction Class**: Represents payment transactions. 121 | 3. **PaymentService Class**: Implements send and request payment logic. 122 | 4. **Main Class**: Demonstrates API usage. 123 | 124 | --- 125 | 126 | ### **Java Implementation** 127 | 128 | ```java 129 | import java.util.*; 130 | 131 | class User { 132 | private String userId; 133 | private double balance; 134 | 135 | public User(String userId, double balance) { 136 | this.userId = userId; 137 | this.balance = balance; 138 | } 139 | 140 | public String getUserId() { 141 | return userId; 142 | } 143 | 144 | public double getBalance() { 145 | return balance; 146 | } 147 | 148 | public void setBalance(double balance) { 149 | this.balance = balance; 150 | } 151 | } 152 | 153 | class Transaction { 154 | private String senderId; 155 | private String receiverId; 156 | private double amount; 157 | private String status; // "COMPLETED" or "FAILED" 158 | 159 | public Transaction(String senderId, String receiverId, double amount, String status) { 160 | this.senderId = senderId; 161 | this.receiverId = receiverId; 162 | this.amount = amount; 163 | this.status = status; 164 | } 165 | 166 | public String toString() { 167 | return "Transaction: " + senderId + " -> " + receiverId + " | Amount: " + amount + " | Status: " + status; 168 | } 169 | } 170 | 171 | class PaymentService { 172 | private Map users = new HashMap<>(); 173 | private List transactions = new ArrayList<>(); 174 | private List paymentRequests = new ArrayList<>(); 175 | 176 | public void addUser(String userId, double balance) { 177 | users.put(userId, new User(userId, balance)); 178 | } 179 | 180 | public String sendPayment(String senderId, String receiverId, double amount) { 181 | if (!users.containsKey(senderId) || !users.containsKey(receiverId)) { 182 | return "Invalid user IDs"; 183 | } 184 | 185 | User sender = users.get(senderId); 186 | User receiver = users.get(receiverId); 187 | 188 | if (sender.getBalance() < amount) { 189 | transactions.add(new Transaction(senderId, receiverId, amount, "FAILED")); 190 | return "Insufficient balance"; 191 | } 192 | 193 | sender.setBalance(sender.getBalance() - amount); 194 | receiver.setBalance(receiver.getBalance() + amount); 195 | transactions.add(new Transaction(senderId, receiverId, amount, "COMPLETED")); 196 | 197 | return "Payment Successful"; 198 | } 199 | 200 | public String requestPayment(String requesterId, String payerId, double amount) { 201 | if (!users.containsKey(requesterId) || !users.containsKey(payerId)) { 202 | return "Invalid user IDs"; 203 | } 204 | 205 | String request = "Request from " + requesterId + " to " + payerId + " for amount " + amount; 206 | paymentRequests.add(request); 207 | return "Payment Request Sent"; 208 | } 209 | 210 | public void printTransactions() { 211 | transactions.forEach(System.out::println); 212 | } 213 | 214 | public void printRequests() { 215 | paymentRequests.forEach(System.out::println); 216 | } 217 | } 218 | 219 | public class PeerToPeerPayment { 220 | public static void main(String[] args) { 221 | PaymentService service = new PaymentService(); 222 | 223 | service.addUser("user1", 1000); 224 | service.addUser("user2", 500); 225 | 226 | System.out.println(service.sendPayment("user1", "user2", 200)); 227 | System.out.println(service.requestPayment("user2", "user1", 150)); 228 | 229 | service.printTransactions(); 230 | service.printRequests(); 231 | } 232 | } 233 | ``` 234 | 235 | --- 236 | 237 | ### **Explanation** 238 | 1. **User Class**: Holds user ID and balance. 239 | 2. **Transaction Class**: Stores transaction details. 240 | 3. **PaymentService Class**: 241 | - **sendPayment()**: Checks balance and transfers money. 242 | - **requestPayment()**: Adds a payment request. 243 | 4. **Main Class**: Demonstrates functionality. 244 | 245 | --- 246 | ### **PayPal Technical L3 Interview - Coding Questions** 247 | 248 | ```java 249 | import java.util.EnumMap; 250 | import java.util.Map; 251 | 252 | // Enum for Furniture with cost 253 | enum Furniture { 254 | CHAIR(1500), FAN(2000), BED(5000); 255 | 256 | private final int cost; 257 | 258 | Furniture(int cost) { 259 | this.cost = cost; 260 | } 261 | 262 | public int getCost() { 263 | return cost; 264 | } 265 | } 266 | 267 | // Furniture Order Class 268 | class FurnitureOrder { 269 | private final Map orders = new EnumMap<>(Furniture.class); 270 | 271 | // Add order 272 | public void addOrder(Furniture furniture, int quantity) { 273 | orders.put(furniture, orders.getOrDefault(furniture, 0) + quantity); 274 | } 275 | 276 | // Get all orders 277 | public Map getAllOrders() { 278 | return new EnumMap<>(orders); 279 | } 280 | 281 | // Get total furniture count 282 | public int getTotalFurnitureCount() { 283 | return orders.values().stream().mapToInt(Integer::intValue).sum(); 284 | } 285 | 286 | // Get specific furniture count 287 | public int getFurnitureCount(Furniture furniture) { 288 | return orders.getOrDefault(furniture, 0); 289 | } 290 | 291 | // Get total cost of all orders 292 | public int getTotalOrderCost() { 293 | return orders.entrySet().stream().mapToInt(e -> e.getKey().getCost() * e.getValue()).sum(); 294 | } 295 | 296 | // Get cost of specific furniture type 297 | public int getFurnitureTypeCost(Furniture furniture) { 298 | return getFurnitureCount(furniture) * furniture.getCost(); 299 | } 300 | } 301 | 302 | // JUnit Test Cases 303 | import static org.junit.jupiter.api.Assertions.*; 304 | import org.junit.jupiter.api.BeforeEach; 305 | import org.junit.jupiter.api.Test; 306 | 307 | class FurnitureOrderTest { 308 | private FurnitureOrder order; 309 | 310 | @BeforeEach 311 | void setUp() { 312 | order = new FurnitureOrder(); 313 | } 314 | 315 | @Test 316 | void testAddOrder() { 317 | order.addOrder(Furniture.CHAIR, 2); 318 | assertEquals(2, order.getFurnitureCount(Furniture.CHAIR)); 319 | } 320 | 321 | @Test 322 | void testGetAllOrders() { 323 | order.addOrder(Furniture.FAN, 1); 324 | assertTrue(order.getAllOrders().containsKey(Furniture.FAN)); 325 | } 326 | 327 | @Test 328 | void testGetTotalFurnitureCount() { 329 | order.addOrder(Furniture.BED, 2); 330 | order.addOrder(Furniture.CHAIR, 3); 331 | assertEquals(5, order.getTotalFurnitureCount()); 332 | } 333 | 334 | @Test 335 | void testGetFurnitureCount() { 336 | order.addOrder(Furniture.FAN, 4); 337 | assertEquals(4, order.getFurnitureCount(Furniture.FAN)); 338 | } 339 | 340 | @Test 341 | void testGetTotalOrderCost() { 342 | order.addOrder(Furniture.CHAIR, 2); 343 | order.addOrder(Furniture.BED, 1); 344 | assertEquals(8000, order.getTotalOrderCost()); 345 | } 346 | 347 | @Test 348 | void testGetFurnitureTypeCost() { 349 | order.addOrder(Furniture.FAN, 3); 350 | assertEquals(6000, order.getFurnitureTypeCost(Furniture.FAN)); 351 | } 352 | 353 | @Test 354 | void testEmptyOrderCost() { 355 | assertEquals(0, order.getTotalOrderCost()); 356 | } 357 | } 358 | ``` 359 | -------------------------------------------------------------------------------- /MindGate/MindGate1.md: -------------------------------------------------------------------------------- 1 | # L1 MindGate 2 | 1. **How to migrate HTML & JavaScript code to ReactJS?** 3 | 4 | **Answer:** 5 | To migrate HTML and JavaScript code to ReactJS, follow these steps: 6 | - **Set Up React Environment:** Initialize a new React project using Create React App or any other setup tool. 7 | - **Component Structure:** Identify distinct sections of your HTML and JavaScript that can be transformed into React components. 8 | - **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. 9 | - **State Management:** Convert JavaScript logic related to state and events into React state and event handlers. 10 | - **Refactor Functions:** Transform your JavaScript functions into React component methods or hooks. 11 | - **Routing:** If your application has multiple pages, set up React Router to handle navigation. 12 | 13 | 2. **How to consume already shared messages in Kafka?** 14 | 15 | **Answer:** 16 | To consume messages that have already been shared in Kafka: 17 | - **Set Consumer Group:** Configure your Kafka consumer to be part of a consumer group. Kafka maintains offsets per consumer group. 18 | - **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. 19 | - **Configure Consumer Properties:** Ensure your consumer properties are set correctly, such as `auto.offset.reset` (e.g., `earliest` to read from the beginning). 20 | 21 | 3. **What are your daily roles and responsibilities?** 22 | 23 | **Answer:** 24 | This answer will vary depending on the role, but generally: 25 | - **Development:** Writing and maintaining code for various features and fixing bugs. 26 | - **Collaboration:** Working with cross-functional teams including designers, product managers, and other developers. 27 | - **Code Reviews:** Participating in code reviews to ensure code quality and adherence to best practices. 28 | - **Testing:** Writing and running unit tests and integration tests. 29 | - **Deployment:** Assisting with the deployment of applications and ensuring smooth production operations. 30 | 31 | 4. **What is the difference between `@RestController` and `@Controller` in Spring?** 32 | 33 | **Answer:** 34 | - **`@Controller`:** Used in Spring MVC to define a controller class. It is used for building web applications and returns views (JSP, Thymeleaf). 35 | - **`@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. 36 | 37 | 5. **What is the difference between method overloading and method overriding in Java?** 38 | 39 | **Answer:** 40 | - **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. 41 | - **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. 42 | 43 | 6. **What is a thread in Java?** 44 | 45 | **Answer:** 46 | 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. 47 | 48 | 7. **How do you handle exceptions in a `Runnable` since it cannot throw checked exceptions?** 49 | 50 | **Answer:** 51 | 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: 52 | 53 | ```java 54 | public class MyRunnable implements Runnable { 55 | @Override 56 | public void run() { 57 | try { 58 | // Code that might throw an exception 59 | } catch (Exception e) { 60 | // Handle the exception 61 | e.printStackTrace(); 62 | } 63 | } 64 | } 65 | ``` 66 | 67 | 8. **What are the differences between `Callable` and `Runnable` in Java?** 68 | 69 | **Answer:** 70 | - **`Runnable`:** Represents a task that can be executed by a thread. It does not return a result and cannot throw checked exceptions. 71 | - **`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. 72 | 73 | 9. **What is the difference between `wait()` and `sleep()` methods in Java?** 74 | 75 | **Answer:** 76 | - **`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. 77 | - **`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. 78 | 79 | 10. **Can you explain the thread life cycle in Java?** 80 | 81 | **Answer:** 82 | The thread life cycle consists of: 83 | - **New:** The thread is created but not yet started. 84 | - **Runnable:** The thread is ready to run and waiting for CPU time. 85 | - **Blocked:** The thread is waiting to acquire a lock or resource. 86 | - **Waiting:** The thread is waiting indefinitely for another thread to perform a particular action. 87 | - **Timed Waiting:** The thread is waiting for a specified period. 88 | - **Terminated:** The thread has completed execution or terminated. 89 | 90 | 11. **What is a thread pool in Java and how does it work?** 91 | 92 | **Answer:** 93 | 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`. 94 | 95 | 12. **What are the differences between Spring MVC and Spring Boot?** 96 | 97 | **Answer:** 98 | - **Spring MVC:** A framework for building web applications using the Model-View-Controller design pattern. Requires configuration for setting up the application. 99 | - **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. 100 | 101 | 13. **How do you join two tables in SQL? Provide an example query.** 102 | 103 | **Answer:** 104 | To join two tables in SQL, you use the `JOIN` clause. For example, to join `employees` and `departments` tables: 105 | 106 | ```sql 107 | SELECT e.employee_id, e.name, d.department_name 108 | FROM employees e 109 | JOIN departments d ON e.department_id = d.department_id; 110 | ``` 111 | 112 | 14. **Write a Java code snippet to find the top element in a mountain array.** 113 | 114 | **Answer:** 115 | 116 | ```java 117 | public class MountainArrayTop { 118 | 119 | public static int findTopElement(int[] arr) { 120 | int left = 0, right = arr.length - 1; 121 | while (left <= right) { 122 | int mid = left + (right - left) / 2; 123 | if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) { 124 | return arr[mid]; 125 | } else if (arr[mid] > arr[mid - 1]) { 126 | left = mid + 1; 127 | } else { 128 | right = mid - 1; 129 | } 130 | } 131 | return -1; // should not reach here if input is a valid mountain array 132 | } 133 | 134 | public static void main(String[] args) { 135 | int[] mountainArray = {1, 3, 8, 12, 4, 2}; 136 | System.out.println("Top element: " + findTopElement(mountainArray)); 137 | } 138 | } 139 | ``` 140 | 141 | **Example:** 142 | - **Input:** `[1, 3, 8, 12, 4, 2]` 143 | - **Output:** `12` 144 | 145 | 15. **Which technologies have you worked with, and how have you utilized them in your projects?** 146 | 147 | **Answer:** 148 | This question is specific to your experience and will vary. Here’s an example structure: 149 | - **ReactJS:** Used for building dynamic and responsive user interfaces. 150 | - **Spring Boot:** Utilized for creating RESTful APIs and microservices. 151 | - **Kafka:** Implemented for handling real-time data streams and message processing. 152 | - **Docker/Kubernetes:** Deployed and managed containerized applications for scalable and consistent environments. 153 | 154 | # L2 MindGate 155 | 156 | 1. **Can you describe a project you have worked on?** 157 | 158 | **Answer:** 159 | - Provide an overview of the project, including its objectives, technology stack, and your role. 160 | - Mention key features or functionalities, any challenges faced, and how they were overcome. 161 | 162 | 2. **How do you scale your project?** 163 | 164 | **Answer:** 165 | - Describe the strategies you use for scaling, such as load balancing, database optimization, caching, or microservices architecture. 166 | - Explain how you ensure the application can handle increased traffic or data volume. 167 | 168 | 3. **How do you analyze code for performance and quality?** 169 | 170 | **Answer:** 171 | - Mention tools and techniques used, such as code reviews, static analysis tools, profiling, and performance testing. 172 | - Explain how you identify and address bottlenecks or issues in the code. 173 | 174 | 4. **Which version of Spring Boot and Java have you used in your project?** 175 | 176 | **Answer:** 177 | - Specify the versions of Spring Boot and Java used. 178 | - Explain why you chose these versions and how they fit with your project requirements. 179 | 180 | 5. **Why did you choose this company?** 181 | 182 | **Answer:** 183 | - Discuss what attracted you to the company, such as its reputation, culture, projects, or growth opportunities. 184 | - Mention how your goals and skills align with the company’s mission and values. 185 | 186 | 6. **Have you used threads in your project? If so, how?** 187 | 188 | **Answer:** 189 | - Provide examples of how you used threads, such as for parallel processing, improving performance, or handling concurrent tasks. 190 | - Describe any challenges related to thread management and how you addressed them. 191 | 192 | 7. **Why do you use `ExecutorService` in your projects?** 193 | 194 | **Answer:** 195 | - Explain the benefits of using `ExecutorService`, such as managing thread pools, simplifying concurrent task execution, and improving resource management. 196 | - Discuss how it helps avoid issues related to manual thread management. 197 | 198 | 8. **Is it possible to solve tasks without using `ExecutorService`?** 199 | 200 | **Answer:** 201 | - Explain that while tasks can be solved without `ExecutorService` using raw threads, `ExecutorService` provides a more efficient and manageable approach. 202 | - Discuss the potential difficulties of manual thread management and how `ExecutorService` simplifies concurrency. 203 | 204 | 9. **How do you ensure code quality and maintainability in your projects?** 205 | 206 | **Answer:** 207 | - Talk about practices such as code reviews, adherence to coding standards, writing unit tests, and using design patterns. 208 | - Mention tools and processes that help maintain code quality over time. 209 | 210 | 10. **How do you handle version control and collaboration in your projects?** 211 | 212 | **Answer:** 213 | - Describe your version control strategy, such as branching, merging, and pull requests. 214 | - Explain how you use collaboration tools and practices to work effectively with your team. 215 | 216 | # HR 217 | 1. BASICS,SALARY & LOCATION .... 218 | -------------------------------------------------------------------------------- /Axis/Axis.md: -------------------------------------------------------------------------------- 1 | # Axis L1 2 | ### 1. What are streams in Java, and how are they used? 3 | 4 | **Answer:** 5 | 6 | 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. 7 | 8 | - **Key Features:** 9 | - **Functional Operations:** Streams support operations like `filter`, `map`, `reduce`, `collect`, and `forEach` that can be chained together. 10 | - **Lazy Evaluation:** Intermediate operations are lazily evaluated, meaning computations are deferred until a terminal operation is invoked. 11 | - **Parallel Processing:** Streams can be processed in parallel to leverage multi-core processors. 12 | 13 | **Example Usage:** 14 | 15 | ```java 16 | import java.util.Arrays; 17 | import java.util.List; 18 | import java.util.stream.Collectors; 19 | 20 | public class StreamExample { 21 | public static void main(String[] args) { 22 | List words = Arrays.asList("apple", "banana", "cherry", "date"); 23 | List filteredWords = words.stream() 24 | .filter(word -> word.startsWith("b")) 25 | .map(String::toUpperCase) 26 | .collect(Collectors.toList()); 27 | System.out.println(filteredWords); // Output: [BANANA] 28 | } 29 | } 30 | ``` 31 | 32 | ### 2. Explain lambda expressions in Java with an example. 33 | 34 | **Answer:** 35 | 36 | Lambda expressions in Java provide a concise way to express instances of functional interfaces (interfaces with a single abstract method). They consist of a parameter list, an arrow (`->`), and a body. 37 | 38 | **Syntax:** 39 | 40 | ```java 41 | (parameters) -> expression 42 | ``` 43 | 44 | **Example:** 45 | 46 | ```java 47 | import java.util.Arrays; 48 | import java.util.List; 49 | 50 | public class LambdaExample { 51 | public static void main(String[] args) { 52 | List names = Arrays.asList("Alice", "Bob", "Charlie"); 53 | 54 | names.forEach(name -> System.out.println(name)); // Output: Alice Bob Charlie 55 | } 56 | } 57 | ``` 58 | 59 | In this example, `name -> System.out.println(name)` is a lambda expression that prints each name in the list. 60 | 61 | ### 3. What is reactive programming, and where is it used? 62 | 63 | **Answer:** 64 | 65 | Reactive programming is a programming paradigm that deals with asynchronous data streams and the propagation of changes. It allows systems to react to data changes or events in a non-blocking and efficient manner. 66 | 67 | **Use Cases:** 68 | - **Real-Time Systems:** Handling real-time data streams, such as stock market data or sensor data. 69 | - **User Interfaces:** Building responsive UIs that react to user inputs or data changes. 70 | - **Microservices:** Managing asynchronous communication between services and handling high-load data processing. 71 | 72 | **Key Libraries/Frameworks:** 73 | - **RxJava:** A library for composing asynchronous and event-based programs using observable sequences. 74 | - **Project Reactor:** A reactive programming library for building non-blocking applications on the JVM. 75 | 76 | ### 4. Describe the architecture of microservices and how services communicate with each other. 77 | 78 | **Answer:** 79 | 80 | **Architecture:** 81 | - **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. 82 | 83 | **Communication Methods:** 84 | - **HTTP/REST:** Services expose RESTful APIs over HTTP for communication. 85 | - **gRPC:** A high-performance, language-agnostic RPC framework. 86 | - **Message Brokers:** Services communicate asynchronously through message brokers like Kafka, RabbitMQ, or ActiveMQ. 87 | - **Service Discovery:** Tools like Eureka or Consul are used for locating services dynamically. 88 | 89 | **Example Diagram:** 90 | ``` 91 | +-------------------+ +-------------------+ 92 | | Service A | ---> | Service B | 93 | | (REST API) | | (Message Queue) | 94 | +-------------------+ +-------------------+ 95 | ``` 96 | 97 | ### 5. Explain the architecture of the Spring Framework and the role of the IoC container. 98 | 99 | **Answer:** 100 | 101 | **Architecture:** 102 | - **Core Container:** Provides the foundation for dependency injection (DI) and bean lifecycle management. 103 | - **AOP (Aspect-Oriented Programming):** Supports cross-cutting concerns like logging and transactions. 104 | - **Data Access/Integration:** Simplifies data access with JDBC and ORM support. 105 | - **Web:** Provides support for building web applications, including RESTful APIs. 106 | 107 | **IoC Container:** 108 | - **Role:** Manages the lifecycle and configuration of application objects (beans). It uses Dependency Injection (DI) to decouple the creation of objects from their usage. 109 | - **Types of IoC Containers:** `BeanFactory` (basic container) and `ApplicationContext` (more advanced container). 110 | 111 | **Example:** 112 | ```java 113 | import org.springframework.context.ApplicationContext; 114 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 115 | 116 | public class Main { 117 | public static void main(String[] args) { 118 | ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 119 | MyService myService = context.getBean(MyService.class); 120 | myService.performAction(); 121 | } 122 | } 123 | ``` 124 | 125 | ### 6. What is Docker, and how does it relate to Kubernetes? 126 | 127 | **Answer:** 128 | 129 | **Docker:** 130 | - **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. 131 | 132 | **Kubernetes:** 133 | - **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. 134 | 135 | **Example Workflow:** 136 | 1. **Develop:** Write application code and Dockerize it. 137 | 2. **Deploy:** Use Kubernetes to deploy and manage the Docker containers. 138 | 139 | ### 7. Explain the architecture of a Kafka cluster. 140 | 141 | **Answer:** 142 | 143 | **Architecture:** 144 | - **Brokers:** Kafka brokers store and manage data. Each broker handles a subset of partitions and replicas. 145 | - **Topics:** Data is organized into topics. Each topic can be divided into multiple partitions for parallel processing. 146 | - **Producers:** Publish messages to topics. 147 | - **Consumers:** Subscribe to topics and consume messages. 148 | - **Zookeeper:** Manages broker metadata, leader elections, and configuration. 149 | 150 | **Diagram:** 151 | ``` 152 | +-----------------+ +-----------------+ +-----------------+ 153 | | Kafka Broker | | Kafka Broker | | Kafka Broker | 154 | +-----------------+ +-----------------+ +-----------------+ 155 | | | | 156 | | | | 157 | +-----------------+ +-----------------+ +-----------------+ 158 | | Producer | | Consumer | | Zookeeper | 159 | +-----------------+ +-----------------+ +-----------------+ 160 | ``` 161 | 162 | ### 8. What is a Security Context in Spring Security, and how does it work? 163 | 164 | **Answer:** 165 | 166 | **Security Context:** 167 | - **Definition:** A Security Context is a container that holds the authentication and authorization information for the currently authenticated user. 168 | - **Usage:** It is stored in a `ThreadLocal` and provides access to the current user's roles and permissions. 169 | 170 | **How it Works:** 171 | 1. **Authentication:** Upon successful login, Spring Security creates a `SecurityContext` that holds an `Authentication` object. 172 | 2. **Authorization:** The `SecurityContext` is used throughout the application to check if the user has the necessary permissions to access resources. 173 | 174 | **Example:** 175 | ```java 176 | import org.springframework.security.core.Authentication; 177 | import org.springframework.security.core.context.SecurityContextHolder; 178 | 179 | public class SecurityUtils { 180 | public static String getCurrentUsername() { 181 | Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 182 | return auth != null ? auth.getName() : "Anonymous"; 183 | } 184 | } 185 | ``` 186 | 187 | ### 9. How do you implement JWT token-based authentication? 188 | 189 | **Answer:** 190 | 191 | **Implementation Steps:** 192 | 1. **Generate Token:** After successful authentication, generate a JWT token containing user details. 193 | 2. **Send Token:** Send the token to the client, typically in the response header. 194 | 3. **Authenticate Requests:** Include the token in the Authorization header of subsequent requests. Verify the token and extract user information. 195 | 196 | **Example Code (Java):** 197 | 198 | ```java 199 | import io.jsonwebtoken.Jwts; 200 | import io.jsonwebtoken.SignatureAlgorithm; 201 | 202 | public class JwtUtil { 203 | private static final String SECRET_KEY = "your-secret-key"; 204 | 205 | public static String generateToken(String username) { 206 | return Jwts.builder() 207 | .setSubject(username) 208 | .signWith(SignatureAlgorithm.HS256, SECRET_KEY) 209 | .compact(); 210 | } 211 | } 212 | ``` 213 | 214 | ### 10. How do you use salt and hash in JWT to secure tokens? 215 | 216 | **Answer:** 217 | 218 | **Salt and Hash:** 219 | - **Salt:** A random value added to the token before hashing to enhance security and prevent precomputed attacks. 220 | - **Hash:** A cryptographic function applied to the salted token to ensure its integrity. 221 | 222 | **Steps:** 223 | 1. **Generate Salt:** Create a unique salt for each token. 224 | 2. **Hash Token:** Combine the token with the salt and apply a hash function. 225 | 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. 226 | 227 | **Example Code (Java):** 228 | 229 | ```java 230 | import java.security.MessageDigest; 231 | import java.security.NoSuchAlgorithmException; 232 | import java.security.SecureRandom; 233 | 234 | public class TokenUtil { 235 | private static final SecureRandom random = new SecureRandom(); 236 | 237 | public static String generateSalt() { 238 | byte[] salt = new byte[16]; 239 | random.nextBytes(salt); 240 | return new String(salt); 241 | } 242 | 243 | public static String hashToken(String token, String salt) throws NoSuchAlgorithmException { 244 | MessageDigest md = MessageDigest.getInstance("SHA-256"); 245 | md.update((token + salt).getBytes()); 246 | byte[] hashedBytes = md.digest(); 247 | return new String(has 248 | 249 | hedBytes); 250 | } 251 | } 252 | ``` 253 | 254 | ### 11. Write a code to find the longest palindrome substring length in a string. 255 | 256 | **Answer:** 257 | 258 | Here is an example code to find the length of the longest palindrome substring: 259 | 260 | **Code:** 261 | 262 | ```java 263 | public class LongestPalindromeLength { 264 | 265 | private static int expandAroundCenter(String s, int left, int right) { 266 | while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { 267 | left--; 268 | right++; 269 | } 270 | return right - left - 1; 271 | } 272 | 273 | public static int longestPalindromeLength(String s) { 274 | if (s == null || s.length() == 0) return 0; 275 | 276 | int maxLength = 0; 277 | 278 | for (int i = 0; i < s.length(); i++) { 279 | int len1 = expandAroundCenter(s, i, i); // Odd length palindromes 280 | int len2 = expandAroundCenter(s, i, i + 1); // Even length palindromes 281 | int len = Math.max(len1, len2); 282 | maxLength = Math.max(maxLength, len); 283 | } 284 | 285 | return maxLength; 286 | } 287 | 288 | public static void main(String[] args) { 289 | String input = "babad"; 290 | System.out.println("Length of longest palindrome substring: " + longestPalindromeLength(input)); 291 | } 292 | } 293 | ``` 294 | 295 | **Example:** 296 | - **Input:** `"babad"` 297 | - **Output:** `3` (The longest palindromes are `"bab"` or `"aba"`, both with a length of 3) 298 | -------------------------------------------------------------------------------- /Infosis/InfosisInterview.md: -------------------------------------------------------------------------------- 1 | #Technical Round 2 | ## Self-Introduction and Project Explanation 3 | 4 | 1. **Self-introduction with a brief explanation about your project.** 5 | - *"Hello, I’m [Your Name]. I have been working in software development for [X] years, specializing in Java and React. Currently, I am involved in a project that focuses on developing a [brief description of the project]."* 6 | 7 | 2. **Have you developed any project for your referencing purpose?** 8 | - *"Yes, I have worked on several projects for reference, including [briefly mention training projects or key projects you’ve worked on]. These projects helped me enhance my skills in [mention technologies or areas]."* 9 | 10 | 3. **Explain about your developed project. (Follow-up questions based on the project)** 11 | - *"My recent project involved [describe the scope of your project]. It was designed to [mention key objectives or features]. We utilized technologies such as [mention technologies] to achieve [mention goals or results]."* 12 | 13 | 4. **How do you monitor your project?** 14 | - *"I use various tools like New Relic and Grafana for monitoring application performance and logs. Additionally, I rely on automated tests and CI/CD pipelines to ensure the project’s stability."* 15 | 16 | 5. **Which database did you use?** 17 | - *"I used SQL for managing relational data due to its robust features and performance advantages."* 18 | 19 | ## Java 20 | 1. **What is a class loader?** 21 | - *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.* 22 | 23 | 2. **What is the Object class?** 24 | - *The Object class is the root class of the Java class hierarchy. Every class in Java inherits from Object, and it provides basic methods like `toString()`, `equals()`, and `hashCode()`.* 25 | 26 | 3. **What are the equals and hashCode methods in the Object class?** 27 | - *`equals()` is used to compare two objects for equality, while `hashCode()` returns a unique integer for each object. These methods are used in collections like HashMap.* 28 | 29 | 4. **Explain encapsulation.** 30 | - *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.* 31 | 32 | 5. **Give a real-time example of encapsulation.** 33 | - *A real-time example is a bank account class. The account details (balance, account number) are private, and access is provided through public methods (deposit, withdraw) to ensure controlled and secure manipulation of the data.* 34 | 35 | 6. **Compare static block vs static method.** 36 | - *A static block is used for initializing static variables or performing some initialization when the class is first loaded. A static method, on the other hand, can be called without creating an instance of the class and can only access static members.* 37 | 38 | 7. **Does a static block execute first or does a constructor execute first?** 39 | - *A static block executes before a constructor. It runs when the class is first loaded, whereas the constructor is executed when an instance of the class is created.* 40 | 41 | 8. **If I remove static from the main method, will it work?** 42 | - *No, the `main` method must be static because it is the entry point for the JVM to start the application. Without `static`, the JVM cannot call the method.* 43 | 44 | 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}** 45 | ```java 46 | public class MoveZeros { 47 | public static void moveZeros(int[] arr) { 48 | int count = 0; // Count of non-zero elements 49 | for (int i = 0; i < arr.length; i++) { 50 | if (arr[i] != 0) { 51 | arr[count++] = arr[i]; // Move non-zero elements to the front 52 | } 53 | } 54 | while (count < arr.length) { 55 | arr[count++] = 0; // Fill remaining positions with zeros 56 | } 57 | } 58 | } 59 | ``` 60 | - *This code iterates through the array, moving all non-zero elements to the front. After that, it fills the remaining positions with zeros.* 61 | 62 | 10. **Class Inheritance Issue:** 63 | ```java 64 | class A { 65 | public void sum() {} 66 | } 67 | class B extends A { 68 | public void sum() {} 69 | } 70 | // class C extends A, B {} // Compilation error 71 | ``` 72 | - *Java does not support multiple inheritance directly. You need to refactor the code, perhaps using interfaces or abstract classes.* 73 | 74 | 11. **Interface Implementation Issue:** 75 | ```java 76 | interface A { 77 | void sum(); 78 | } 79 | interface B{ 80 | void sum(); 81 | } 82 | class C implements A, B { 83 | // which sum method i want to implemet 84 | } 85 | ``` 86 | - *In Java, when a class implements multiple interfaces that declare methods with the same name and signature, you only need to provide one implementation for that method in the class. This single implementation will be used for both interfaces.* 87 | ```java 88 | class C implements A, B { 89 | @Override 90 | public void sum() { 91 | // Single implementation of the sum method 92 | System.out.println("Sum method implemented in class C"); 93 | } 94 | } 95 | ``` 96 | 12. **What is a functional interface?** 97 | - *A functional interface is an interface with a single abstract method. They are used as the target type for lambda expressions and method references. Examples include `Runnable` and `Callable`.* 98 | 99 | 13. **Write code to find the second largest number in the array `[1, 2, 3, 4, 5, 2, 4]` using Java 8.** 100 | ```java 101 | import java.util.Arrays; 102 | import java.util.Comparator; 103 | 104 | public class SecondLargestNumber { 105 | public static void main(String[] args) { 106 | int[] a = {3, 6, 32, 1, 8, 5, 31, 22}; 107 | 108 | int secondLargest = Arrays.stream(a) 109 | .boxed() 110 | .sorted(Comparator.reverseOrder()) 111 | .distinct() 112 | .skip(1) 113 | .findFirst() 114 | .orElseThrow(() -> new IllegalArgumentException("Array must contain at least two distinct elements")); 115 | 116 | System.out.println("Second Largest Number: " + secondLargest); 117 | } 118 | } 119 | 120 | ``` 121 | - *This code first removes duplicates, sorts the array, and then retrieves the second last element.* 122 | 123 | 14. **What is a HashMap?** 124 | - *HashMap is a collection that stores key-value pairs. It allows for efficient retrieval of values based on their keys.* 125 | 126 | 15. **Can a HashMap key be null?** 127 | - *Yes, HashMap allows one null key and multiple null values.* 128 | 129 | 16. **Explain the internal working process of a HashMap.** 130 | - *HashMap uses an array of buckets to store key-value pairs. The hash code of the key determines the bucket in which the entry is stored. Collisions are handled by linking entries in the same bucket.* 131 | 132 | 17. **What is the new change in Java 8 hashCode?** 133 | - *Java 8 introduced improvements to the `hashCode` method, particularly in hash-based collections. For example, `HashMap` uses a balanced tree structure for high collision scenarios.* 134 | 135 | 18. **What is the default size of a HashMap?** 136 | - *The default initial capacity of a HashMap is 16 buckets.* 137 | 138 | 19. **Explain fail-safe and fail-fast iterators.** 139 | - *Fail-fast iterators immediately throw `ConcurrentModificationException` if the collection is modified during iteration. Fail-safe iterators, like those in `CopyOnWriteArrayList`, work on a copy of the collection and do not throw exceptions if the collection is modified.* 140 | 141 | -*[Reference code]* 142 | *Code Example for Fail-Fast Iterators:* 143 | ```java 144 | import java.util.ArrayList; 145 | import java.util.Iterator; 146 | import java.util.List; 147 | 148 | public class FailFastExample { 149 | public static void main(String[] args) { 150 | List list = new ArrayList<>(); 151 | list.add("A"); 152 | list.add("B"); 153 | list.add("C"); 154 | 155 | Iterator iterator = list.iterator(); 156 | 157 | // Modify the collection while iterating 158 | while (iterator.hasNext()) { 159 | String item = iterator.next(); 160 | System.out.println(item); 161 | list.add("D"); // This will cause ConcurrentModificationException 162 | } 163 | } 164 | } 165 | ``` 166 | *Code Example for Fail-Safe Iterators:* 167 | 168 | ```java 169 | import java.util.List; 170 | import java.util.concurrent.CopyOnWriteArrayList; 171 | 172 | public class FailSafeExample { 173 | public static void main(String[] args) { 174 | List list = new CopyOnWriteArrayList<>(); 175 | list.add("A"); 176 | list.add("B"); 177 | list.add("C"); 178 | 179 | for (String item : list) { 180 | System.out.println(item); 181 | list.add("D"); // This will not cause ConcurrentModificationException 182 | } 183 | 184 | // Print the list after modification 185 | System.out.println("List after modification: " + list); 186 | } 187 | } 188 | ``` 189 | 190 | ### Hibernate 191 | 1. **What is Hibernate?** 192 | - *Hibernate is an ORM (Object-Relational Mapping) framework that simplifies database interactions by mapping Java objects to database tables.* 193 | 194 | 2. **Does JPA implement Hibernate? (True or False and why)** 195 | - *False. JPA (Java Persistence API) is a specification for ORM in Java. Hibernate is an implementation of JPA.* 196 | 197 | 3. **If JDBC is there, why do we need Hibernate?** 198 | - *Hibernate provides a higher level of abstraction compared to JDBC. It handles complex database operations, caching, and object mapping more efficiently than raw JDBC.* 199 | 200 | 4. **Do you know SQL and NoSQL databases?** 201 | - *Yes, I am familiar with both SQL databases (e.g., PostgreSQL, MySQL) and NoSQL databases (e.g., MongoDB, Cassandra).* 202 | 203 | ### SQL 204 | 1. **What is the difference between HAVING and WHERE clause?** 205 | - *`WHERE` is used to filter rows before aggregation, while `HAVING` is used to filter groups after aggregation.* 206 | 207 | 2. **Can I use WHERE to filter a group of records?** 208 | - *No, `WHERE` filters rows, not groups. Use `HAVING` to filter groups.* 209 | 210 | 3. **What is an index in SQL?** 211 | - *An index is a database object that improves the speed of data retrieval operations on a table. It creates a separate data structure that allows for faster searches.* 212 | 213 | ### Spring Boot 214 | 1. **What is the difference between PUT and PATCH?** 215 | - *`PUT` is used to update an entire resource, while `PATCH` is used to update partial data of a resource.* 216 | 217 | 2. **Can we use PUT in place of POST? Will it work or not?** 218 | - *Yes, `PUT` can be used in place of `POST`, but they have different semantics. `PUT` is idempotent, meaning multiple identical requests have the same effect as a single request, while `POST` may result in different outcomes.* 219 | 220 | 3. **What is the difference between @RestController and @Controller?** 221 | - *`@RestController` is a specialized version of `@Controller` that combines `@Controller` and `@ResponseBody`, meaning it returns JSON/XML responses directly. `@Controller` is used for rendering views (like JSPs).* 222 | 223 | 4. **Why is REST API stateless?** 224 | - *REST APIs are stateless to ensure scalability and reliability. Each request from the client to the server must contain all the information needed to understand and process the request.* 225 | 226 | ### Additional Questions 227 | 228 | 1. **How do you know .NET?** 229 | - *[_____]* 230 | 231 | 2. **Can you give an example of where you have used all your technical skills?** 232 | - *[_____]* 233 | 234 | 235 | # Manager Round 236 | 237 | 1. **Can you provide a brief explanation of your project?** 238 | - *[your self].* 239 | 240 | 2. **What specific work did you do with ReactJS in your project?** 241 | - *I worked on creating reusable components, implementing form validation with Formik, and managing state using React’s Context API. I also optimized the application's performance by using React hooks like `useMemo` and `useCallback`, and implemented lazy loading for certain components to enhance loading times.* 242 | 243 | 3. **On a scale of 1 to 10, how would you rate yourself in Java, Spring Boot, and microservices?** 244 | - *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.* 245 | 246 | 4. **How did you learn .NET?** 247 | - *I learned .NET Core by working on a personal project and by following tutorials and courses available online. I also created content about .NET on my YouTube channel, which helped reinforce my learning by teaching the concepts to others. This approach allowed me to deepen my understanding and gain practical experience.* 248 | 249 | 5. **Which databases have you used in your projects?** 250 | - *I have used MySQL and H2 databases in my projects. MySQL was utilized for managing relational data due to its robustness and scalability, while H2 was used for in-memory data storage and testing purposes, which helped in speeding up the development and testing processes* 251 | 252 | 6. **What issues did you face in your first and second projects, and how did you overcome them?** 253 | - *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.* 254 | 255 | 7. **How have you improved the performance of your code?** 256 | - *I have improved code performance by profiling and identifying bottlenecks, optimizing algorithms and data structures, and implementing caching strategies. Additionally, I have refactored code for better readability and maintainability, which also contributes to improved performance and reduced complexity.* 257 | -------------------------------------------------------------------------------- /Synechron/Synechron.md: -------------------------------------------------------------------------------- 1 | 2 | ### 1. **Can you give a brief introduction about yourself, focusing on your recent projects and the technologies you’ve worked with?** 3 | 4 | *Answer:* 5 | "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." 6 | 7 | ### 2. **What are the key features introduced in Java 8?** 8 | 9 | *Answer:* 10 | - **Lambda Expressions:** Allows concise representation of anonymous functions. 11 | - **Functional Interfaces:** Interfaces with a single abstract method, used with lambda expressions. 12 | - **Streams API:** Enables functional-style operations on collections. 13 | - **Optional Class:** A container object that may or may not contain a non-null value. 14 | - **Default Methods:** Methods in interfaces with default implementations. 15 | - **Date and Time API:** Provides a comprehensive date-time library. 16 | 17 | ### 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.** 18 | 19 | *Answer:* 20 | 21 | ```java 22 | public class BankAccount { 23 | private double balance; 24 | 25 | public BankAccount(double balance) { 26 | this.balance = balance; 27 | } 28 | 29 | public void withdraw(double amount) throws InsufficientBalanceException { 30 | if (amount > balance) { 31 | throw new InsufficientBalanceException("Insufficient balance."); 32 | } else { 33 | balance -= amount; 34 | System.out.println("Withdrawal successful. Remaining balance: " + balance); 35 | } 36 | } 37 | 38 | public double getBalance() { 39 | return balance; 40 | } 41 | } 42 | 43 | class InsufficientBalanceException extends Exception { 44 | public InsufficientBalanceException(String message) { 45 | super(message); 46 | } 47 | } 48 | ``` 49 | 50 | ### 4. **Write a JUnit test case for the withdraw method you just implemented.** 51 | 52 | *Answer:* 53 | 54 | ```java 55 | import static org.junit.jupiter.api.Assertions.*; 56 | import org.junit.jupiter.api.Test; 57 | 58 | public class BankAccountTest { 59 | 60 | @Test 61 | public void testWithdrawSuccess() throws InsufficientBalanceException { 62 | BankAccount account = new BankAccount(1000.0); 63 | account.withdraw(500.0); 64 | assertEquals(500.0, account.getBalance()); 65 | } 66 | 67 | @Test 68 | public void testWithdrawFailure() { 69 | BankAccount account = new BankAccount(300.0); 70 | assertThrows(InsufficientBalanceException.class, () -> account.withdraw(500.0)); 71 | } 72 | } 73 | ``` 74 | 75 | ### 5. **Using Java 8 Streams, how would you find the frequency of each character in a string?** 76 | 77 | *Answer:* 78 | 79 | ```java 80 | import java.util.Map; 81 | import java.util.function.Function; 82 | import java.util.stream.Collectors; 83 | 84 | public class CharacterFrequency { 85 | public static void main(String[] args) { 86 | String str = "Java 8 Streams"; 87 | Map frequencyMap = str.chars() 88 | .mapToObj(c -> (char) c) 89 | .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 90 | 91 | System.out.println(frequencyMap); 92 | } 93 | } 94 | ``` 95 | 96 | ### 6. **Have you completed any certifications? If so, which ones, and how have they helped you in your career?** 97 | 98 | *Answer:* 99 | "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." 100 | 101 | ### 7. **Which framework are you using to write test cases in your projects?** 102 | 103 | *Answer:* 104 | "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." 105 | 106 | ### 8. **Can you explain the architecture and data flow of Spring MVC?** 107 | 108 | *Answer:* 109 | - **Model:** Represents the data and business logic. Managed by Spring, often using JPA entities. 110 | - **View:** The presentation layer that displays data. Implemented using technologies like JSP or Thymeleaf. 111 | - **Controller:** Handles incoming requests, processes them, and returns a view or data. Acts as an intermediary between Model and View. 112 | - **DispatcherServlet:** The central servlet that handles all incoming requests and routes them to appropriate controllers. 113 | - **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. 114 | 115 | ### 9. **How does JWT token-based authentication work?** 116 | 117 | *Answer:* 118 | - **User Authentication:** User logs in with credentials, and the server validates them. 119 | - **Token Generation:** Upon successful login, the server generates a JWT containing user information and signs it with a secret key. 120 | - **Token Storage:** The client stores the JWT, typically in local storage or cookies. 121 | - **Token Usage:** For subsequent requests, the client sends the JWT in the Authorization header. 122 | - **Token Validation:** The server verifies the token's signature and expiration. If valid, it processes the request; otherwise, it rejects it. 123 | 124 | ### 10. **Why is REST API considered stateless?** 125 | 126 | *Answer:* 127 | - 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. 128 | ### 11. Create a Spring Boot project using Spring Initializer. Implement two APIs (GET and POST) and handle exceptions in the project. 129 | #### **Project Structure** 130 | 131 | 1. **Controller** 132 | 2. **Service** 133 | 3. **Repository** 134 | 4. **Entity** 135 | 5. **Exception Handling** 136 | 6. **Application Properties** 137 | 138 | --- 139 | 140 | #### **1. Create a Spring Boot Project Using Spring Initializer** 141 | 142 | - **Go to Spring Initializer:** Open [Spring Initializr](https://start.spring.io/). 143 | - **Project Setup:** 144 | - **Project:** Maven Project 145 | - **Language:** Java 146 | - **Spring Boot Version:** 3.x.x 147 | - **Group:** `com.example` 148 | - **Artifact:** `demo` 149 | - **Name:** `demo` 150 | - **Package Name:** `com.example.demo` 151 | - **Packaging:** Jar 152 | - **Java Version:** 17 153 | - **Dependencies:** 154 | - **Spring Web** 155 | - **Spring Boot DevTools** 156 | - **Spring Data JPA** 157 | - **H2 Database** 158 | - **Generate the Project:** Click "Generate" to download the project as a ZIP file. 159 | - **Import into IDE:** Extract the ZIP file and import it into your IDE. 160 | 161 | --- 162 | 163 | #### **2. Project Code** 164 | 165 | #### **a. Entity** 166 | 167 | Create the `Student` entity class: 168 | 169 | ```java 170 | package com.example.demo.model; 171 | 172 | import jakarta.persistence.Entity; 173 | import jakarta.persistence.GeneratedValue; 174 | import jakarta.persistence.GenerationType; 175 | import jakarta.persistence.Id; 176 | import jakarta.validation.constraints.Min; 177 | 178 | @Entity 179 | public class Student { 180 | 181 | @Id 182 | @GeneratedValue(strategy = GenerationType.IDENTITY) 183 | private Long id; 184 | 185 | private String name; 186 | 187 | @Min(18) 188 | private int age; 189 | 190 | // Constructors, Getters, and Setters 191 | 192 | public Student() {} 193 | 194 | public Student(String name, int age) { 195 | this.name = name; 196 | this.age = age; 197 | } 198 | 199 | public Long getId() { 200 | return id; 201 | } 202 | 203 | public void setId(Long id) { 204 | this.id = id; 205 | } 206 | 207 | public String getName() { 208 | return name; 209 | } 210 | 211 | public void setName(String name) { 212 | this.name = name; 213 | } 214 | 215 | public int getAge() { 216 | return age; 217 | } 218 | 219 | public void setAge(int age) { 220 | this.age = age; 221 | } 222 | } 223 | ``` 224 | 225 | #### **b. Repository** 226 | 227 | Create the `StudentRepository` interface: 228 | 229 | ```java 230 | package com.example.demo.repository; 231 | 232 | import com.example.demo.model.Student; 233 | import org.springframework.data.jpa.repository.JpaRepository; 234 | 235 | public interface StudentRepository extends JpaRepository { 236 | } 237 | ``` 238 | 239 | #### **c. Service** 240 | 241 | Create the `StudentService` interface and its implementation: 242 | 243 | **StudentService Interface:** 244 | 245 | ```java 246 | package com.example.demo.service; 247 | 248 | import com.example.demo.model.Student; 249 | 250 | import java.util.List; 251 | 252 | public interface StudentService { 253 | Student saveStudent(Student student); 254 | List getAllStudents(); 255 | Student getStudentById(Long id); 256 | } 257 | ``` 258 | 259 | **StudentService Implementation:** 260 | 261 | ```java 262 | package com.example.demo.service.impl; 263 | 264 | import com.example.demo.model.Student; 265 | import com.example.demo.repository.StudentRepository; 266 | import com.example.demo.service.StudentService; 267 | import org.springframework.stereotype.Service; 268 | 269 | import java.util.List; 270 | 271 | @Service 272 | public class StudentServiceImpl implements StudentService { 273 | 274 | private final StudentRepository studentRepository; 275 | 276 | public StudentServiceImpl(StudentRepository studentRepository) { 277 | this.studentRepository = studentRepository; 278 | } 279 | 280 | @Override 281 | public Student saveStudent(Student student) { 282 | return studentRepository.save(student); 283 | } 284 | 285 | @Override 286 | public List getAllStudents() { 287 | return studentRepository.findAll(); 288 | } 289 | 290 | @Override 291 | public Student getStudentById(Long id) { 292 | return studentRepository.findById(id).orElse(null); 293 | } 294 | } 295 | ``` 296 | 297 | #### **d. Controller** 298 | 299 | Create the `StudentController` class: 300 | 301 | ```java 302 | package com.example.demo.controller; 303 | 304 | import com.example.demo.model.Student; 305 | import com.example.demo.service.StudentService; 306 | import org.springframework.http.HttpStatus; 307 | import org.springframework.http.ResponseEntity; 308 | import org.springframework.web.bind.annotation.*; 309 | 310 | import javax.validation.Valid; 311 | import java.util.List; 312 | 313 | @RestController 314 | @RequestMapping("/api/students") 315 | public class StudentController { 316 | 317 | private final StudentService studentService; 318 | 319 | public StudentController(StudentService studentService) { 320 | this.studentService = studentService; 321 | } 322 | 323 | @GetMapping 324 | public ResponseEntity> getAllStudents() { 325 | return new ResponseEntity<>(studentService.getAllStudents(), HttpStatus.OK); 326 | } 327 | 328 | @PostMapping 329 | public ResponseEntity createStudent(@Valid @RequestBody Student student) { 330 | return new ResponseEntity<>(studentService.saveStudent(student), HttpStatus.CREATED); 331 | } 332 | } 333 | ``` 334 | 335 | #### **e. Exception Handling** 336 | 337 | Create global exception handling for validation errors: 338 | 339 | ```java 340 | package com.example.demo.exception; 341 | 342 | import org.springframework.http.HttpStatus; 343 | import org.springframework.http.ResponseEntity; 344 | import org.springframework.web.bind.MethodArgumentNotValidException; 345 | import org.springframework.web.bind.annotation.ControllerAdvice; 346 | import org.springframework.web.bind.annotation.ExceptionHandler; 347 | 348 | import java.util.LinkedHashMap; 349 | import java.util.Map; 350 | 351 | @ControllerAdvice 352 | public class GlobalExceptionHandler { 353 | 354 | @ExceptionHandler(MethodArgumentNotValidException.class) 355 | public ResponseEntity> handleValidationException(MethodArgumentNotValidException ex) { 356 | Map errors = new LinkedHashMap<>(); 357 | ex.getBindingResult().getFieldErrors().forEach(error -> { 358 | errors.put(error.getField(), error.getDefaultMessage()); 359 | }); 360 | return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); 361 | } 362 | } 363 | ``` 364 | 365 | #### **f. Application Properties** 366 | 367 | Configure H2 database and server port in `application.properties`: 368 | 369 | ```properties 370 | server.port=8080 371 | spring.datasource.url=jdbc:h2:mem:testdb 372 | spring.datasource.driverClassName=org.h2.Driver 373 | spring.datasource.username=sa 374 | spring.datasource.password=password 375 | spring.h2.console.enabled=true 376 | spring.jpa.hibernate.ddl-auto=update 377 | ``` 378 | 379 | #### **g. Main Application Class** 380 | 381 | Your main application class should look like this: 382 | 383 | ```java 384 | package com.example.demo; 385 | 386 | import org.springframework.boot.SpringApplication; 387 | import org.springframework.boot.autoconfigure.SpringBootApplication; 388 | 389 | @SpringBootApplication 390 | public class DemoApplication { 391 | 392 | public static void main(String[] args) { 393 | SpringApplication.run(DemoApplication.class, args); 394 | } 395 | } 396 | ``` 397 | 398 | --- 399 | 400 | #### **3. Running the Application** 401 | 402 | 1. **Run** the application by executing the `main` method in the `DemoApplication` class. 403 | 2. **Test the APIs** using tools like Postman or `curl`: 404 | - **GET** `/api/students` - Retrieves all students. 405 | - **POST** `/api/students` - Creates a new student. Use JSON body like `{"name": "John Doe", "age": 22}`. 406 | 407 | --- 408 | -------------------------------------------------------------------------------- /LTIMindtree/LtiMindtree.md: -------------------------------------------------------------------------------- 1 | ### 1. **Brief explanation about your project and daily tasks.** 2 | 3 | In my current project, I am working on a [briefly describe the project’s purpose, such as "banking application that handles customer transactions and account management"]. My daily tasks involve designing and implementing microservices using Spring Boot, developing RESTful APIs, managing the database using JPA/Hibernate, writing unit tests with JUnit and Mockito, and deploying services to a cloud environment like AWS. I also participate in code reviews, pair programming, and daily stand-ups to ensure smooth progress. 4 | 5 | ### 2. **You mentioned you worked on microservices; can you elaborate?** 6 | 7 | Yes, I have experience in designing, developing, and deploying microservices. I have worked on breaking down a monolithic application into smaller, independent microservices that can be developed, deployed, and scaled independently. Each microservice handled a specific business capability and communicated with others through RESTful APIs or message queues. This architecture improved our system's scalability, maintainability, and fault tolerance. 8 | 9 | ### 3. **How do you handle fault tolerance in microservices?** 10 | 11 | Fault tolerance in microservices is achieved using several strategies, including implementing retries, fallbacks, and circuit breakers. We use libraries like Hystrix or Resilience4j to manage circuit breaking and timeouts, ensuring that the failure of one microservice does not cascade and affect the entire system. We also deploy services across multiple instances and use load balancers to distribute traffic, ensuring high availability. 12 | 13 | ### 4. **What is a circuit breaker in microservices?** 14 | 15 | A circuit breaker is a design pattern used to detect and handle failures in microservices. When a service fails or becomes unresponsive, the circuit breaker trips and stops further calls to the failing service. Instead, it returns a fallback response or an error message. This prevents the system from being overwhelmed by repeated attempts to call the failing service, helping to maintain overall stability. 16 | 17 | ### 5. **How do you manage retrying, timeouts, and circuit breakers in microservices?** 18 | 19 | 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. 20 | 21 | ### 6. **How do microservices communicate with each other?** 22 | 23 | Microservices communicate with each other using HTTP/REST, messaging queues, or RPC frameworks like gRPC. For RESTful communication, we use HTTP requests with JSON payloads. For asynchronous communication, we use messaging systems like Kafka or RabbitMQ. gRPC is used for efficient communication between services, especially when low latency and high throughput are required. 24 | 25 | ### 7. **What is gRPC?** 26 | 27 | gRPC is a high-performance, open-source RPC framework that allows microservices to communicate with each other efficiently. It uses Protocol Buffers (protobuf) for serializing structured data, which is more efficient than JSON. gRPC supports bi-directional streaming and is language-agnostic, allowing services written in different programming languages to communicate seamlessly. 28 | 29 | ### 8. **How do you transfer data efficiently between microservices?** 30 | 31 | To transfer data efficiently between microservices, we use lightweight data formats like Protocol Buffers (protobuf) with gRPC. We also ensure that only necessary data is transmitted by designing APIs with minimal payloads. Data compression and pagination techniques are also applied to manage large datasets effectively. 32 | 33 | ### 9. **What is event-driven processing in microservices?** 34 | 35 | Event-driven processing in microservices is an architectural pattern where services communicate and react to events rather than direct requests. When an event occurs (e.g., a user places an order), it is published to an event bus (e.g., Kafka). Other services subscribe to these events and perform their actions accordingly. This decouples services, allowing them to evolve independently and handle high traffic efficiently. 36 | 37 | ### 10. **Explain the CQRS pattern in microservices.** 38 | 39 | CQRS (Command Query Responsibility Segregation) is a design pattern where the read and write operations are separated into different models. The command model handles writes (modifications), while the query model handles reads (queries). This separation allows for optimizing each model independently, improving performance, and simplifying the design, especially in complex systems. 40 | 41 | ### 11. **What is the difference between synchronous and asynchronous communication in microservices?** 42 | 43 | - **Synchronous Communication:** Involves direct communication between microservices where the caller waits for a response before proceeding. It is typically implemented using REST APIs or RPC. This method can lead to tight coupling and latency issues. 44 | 45 | - **Asynchronous Communication:** Involves message-based communication where the caller sends a message and continues its processing without waiting for a response. It is typically implemented using messaging systems like Kafka or RabbitMQ. This method promotes loose coupling and better scalability. 46 | 47 | ### 12. **What is load balancing, and how do you handle it in microservices?** 48 | 49 | 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. 50 | 51 | ### 13. **How do you monitor and measure metrics in microservices?** 52 | 53 | We monitor and measure metrics in microservices using tools like Prometheus, Grafana, and ELK stack (Elasticsearch, Logstash, Kibana). Metrics like CPU usage, memory consumption, request rates, response times, and error rates are tracked. Logs and traces are also collected using tools like Zipkin or Jaeger for distributed tracing. Alerts are set up to notify the team of any issues. 54 | 55 | ### 14. **How do you handle a high number of incoming requests in microservices, and how do you track and manage them?** 56 | 57 | To handle a high number of incoming requests, we scale microservices horizontally by deploying multiple instances behind a load balancer. We implement rate limiting, caching, and use of efficient data stores. To track and manage requests, we use distributed tracing tools like Jaeger and Prometheus for monitoring, which helps in identifying bottlenecks and optimizing performance. 58 | 59 | ### 15. **Can you give some examples of design patterns?** 60 | 61 | Some common design patterns used in microservices and general software development include: 62 | - **Singleton:** Ensures a class has only one instance. 63 | - **Factory Method:** Creates objects without specifying the exact class. 64 | - **Observer:** Allows objects to subscribe and receive notifications from another object. 65 | - **Strategy:** Enables selecting an algorithm's behavior at runtime. 66 | - **Decorator:** Adds behavior to objects dynamically. 67 | 68 | ### 16. **Write a code example of the Singleton design pattern in Java.** 69 | 70 | ```java 71 | public class Singleton { 72 | // Private static instance of the class 73 | private static Singleton instance; 74 | 75 | // Private constructor to prevent instantiation 76 | private Singleton() {} 77 | 78 | // Public method to provide access to the instance 79 | public static synchronized Singleton getInstance() { 80 | if (instance == null) { 81 | instance = new Singleton(); 82 | } 83 | return instance; 84 | } 85 | } 86 | ``` 87 | 88 | ### 17. **If two threads access the same class simultaneously, how do you manage it?** 89 | 90 | To manage concurrent access by multiple threads, we use synchronization. In the Singleton pattern, the `getInstance()` method is synchronized to ensure only one thread can access it at a time, preventing multiple instances from being created. 91 | 92 | ### 18. **How can you give the option to clone a Singleton class?** 93 | 94 | To allow cloning in a Singleton class while maintaining the singleton property, override the `clone()` method and throw a `CloneNotSupportedException`. 95 | 96 | ```java 97 | @Override 98 | protected Object clone() throws CloneNotSupportedException { 99 | throw new CloneNotSupportedException("Cannot clone a singleton object"); 100 | } 101 | ``` 102 | 103 | ### 19. **What is the `Cloneable` interface in Java?** 104 | 105 | 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`. 106 | 107 | ### 20. **Write code to handle exceptions like `ArithmeticException` for division by zero.** 108 | 109 | ```java 110 | public class DivisionExample { 111 | public static void main(String[] args) { 112 | try { 113 | int result = divide(10, 0); 114 | System.out.println("Result: " + result); 115 | } catch (ArithmeticException e) { 116 | System.out.println("Error: Division by zero is not allowed."); 117 | } 118 | } 119 | 120 | public static int divide(int a, int b) { 121 | return a / b; 122 | } 123 | } 124 | ``` 125 | 126 | ### 21. **Why do we use the `Optional` class in Java?** 127 | 128 | 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. 129 | 130 | ### 22. **Which methods are available in the `Optional` class?** 131 | 132 | Some commonly used methods in the `Optional` class include: 133 | - `of(T value)`: Creates an Optional with the specified value. 134 | - `ofNullable(T value)`: Creates an Optional that may be empty if the value is `null`. 135 | - `empty()`: Returns an empty Optional. 136 | - `get()`: Returns the value if present, otherwise throws an exception. 137 | - `isPresent()`: Checks if the value is present. 138 | - `ifPresent(Consumer action)`: Executes the given action if the value is present. 139 | 140 | 141 | - `orElse(T other)`: Returns the value if present, otherwise returns the provided default value. 142 | - `orElseThrow(Supplier exceptionSupplier)`: Returns the value if present, otherwise throws the provided exception. 143 | 144 | ### 23. **How did you optimize a project when migrating from Java 7 to Java 8? Provide a full project explanation.** 145 | 146 | When migrating from Java 7 to Java 8, we optimized our project by leveraging Java 8's new features: 147 | - **Lambda Expressions:** Replaced anonymous inner classes with lambda expressions, making the code more concise and readable. 148 | - **Streams API:** Used streams to process collections in a more functional style, improving performance and reducing boilerplate code. 149 | - **Optional:** Replaced null checks with `Optional` to handle `null` values more safely. 150 | - **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. 151 | 152 | 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. 153 | 154 | ### 24. **What classes are available in the Java Time API?** 155 | 156 | Some of the key classes in the Java Time API (`java.time` package) include: 157 | - `LocalDate`: Represents a date (year, month, day) without time. 158 | - `LocalTime`: Represents a time (hours, minutes, seconds, nanoseconds) without a date. 159 | - `LocalDateTime`: Combines `LocalDate` and `LocalTime` into a single date-time object. 160 | - `ZonedDateTime`: Represents a date-time with a time zone. 161 | - `Instant`: Represents a specific point in time, typically used for timestamps. 162 | - `Duration`: Represents a duration or amount of time. 163 | - `Period`: Represents a date-based amount of time, such as "2 years, 3 months, and 4 days." 164 | 165 | ### 25. **How do you schedule tasks in Java?** 166 | 167 | Tasks in Java can be scheduled using the `ScheduledExecutorService` or the `Timer` class. The `ScheduledExecutorService` is preferred as it provides more flexibility and allows for multiple tasks to be scheduled concurrently. 168 | 169 | ```java 170 | import java.util.concurrent.Executors; 171 | import java.util.concurrent.ScheduledExecutorService; 172 | import java.util.concurrent.TimeUnit; 173 | 174 | public class TaskScheduler { 175 | public static void main(String[] args) { 176 | ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 177 | 178 | scheduler.scheduleAtFixedRate(() -> { 179 | System.out.println("Task executed at: " + System.currentTimeMillis()); 180 | }, 0, 1, TimeUnit.SECONDS); 181 | } 182 | } 183 | ``` 184 | 185 | ### 26. **What are parallel streams in Java?** 186 | 187 | 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. 188 | 189 | ### 27. **What are the advantages and disadvantages of parallel streams?** 190 | 191 | **Advantages:** 192 | - **Performance Improvement:** Parallel streams can significantly speed up the processing of large data sets by utilizing multiple CPU cores. 193 | - **Simplified Concurrency:** Parallel streams abstract away the complexities of writing concurrent code, making it easier to implement parallelism. 194 | 195 | **Disadvantages:** 196 | - **Overhead:** For small data sets, the overhead of parallelization might outweigh the benefits, leading to worse performance than sequential streams. 197 | - **Non-Deterministic Order:** Parallel streams do not guarantee the order of processing, which can be problematic if order matters. 198 | - **Complexity in Debugging:** Debugging parallel streams can be more challenging than sequential code due to the concurrency involved. 199 | --------------------------------------------------------------------------------