{"id":25693921,"url":"https://github.com/c-akhil/java-interview-guide","last_synced_at":"2026-04-18T12:32:37.522Z","repository":{"id":276757383,"uuid":"930192279","full_name":"c-akhil/java-interview-guide","owner":"c-akhil","description":"A comprehensive repository for Java and Spring Boot interview preparation. This repository includes detailed questions and answers covering Core Java Concepts, OOP, Collections \u0026 Data Structures, Java 8 \u0026 Functional Programming, Spring Boot \u0026 Microservices, and Spring Boot Security \u0026 Optimization","archived":false,"fork":false,"pushed_at":"2025-02-10T08:34:51.000Z","size":16,"stargazers_count":12,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-24T23:49:19.901Z","etag":null,"topics":["api-development","backend-development","collections","functional-programming","interview-questions","java","java-interview","microservices","software-development","spring-boot","technical-interview"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/c-akhil.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-02-10T08:27:15.000Z","updated_at":"2025-02-19T16:59:28.000Z","dependencies_parsed_at":"2025-02-10T09:30:58.927Z","dependency_job_id":"9c50363a-8b55-49a5-a7ce-b8e5d3335cf7","html_url":"https://github.com/c-akhil/java-interview-guide","commit_stats":null,"previous_names":["c-akhil/java-interview-guide"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/c-akhil/java-interview-guide","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/c-akhil%2Fjava-interview-guide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/c-akhil%2Fjava-interview-guide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/c-akhil%2Fjava-interview-guide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/c-akhil%2Fjava-interview-guide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/c-akhil","download_url":"https://codeload.github.com/c-akhil/java-interview-guide/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/c-akhil%2Fjava-interview-guide/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31969661,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-18T00:39:45.007Z","status":"online","status_checked_at":"2026-04-18T02:00:07.018Z","response_time":103,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-development","backend-development","collections","functional-programming","interview-questions","java","java-interview","microservices","software-development","spring-boot","technical-interview"],"created_at":"2025-02-24T23:49:21.473Z","updated_at":"2026-04-18T12:32:37.490Z","avatar_url":"https://github.com/c-akhil.png","language":null,"readme":"# 🚀 Java \u0026 Spring Boot Interview Preparation\n\nThis document covers essential interview questions for Java and Spring Boot in the exact order provided.\n\n---\n\n## 📌 Core Java Concepts\n\n### 1. What are the main features of Java?\nJava is a high-level, object-oriented programming language known for:\n- **Platform Independence**: Java programs run on any platform with a JVM (\"Write Once, Run Anywhere\").\n- **Object-Oriented**: Supports principles like encapsulation, abstraction, inheritance, and polymorphism.\n- **Automatic Memory Management**: Uses a garbage collector to manage memory.\n- **Multithreading**: Enables concurrent execution of two or more parts of a program.\n- **Robustness**: Provides strong type checking, exception handling, and eliminates issues like explicit pointer manipulation.\n- **Security**: Includes features like bytecode verification, a security manager, and class loaders.\n- **Performance**: Utilizes a Just-In-Time (JIT) compiler for efficient execution.\n\n---\n\n### 2. What is the difference between JDK, JRE, and JVM?\n| Feature | JDK (Java Development Kit) | JRE (Java Runtime Environment) | JVM (Java Virtual Machine) |\n|---------|----------------------------|-------------------------------|----------------------------|\n| **Definition** | A complete toolkit for Java development (includes the compiler and other tools). | Provides the environment required to run Java applications. | An engine that executes Java bytecode. |\n| **Components** | Contains the JRE, compiler (`javac`), and debugging tools. | Includes the JVM and core libraries. | Converts `.class` files into machine-specific code. |\n| **Usage** | Used for both developing and running Java applications. | Needed only for running Java applications. | Works behind the scenes to run Java programs. |\n\n---\n\n### 3. How does memory management work in Java?\nJava manages memory automatically with:\n- **Heap Memory**: Where all the class instances and objects are stored.\n- **Stack Memory**: Stores method frames, including local variables and method calls.\n- **Metaspace (formerly PermGen)**: Stores class metadata.\n- **Garbage Collector (GC)**: Periodically reclaims memory from objects that are no longer in use.\n\n---\n\n### 4. What is the difference between `==` and `.equals()`?\n| Operator    | Purpose                                           | Example                                    |\n|-------------|---------------------------------------------------|--------------------------------------------|\n| `==`        | Checks if two object references point to the same memory location. | `s1 == s2` returns `false` for two distinct objects with the same content. |\n| `.equals()` | Compares the actual content of the objects (if overridden properly). | `s1.equals(s2)` returns `true` if the contents are identical. |\n\n*Example:*\n```java\nString s1 = new String(\"Hello\");\nString s2 = new String(\"Hello\");\nSystem.out.println(s1 == s2);      // false\nSystem.out.println(s1.equals(s2)); // true\n```\n### 5. What is the purpose of final, finally, and finalize()?\nKeyword\tPurpose\nfinal\tUsed to declare constants, prevent method overriding, and stop inheritance.\nfinally\tA block that always executes after try-catch blocks, used for cleanup code.\nfinalize()\tA method called by the garbage collector before an object is destroyed (deprecated in newer Java versions).\n## 📌 OOP in Java\n### 6. What are the four main principles of OOP?\nEncapsulation: Bundling data and methods that operate on the data within a single unit (class).\nAbstraction: Hiding complex implementation details and exposing only the necessary parts.\nInheritance: Creating new classes from existing ones, promoting code reuse.\nPolymorphism: Allowing methods to perform different tasks based on the object that invokes them.\n### 7. What is method overloading vs method overriding?\nAspect\tMethod Overloading\tMethod Overriding\nDefinition\tMultiple methods in the same class with the same name but different parameters.\tA subclass provides a specific implementation for a method already defined in its superclass.\nScope\tWithin the same class.\tAcross a superclass and its subclass.\nReturn Type\tCan vary (subject to rules).\tMust be the same (or covariant) as in the superclass.\n### 8. What is abstraction, and how is it implemented?\nAbstraction involves hiding the complex implementation details and exposing only the necessary functionality. It can be implemented using:\n\nAbstract Classes: Classes declared with the abstract keyword that can include both abstract and concrete methods.\nInterfaces: Define methods that must be implemented by a class; Java 8+ allows default and static methods.\n### 9. What are access modifiers in Java?\nAccess modifiers determine the visibility of classes, methods, and variables:\n\nprivate: Accessible only within the same class.\ndefault (no modifier): Accessible within the same package.\nprotected: Accessible within the same package and subclasses.\npublic: Accessible from any other class.\n\n| Modifier  | Class | Package | Subclass | World |\n|-----------|-------|---------|----------|-------|\n| `private` | ✅ | ❌ | ❌ | ❌ |\n| `default` | ✅ | ✅ | ❌ | ❌ |\n| `protected` | ✅ | ✅ | ✅ | ❌ |\n| `public` | ✅ | ✅ | ✅ | ✅ |\n\n### 10. What is the difference between an interface and an abstract class?\nFeature\tAbstract Class\tInterface\nMethods\tCan have both abstract and concrete methods.\tAll methods are abstract by default (Java 8+ allows default and static methods).\nFields\tCan have instance variables.\tOnly constants (implicitly public static final).\nInheritance\tSupports single inheritance.\tSupports multiple inheritance (a class can implement multiple interfaces).\n## 📌 Collections \u0026 Data Structures\n### 11. What are key interfaces in Java Collections?\nKey interfaces include:\n\nList: An ordered collection (e.g., ArrayList, LinkedList).\nSet: A collection that does not allow duplicate elements (e.g., HashSet, TreeSet).\nQueue: Typically used to hold elements prior to processing (e.g., LinkedList, PriorityQueue).\nMap: An object that maps keys to values (e.g., HashMap, TreeMap).\n### 12. How does HashMap work internally?\nBuckets: Uses an array of buckets where each bucket is essentially a linked list (or a balanced tree if many collisions occur).\nHashing: The key's hashCode() is used to compute an index for the bucket.\nCollision Handling: When multiple keys hash to the same bucket, they are stored in a list or tree structure within that bucket.\n### 13. What is the difference between ArrayList and LinkedList?\nAspect\tArrayList\tLinkedList\nUnderlying Structure\tDynamic array.\tDoubly linked list.\nAccess Time\tFast random access (O(1)).\tSlower random access (O(n)).\nInsertion/Deletion\tSlower for middle operations (requires shifting elements).\tFaster insertions and deletions (especially at the beginning or end).\n### 14. How do you remove duplicate elements from a list?\nYou can remove duplicates by converting the list into a set (which doesn’t allow duplicates) and then back to a list. For example:\n\njava\n```\nList\u003cInteger\u003e list = Arrays.asList(1, 2, 2, 3, 4, 4);\nSet\u003cInteger\u003e set = new HashSet\u003c\u003e(list);\nList\u003cInteger\u003e uniqueList = new ArrayList\u003c\u003e(set);\n```\nOr using Java 8 Streams:\n\njava\n```\nList\u003cInteger\u003e uniqueList = list.stream()\n                               .distinct()\n                               .collect(Collectors.toList());\n```\n### 15. What is a ConcurrentHashMap, and why is it useful?\nConcurrentHashMap is a thread-safe version of HashMap that:\n\nAllows concurrent read and write operations.\nUses a segmented locking mechanism (or finer-grained locks in Java 8+) to reduce contention.\nIs useful in multi-threaded applications where high concurrency is needed.\n## 📌 Java 8 \u0026 Functional Programming\n### 16. What are lambda expressions in Java?\nLambda expressions are a way to write anonymous functions (i.e., functions without a name) that can be treated as objects. They provide a clear and concise way to represent one method interface using an expression.\n\njava\n```\nRunnable r = () -\u003e System.out.println(\"Hello, Lambda!\");\n```\n### 17. What is the Streams API, and why is it useful?\nThe Streams API enables functional-style operations on streams of elements (such as collections). It allows for operations like filtering, mapping, and reducing without modifying the underlying data source. It also supports parallel processing.\n\njava\n```\nList\u003cInteger\u003e numbers = Arrays.asList(1, 2, 3, 4, 5);\nList\u003cInteger\u003e squares = numbers.stream()\n                               .map(n -\u003e n * n)\n                               .collect(Collectors.toList());\n```\n### 18. What is the difference between map(), flatMap(), and filter()?\nmap(): Applies a given function to each element of the stream and returns a stream of the results.\nflatMap(): Similar to map(), but each element is replaced with a stream of new values, and then all the streams are flattened into a single stream.\nfilter(): Evaluates each element against a predicate and returns a stream that includes only those elements that match the predicate.\n### 19. What are Optional classes, and how are they useful?\nThe Optional class is a container that may or may not contain a non-null value. It helps in avoiding NullPointerException and provides methods to safely handle the presence or absence of a value.\n\njava\n```\nOptional\u003cString\u003e optionalName = Optional.ofNullable(getName());\noptionalName.ifPresent(name -\u003e System.out.println(\"Name: \" + name));\n```\n### 20. What are default and static methods in interfaces?\nDefault Methods: Allow an interface to provide a default implementation so that classes implementing the interface are not forced to implement them.\nStatic Methods: Belong to the interface itself rather than any instance, and can be invoked without an implementation class.\njava\n```\npublic interface MyInterface {\n    default void defaultMethod() {\n        System.out.println(\"Default method\");\n    }\n    static void staticMethod() {\n        System.out.println(\"Static method\");\n    }\n}\n```\n## 📌 Spring Boot \u0026 Microservices\n### 21. What is Spring Boot, and why is it popular?\nSpring Boot is a framework that simplifies the development of Spring-based applications by:\n\nProviding auto-configuration to reduce manual setup.\nOffering embedded servers (e.g., Tomcat, Jetty) for standalone applications.\nReducing boilerplate code and easing dependency management.\nBeing production-ready with built-in metrics, health checks, and externalized configuration.\n\n### 22. What are key annotations in Spring Boot?\n\nSome of the key annotations include:\n\n@SpringBootApplication: Enables auto-configuration and component scanning.\n\n@RestController: Marks a class as a controller where every method returns a domain object rather than a view.\n\n@Service, @Repository, @Component: Stereotype annotations to indicate the role of a class.\n\n@Autowired: Enables automatic dependency injection.\n\n### 23. How does Spring Boot handle database connections?\nSpring Boot simplifies database connectivity by:\n\nUsing Spring Data JPA or JDBC templates.\nAuto-configuring data sources and connection pools (HikariCP is the default).\nAllowing configuration via application.properties or application.yml files:\nproperties\n```\nspring.datasource.url=jdbc:mysql://localhost:3306/mydb\nspring.datasource.username=root\nspring.datasource.password=root\n```\n### 24. What is dependency injection?\nDependency Injection (DI) is a design pattern where an object’s dependencies are provided by an external entity (like the Spring container) rather than being created by the object itself. This promotes loose coupling and easier testing.\n\n### 25. What is the purpose of @Transactional?\nThe @Transactional annotation is used to define the scope of a single database transaction. It ensures that all operations within the annotated method are executed within a transaction boundary. If any operation fails, the transaction is rolled back, ensuring data integrity (ACID properties).\n\n## 📌 Spring Boot \u0026 API Development\n### 26. What is REST, and how does Spring Boot implement it?\nREST (Representational State Transfer) is an architectural style for designing networked applications. Spring Boot implements RESTful web services using:\n\n@RestController for creating controllers.\nMapping annotations such as @RequestMapping, @GetMapping, and @PostMapping.\nJSON (or XML) as the data interchange format.\n### 27. What is the difference between @GetMapping and @PostMapping?\nAnnotation\tHTTP Method\tPurpose\n@GetMapping\tGET\tRetrieves data from the server.\n@PostMapping\tPOST\tSubmits data to the server.\n### 28. How does Spring Boot handle authentication? (JWT, OAuth)\nSpring Boot, along with Spring Security, supports various authentication methods:\n\nJWT (JSON Web Token): A stateless, token-based authentication method.\nOAuth 2.0: An industry-standard protocol for authorization that can also handle authentication. These methods secure REST endpoints and manage user sessions or stateless interactions.\n### 29. What are the best practices for designing REST APIs?\nSome best practices include:\n\nUse the correct HTTP methods (GET, POST, PUT, DELETE).\nUse meaningful and resource-based URIs.\nImplement proper error handling and status codes.\nSupport pagination, filtering, and sorting.\nDocument the API (e.g., using Swagger/OpenAPI).\nSecure endpoints using authentication and authorization.\n### 30. How does Spring Boot handle pagination?\nSpring Boot integrates with Spring Data, which provides pagination support through the Pageable interface. Repository methods can return a Page\u003cT\u003e:\n\njava\n```\nPage\u003cUser\u003e users = userRepository.findAll(PageRequest.of(0, 10));\n```\n## 📌 Spring Boot \u0026 Microservices Architecture\n### 31. What are microservices, and how does Spring Boot support them?\nMicroservices are an architectural style where an application is composed of small, independent services. Spring Boot supports microservices by simplifying service creation, configuration, and deployment. It works well with Spring Cloud to handle service discovery, configuration, and inter-service communication.\n\n### 32. What is the difference between monolithic and microservices architecture?\nMonolithic Architecture: The entire application is built as a single, unified unit.\nMicroservices Architecture: The application is divided into independent, loosely coupled services that can be developed, deployed, and scaled independently.\n### 33. What is API Gateway, and how does it work?\nAn API Gateway is a single entry point for all client requests to a set of microservices. It handles routing, load balancing, authentication, rate limiting, and other cross-cutting concerns. Examples include Netflix Zuul and Spring Cloud Gateway.\n\n### 34. What is Eureka Server, and how does service discovery work?\nEureka Server is a service registry from Netflix OSS. It allows microservices to register themselves so that they can be discovered by other services. Clients query Eureka to locate instances of a service dynamically.\n\n### 35. What is Circuit Breaker, and how does it improve resilience?\nThe Circuit Breaker pattern prevents cascading failures by stopping the flow of requests to a failing service after a threshold is reached. It temporarily “opens” the circuit, allowing fallback methods to be invoked until the service recovers. Libraries like Hystrix or Resilience4j provide this functionality.\n\n## 📌 Spring Boot Security \u0026 Optimization\n### 36. How does Spring Boot implement security best practices?\nSpring Boot integrates with Spring Security to implement security best practices such as:\n\nSecure authentication and authorization.\nProtection against common vulnerabilities (e.g., CSRF, XSS).\nSecure password storage and encryption.\nIntegration with OAuth2 and JWT for token-based security.\n### 37. How can you improve Spring Boot performance?\nPerformance improvements can include:\n\nImplementing caching mechanisms (e.g., Redis, EhCache).\nOptimizing database queries and using efficient connection pooling.\nEnabling asynchronous processing where appropriate.\nConfiguring GZIP compression for responses.\nTuning embedded server settings (e.g., thread pools).\n### 38. What is rate limiting, and why is it useful?\nRate limiting restricts the number of requests a client can make within a specified time period. This helps prevent abuse, ensures fair usage, and protects against Denial-of-Service (DoS) attacks.\n\n### 39. What is CORS, and how does Spring Boot handle it?\nCORS (Cross-Origin Resource Sharing) is a security feature that restricts how resources on a web server can be requested from another domain. Spring Boot can handle CORS using:\n\nThe @CrossOrigin annotation on controllers.\nGlobal configuration through a WebMvcConfigurer bean.\n### 40. How does Spring Boot integrate with Kubernetes \u0026 Docker?\nSpring Boot applications can be containerized using Docker. Once containerized, these applications can be orchestrated using Kubernetes for scaling, load balancing, and managing deployments. Spring Boot’s production-ready features (such as health checks and externalized configuration) make it well-suited for cloud-native environments.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fc-akhil%2Fjava-interview-guide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fc-akhil%2Fjava-interview-guide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fc-akhil%2Fjava-interview-guide/lists"}