Docsity

Core Java and Problem Solving Exercises, Study Guides, Projects, Research of Java Programming

Toggle sidebar
bg1
Java, Spring Boot, Microservices, and Angular
Interview Preparation Guide
August 2025
Contents
1 Core Java & OOPs 4
1.1 Difference between String, StringBuilder, and StringBuffer . . . . . . . . . . . 4
1.2 Difference between .equals() method and == operator . . . . . . . . . . . . . . 5
1.3 Difference between method overloading and method overriding . . . . . . . 5
1.4 WhatisSingletonclass? ................................ 5
1.5 CreateSingletonclass.................................. 5
1.6 What is thread safety and how do you ensure thread-safe classes? . . . . . . 6
1.7 How does HashMap work internally? . . . . . . . . . . . . . . . . . . . . . . . . 6
1.8 Difference: HashMap vs Hashtable vs ConcurrentHashMap . . . . . . . . . . 6
1.9 How does HashMap work with Employee object as key? . . . . . . . . . . . . 6
1.10 What is immutability and how does it help in concurrency? . . . . . . . . . . 7
1.11 What is volatile and synchronized? . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.12 How many ways can an object be created in Java? . . . . . . . . . . . . . . . . 7
1.13 What is the use of ResponseEntity? . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.14 What is meant by functional interfaces? . . . . . . . . . . . . . . . . . . . . . . 8
1.15 How do functional interfaces work? . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.16 What is dependency injection and its types? . . . . . . . . . . . . . . . . . . . . 8
1.17 Difference between IOC and Dependency Injection . . . . . . . . . . . . . . . 9
1.18 How many ways to achieve dependency injection and which is best? . . . . 9
1.19 @Primary vs @Qualifier — which takes priority? . . . . . . . . . . . . . . . . . 9
1.20 How to create beans manually? . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.21 What is the difference between @RestController and @Controller? . . . . . 9
1.22 What is @SpringBootApplication annotation? . . . . . . . . . . . . . . . . . . . 10
1.23 What are stereotype annotations in Spring Boot? . . . . . . . . . . . . . . . . . 10
1.24Whatispathvariable? ................................. 10
1.25 What is the default server in Spring Boot? . . . . . . . . . . . . . . . . . . . . . 10
1.26 What is the default port in Spring Boot? . . . . . . . . . . . . . . . . . . . . . . 10
2 Java 8 Features 11
2.1 Java 8 features used in your project . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2 What is a lambda expression? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3 Write code using lambda expression . . . . . . . . . . . . . . . . . . . . . . . . 11
2.4 WhatisStreamAPI? .................................. 11
2.5 Intermediate vs terminal operations in streams . . . . . . . . . . . . . . . . . 12
2.6 List of intermediate and terminal methods . . . . . . . . . . . . . . . . . . . . 12
2.7 Why Java introduced default and static methods in interfaces . . . . . . . . . 12
2.8 How to create an immutable class in Java . . . . . . . . . . . . . . . . . . . . . 12
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26

Partial preview of the text

Download Core Java and Problem Solving Exercises and more Study Guides, Projects, Research Java Programming in PDF only on Docsity!

Java, Spring Boot, Microservices, and Angular

8.8 Common use cases of HTTP interceptors...................... 34

8.9 What is GraphQL and how does it compare to REST?.............. 34

8.10 Use Apollo in Angular to fetch GraphQL data................... 34

8.11 Differences: BehaviorSubject, Subject, ReplaySubject.............. 35

8.12 Explain: switchMap, mergeMap, concatMap, exhaustMap........... 35

8.13 Design a semantic HTML navigation menu.................... 35

8.14 List 5 semantic HTML tags and their uses..................... 35

8.15 Fetch API data and display in a table........................ 35

8.16 Search by name using Reactive Form........................ 36

8.17 Error handling on API failure............................. 36

8.18 Flatten a nested array.................................. 36

9 Miscellaneous 36

9.1 What do you know about ISO8583?......................... 36

9.2 How do Angular applications interact with backend APIs?........... 36

9.3 How do you clone code from Git and commit changes?............. 37

9.4 How to resolve merge conflicts?........................... 37

9.5 Daily Git commands you use............................. 37

10 Additional Frequently Asked Questions 37

10.1 What is the difference between checked and unchecked exceptions?.... 37

10.2 What is the purpose of @Autowired annotation in Spring?........... 37

10.3 What is the Circuit Breaker pattern in microservices?.............. 37

Introduction

This document provides answers and examples for Java, Spring Boot, Microservices, and

Angular interview questions, organized by topic. Each question includes a beginner-

friendly explanation and a practical example, suitable for interview preparation. Addi-

tional common questions are included at the end.

1 Core Java & OOPs

1.1 Difference between String, StringBuilder, and StringBuffer

Answer: String is immutable, creating new objects for modifications. StringBuilder is

mutable, non-thread-safe, and fast. StringBuffer is mutable, thread-safe, but slower due

to synchronization.

1 public class StringExample { 2 public static void main(String[] args) { 3 String str = ”Hello”; 4 str += ” World”; // New object 5 System.out.println(str); // Hello World 6 StringBuilder sb = new StringBuilder(”Hello”); 7 sb.append(” World”); 8 System.out.println(sb); // Hello World 9 StringBuffer sbf = new StringBuffer(”Hello”); 10 sbf.append(” World”); 11 System.out.println(sbf); // Hello World 12 } 13 }

1.2 Difference between .equals() method and == operator

Answer: == compares object references or primitive values. .equals() compares object

content, customizable for classes.

1 public class EqualsExample { 2 public static void main(String[] args) { 3 String s1 = new String(”Hello”); 4 String s2 = new String(”Hello”); 5 System.out.println(s1 == s2); // false 6 System.out.println(s1.equals(s2)); // true 7 String s3 = ”Hello”; 8 String s4 = ”Hello”; 9 System.out.println(s3 == s4); // true 10 } 11 }

1.3 Difference between method overloading and method overriding

Answer: Overloading uses different parameters in the same class (compile-time). Over-

riding redefines a method in a subclass (runtime).

1 class Animal { 2 void sound() { System.out.println(”Animal sound”); } 3 } 4 class Dog extends Animal { 5 void sound() { System.out.println(”Dog barks”); } // Override 6 void sound(String type) { System.out.println(”Dog ” + type); } // Overload 7 } 8 public class PolymorphismExample { 9 public static void main(String[] args) { 10 Dog dog = new Dog(); 11 dog.sound(); // Dog barks 12 dog.sound(”growls”); // Dog growls 13 } 14 }

1.4 What is Singleton class?

Answer: Ensures one instance with global access, used for shared resources.

1.5 Create Singleton class

Answer: Uses private constructor, static instance, and static access method.

1 public class Singleton { 2 private static Singleton instance; 3 private Singleton() {} 4 public static synchronized Singleton getInstance() { 5 if (instance == null) instance = new Singleton(); 6 return instance; 7 } 8 public static void main(String[] args) { 9 Singleton s1 = Singleton.getInstance(); 10 Singleton s2 = Singleton.getInstance(); 11 System.out.println(s1 == s2); // true 12 }

1 import java.util.HashMap; 2 class Employee { 3 int id; String name; 4 Employee(int id, String name) { this.id = id; this.name = name; } 5 @Override public int hashCode() { return id * 31 + name.hashCode(); } 6 @Override public boolean equals(Object obj) { 7 if (!(obj instanceof Employee)) return false; 8 Employee other = (Employee) obj; 9 return id == other.id && name.equals(other.name); 10 } 11 } 12 public class HashMapEmployee { 13 public static void main(String[] args) { 14 HashMap<Employee, String> map = new HashMap<>(); 15 Employee e1 = new Employee(1, ”Alice”); 16 map.put(e1, ”Developer”); 17 System.out.println(map.get(new Employee(1, ”Alice”))); // Developer 18 } 19 }

1.10 What is immutability and how does it help in concurrency?

Answer: Immutability prevents state changes, ensuring thread safety without synchro-

nization.

1 public final class ImmutableClass { 2 private final int value; 3 public ImmutableClass(int value) { this.value = value; } 4 public int getValue() { return value; } 5 public static void main(String[] args) { 6 ImmutableClass obj = new ImmutableClass(42); 7 System.out.println(obj.getValue()); // 42 8 } 9 }

1.11 What is volatile and synchronized?

Answer: volatile ensures variable visibility; synchronized ensures mutual exclusion.

1 public class VolatileSynchronized { 2 private volatile boolean running = true; 3 public synchronized void update() { running = false; } 4 public static void main(String[] args) throws InterruptedException { 5 VolatileSynchronized vs = new VolatileSynchronized(); 6 new Thread(() -> { while (vs.running) {} System.out.println(”Stopped”); }).start(); 7 Thread.sleep(1000); 8 vs.update(); 9 } 10 }

1.12 How many ways can an object be created in Java?

Answer: Using new, Class.forName(), clone(), deserialization, factory methods.

1 public class ObjectCreation { 2 public static void main(String[] args) throws Exception { 3 ObjectCreation obj1 = new ObjectCreation(); 4 ObjectCreation obj2 = (ObjectCreation) Class.forName(”ObjectCreation”). newInstance(); 5 } 6 }

1.13 What is the use of ResponseEntity?

Answer: Represents HTTP response with status, headers, and body.

1 import org.springframework.http.; 2 import org.springframework.web.bind.annotation.; 3 @RestController 4 public class ResponseEntityExample { 5 @GetMapping(”/user”) 6 public ResponseEntity getUser() { 7 return new ResponseEntity<>(”User found”, HttpStatus.OK); 8 } 9 }

1.14 What is meant by functional interfaces?

Answer: Interfaces with one abstract method, used with lambdas.

1 @FunctionalInterface 2 interface MyFunction { void apply(String s); } 3 public class FunctionalInterfaceExample { 4 public static void main(String[] args) { 5 MyFunction func = s -> System.out.println(s); 6 func.apply(”Hello”); // Hello 7 } 8 }

1.15 How do functional interfaces work?

Answer: Enable functional programming via lambda expressions.

1 import java.util.function.Consumer; 2 public class FunctionalInterfaceWork { 3 public static void main(String[] args) { 4 Consumer consumer = s -> System.out.println(s); 5 consumer.accept(”Hello Consumer”); // Hello Consumer 6 } 7 }

1.16 What is dependency injection and its types?

Answer: Provides dependencies externally. Types: constructor, setter, field injection.

1 import org.springframework.stereotype.Component; 2 import org.springframework.beans.factory.annotation.Autowired; 3 @Component 4 class Service { public void serve() { System.out.println(”Serving”); } } 5 @Component

6 public String getView() { return ”view”; } 7 } 8 @RestController 9 public class MyRestController { 10 @GetMapping(”/api”) 11 public String getData() { return ”Data”; } 12 }

1.22 What is @SpringBootApplication annotation?

Answer: Combines @EnableAutoConfiguration, @ComponentScan, @Configuration.

1 import org.springframework.boot.; 2 import org.springframework.boot.autoconfigure.; 3 @SpringBootApplication 4 public class Application { 5 public static void main(String[] args) { 6 SpringApplication.run(Application.class, args); 7 } 8 }

1.23 What are stereotype annotations in Spring Boot?

Answer: @Component, @Service, @Repository, @Controller mark classes for scanning.

1 import org.springframework.stereotype.*; 2 @Service 3 public class MyService { 4 public void serve() { System.out.println(”Service”); } 5 }

1.24 What is path variable?

Answer: @PathVariable extracts URL path values.

1 import org.springframework.web.bind.annotation.*; 2 @RestController 3 public class PathVariableExample { 4 @GetMapping(”/user/{id}”) 5 public String getUser(@PathVariable int id) { 6 return ”User ID: ” + id; 7 } 8 }

1.25 What is the default server in Spring Boot?

Answer: Tomcat.

1 // Run Application.java to start Tomcat

1.26 What is the default port in Spring Boot?

Answer: 8080.

1 // Access http://localhost:

2 Java 8 Features

2.1 Java 8 features used in your project

Answer: Lambda expressions, Stream API, Optional, default/static methods, forEach.

1 import java.util.*; 2 public class Java8Features { 3 public static void main(String[] args) { 4 List list = Arrays.asList(”A”, ”B”); 5 list.forEach(s -> System.out.println(s)); // A, B 6 } 7 }

2.2 What is a lambda expression?

Answer: Concise function representation: (params) -> expression.

1 import java.util.*; 2 public class LambdaExample { 3 public static void main(String[] args) { 4 List list = Arrays.asList(”A”, ”B”); 5 list.forEach(s -> System.out.println(s)); // A, B 6 } 7 }

2.3 Write code using lambda expression

1 import java.util.*; 2 public class LambdaCode { 3 public static void main(String[] args) { 4 List numbers = Arrays.asList(1, 2, 3); 5 numbers.forEach(n -> System.out.println(n * 2)); // 2, 4, 6 6 } 7 }

2.4 What is Stream API?

Answer: Processes collections functionally with operations like filter, map, collect.

1 import java.util.; 2 import java.util.stream.; 3 public class StreamExample { 4 public static void main(String[] args) { 5 List numbers = Arrays.asList(1, 2, 3, 4); 6 List evens = numbers.stream() 7 .filter(n -> n % 2 == 0) 8 .collect(Collectors.toList()); 9 System.out.println(evens); // [2, 4] 10 } 11 }

2.9 How to use groupingBy() in streams

Answer: Groups elements by a classifier.

1 import java.util.; 2 import java.util.stream.; 3 public class GroupingByExample { 4 public static void main(String[] args) { 5 List names = Arrays.asList(”Alice”, ”Bob”, ”Adam”); 6 Map<Character, List> grouped = names.stream() 7 .collect(Collectors.groupingBy(s -> s.charAt(0))); 8 System.out.println(grouped); // {A=[Alice, Adam], B=[Bob]} 9 } 10 }

2.10 How to create an Optional of an employee object

Answer: Wraps object to handle null cases.

1 import java.util.Optional; 2 class Employee { 3 String name; 4 Employee(String name) { this.name = name; } 5 } 6 public class OptionalExample { 7 public static void main(String[] args) { 8 Optional emp = Optional.of(new Employee(”Alice”)); 9 System.out.println(emp.get().name); // Alice 10 } 11 }

2.11 Use Java 8 streams to remove duplicates from a list

1 import java.util.; 2 import java.util.stream.; 3 public class RemoveDuplicates { 4 public static void main(String[] args) { 5 List numbers = Arrays.asList(1, 2, 2, 3); 6 List unique = numbers.stream().distinct().collect(Collectors. toList()); 7 System.out.println(unique); // [1, 2, 3] 8 } 9 }

2.12 Find 3rd highest salary using Java 8 streams

1 import java.util.; 2 import java.util.stream.; 3 class Employee { 4 double salary; 5 Employee(double salary) { this.salary = salary; } 6 double getSalary() { return salary; } 7 } 8 public class ThirdHighestSalary { 9 public static void main(String[] args) { 10 List employees = Arrays.asList(

11 new Employee(50000), new Employee(70000), new Employee(60000) 12 ); 13 double thirdHighest = employees.stream() 14 .map(Employee::getSalary) 15 .distinct() 16 .sorted(Comparator.reverseOrder()) 17 .skip(2) 18 .findFirst() 19 .orElse(0.0); 20 System.out.println(thirdHighest); // 0.0 (if <3 salaries) 21 } 22 }

3 Spring Boot & Microservices

3.1 How do you configure different environments in Spring Boot?

Answer: Use application-{profile}.properties and spring.profiles.active.

1 # application-dev.properties 2 server.port=

1 import org.springframework.context.annotation.*; 2 @Profile(”dev”) 3 @Component 4 public class DevConfig {}

3.2 What is a Spring Boot profile and how did you use it?

Answer: Profiles activate environment-specific configurations.

1 # application.properties 2 spring.profiles.active=dev

3.3 What is exception handling and what is an advisor?

Answer: Exception handling manages errors; advisor combines AOP advice and point-

cut.

1 import org.springframework.http.; 2 import org.springframework.web.bind.annotation.; 3 @RestController 4 public class ExceptionController { 5 @ExceptionHandler(NullPointerException.class) 6 public ResponseEntity handleNPE() { 7 return new ResponseEntity<>(”Error”, HttpStatus.BAD_REQUEST); 8 } 9 }

3.4 How does @Transactional annotation work?

Answer: Manages transactions, ensuring atomicity.

3.11 When to use synchronous vs asynchronous communication

Answer: Synchronous for immediate responses; asynchronous for decoupled systems.

1 import org.springframework.kafka.annotation.*; 2 @Service 3 public class KafkaConsumer { 4 @KafkaListener(topics = ”myTopic”) 5 public void consume(String message) { 6 System.out.println(message); 7 } 8 }

3.12 What is Kafka and how have you implemented it?

Answer: Distributed messaging system for event-driven architectures.

1 import org.springframework.kafka.core.; 2 import org.springframework.stereotype.; 3 @Service 4 public class KafkaProducer { 5 @Autowired 6 private KafkaTemplate<String, String> kafkaTemplate; 7 public void sendMessage(String msg) { 8 kafkaTemplate.send(”myTopic”, msg); 9 } 10 }

3.13 How have you used Spring Security in your project?

Answer: Secures applications via authentication/authorization.

1 import org.springframework.context.annotation.; 2 import org.springframework.security.config.annotation.web.builders.; 3 @Configuration 4 @EnableWebSecurity 5 public class SecurityConfig { 6 @Bean 7 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 8 http.authorizeRequests().anyRequest().authenticated().and().httpBasic() ; 9 return http.build(); 10 } 11 }

3.14 What is JWT security and how have you used it?

Answer: Token-based authentication using JSON Web Tokens.

1 import io.jsonwebtoken.*; 2 public class JwtExample { 3 public String generateToken(String username) { 4 return Jwts.builder() 5 .setSubject(username) 6 .signWith(SignatureAlgorithm.HS512, ”secret”) 7 .compact(); 8 }

3.15 What are the things to consider while developing REST APIs?

Answer: RESTful principles, versioning, error handling, security, documentation.

1 import org.springframework.http.; 2 import org.springframework.web.bind.annotation.; 3 @RestController 4 @RequestMapping(”/api/v1”) 5 public class ApiController { 6 @GetMapping(”/users”) 7 public ResponseEntity<List> getUsers() { 8 return ResponseEntity.ok(Arrays.asList(”Alice”, ”Bob”)); 9 } 10 }

3.16 Difference between PUT, POST, and PATCH

Answer: POST creates, PUT updates entire resource, PATCH updates partially.

1 import org.springframework.web.bind.annotation.*; 2 @RestController 3 public class UserController { 4 @PostMapping(”/users”) public String createUser() { return ”Created”; } 5 @PutMapping(”/users/{id}”) public String updateUser(@PathVariable int id) { return ”Updated”; } 6 @PatchMapping(”/users/{id}”) public String patchUser(@PathVariable int id ) { return ”Patched”; } 7 }

3.17 API versioning strategies

Answer: URI versioning, query parameters, headers, media types.

1 import org.springframework.web.bind.annotation.*; 2 @RestController 3 @RequestMapping(”/api/v1”) 4 public class VersionedController { 5 @GetMapping(”/users”) 6 public String getUsers() { return ”Version 1”; } 7 }

3.18 What is idempotency and why is it critical?

Answer: Ensures multiple identical requests have the same effect, critical for reliability.

1 import org.springframework.web.bind.annotation.*; 2 @RestController 3 public class IdempotentController { 4 @PutMapping(”/users/{id}”) 5 public ResponseEntity updateUser(@PathVariable int id) { 6 return ResponseEntity.ok(”Updated”); 7 } 8 }

3.23 How to handle exceptions in Spring Boot

Answer: Use @ExceptionHandler or @ControllerAdvice.

1 import org.springframework.http.; 2 import org.springframework.web.bind.annotation.; 3 @ControllerAdvice 4 public class GlobalExceptionHandler { 5 @ExceptionHandler(Exception.class) 6 public ResponseEntity handleException(Exception e) { 7 return new ResponseEntity<>(”Error: ” + e.getMessage(), HttpStatus. INTERNAL_SERVER_ERROR); 8 } 9 }

3.24 How to create global exceptions and what annotations are used

Answer: Use @ControllerAdvice and @ExceptionHandler.

1 // See above

3.25 How to exclude classes from component scan

Answer: Use exclude or excludeFilters in @ComponentScan.

1 import org.springframework.context.annotation.*; 2 @ComponentScan(basePackages = ”com.example”, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MyClass.class)) 3 @Configuration 4 public class AppConfig {}

3.26 How does component scan work?

Answer: Scans packages for stereotype-annotated classes, registering them as beans.

1 import org.springframework.stereotype.*; 2 @Component 3 public class MyComponent {}

3.27 What is the most challenging task you’ve done?

Answer: Optimizing a microservice for high load with caching.

1 import org.springframework.cache.annotation.*; 2 @Service 3 public class OptimizedService { 4 @Cacheable(”data”) 5 public String getData() { return ”Data”; } 6 }

3.28 What are the top 3 performance bottlenecks in microservices?

Answer: Network latency, database queries, resource management.

1 import org.springframework.data.jpa.repository.*; 2 public interface UserRepository extends JpaRepository<User, Long> { 3 @Query(”SELECT u FROM User u WHERE u.active = true”) 4 List findActiveUsers(); 5 }

3.29 How do you monitor microservices?

Answer: Use Prometheus, Grafana, or Spring Actuator.

1 # application.properties 2 management.endpoints.web.exposure.include=*

3.30 How do you ensure system resiliency under high load?

Answer: Use circuit breakers, retries, load balancing, caching.

1 // See Circuit Breaker (Question 6)

3.31 What is centralized configuration and secrets management?

Answer: Centralized configuration (Spring Cloud Config); secrets (Vault).

1 # application.properties 2 spring.config.import=configserver:http://config-server

3.32 What is service discovery (Eureka/Consul)?

Answer: Dynamically locates services.

1 import org.springframework.cloud.netflix.eureka.*; 2 @SpringBootApplication 3 @EnableEurekaClient 4 public class Application {}

3.33 Inter-service communication: Feign vs RestTemplate vs WebClient

Answer: RestTemplate (synchronous), WebClient (reactive), Feign (declarative).

1 import feign.*; 2 @FeignClient(name = ”user-service”) 3 interface UserClient { 4 @GetMapping(”/users”) 5 List getUsers(); 6 }

3.34 Circuit Breaker and Retry: Resilience4j

Answer: Circuit Breaker prevents failures; Retry attempts failed operations.

1 import io.github.resilience4j.circuitbreaker.annotation.; 2 import io.github.resilience4j.retry.annotation.; 3 @Service 4 public class ResilientService { 5 @CircuitBreaker(name = ”myService”)