91. What is the WebClient in Spring and how does it differ from RestTemplate?
- WebClient and RestTemplate are identical — they both make synchronous HTTP calls to REST APIs
- WebClient is Spring’s modern, reactive, non-blocking HTTP client supporting both sync and async calls; RestTemplate is the older, synchronous (blocking) HTTP client — WebClient is the recommended replacement for all new code
- WebClient only works in reactive Spring WebFlux applications and cannot be used with Spring MVC
- RestTemplate is faster than WebClient for all types of HTTP operations
Answer : B Explanation: HTTP clients for calling external REST APIs from Spring: RestTemplate (legacy, synchronous): blocks the calling thread until the response arrives. getForObject(“/users/{id}”, User.class, 1L) — simple but blocking. @Deprecated as of Spring 5.0 for new code. Still works, not removed. Good for simple use cases in existing codebases. WebClient (modern, Spring 5+): non-blocking, reactive API (built on Project Reactor). Can be used synchronously: webClient.get().uri(“/users/{id}”, 1L).retrieve().bodyToMono(User.class).block() — .block() makes it synchronous. Or asynchronously: .subscribe(user -> …) — non-blocking. Part of spring-boot-starter-webflux or spring-boot-starter-web (both work). Creating WebClient: WebClient client = WebClient.builder().baseUrl(“http://api.example.com”).defaultHeader(“Accept”,”application/json”).build(). Chaining: client.get().uri(“/users/{id}”, id).retrieve().onStatus(HttpStatus::is4xxClientError, r -> Mono.error(new RuntimeException())).bodyToMono(User.class). Exchange vs retrieve: retrieve() throws on error status. exchange() gives full ResponseSpec (headers, status, body). Feign Client (declarative): @FeignClient(name=”user-service”, url=”${user.service.url}”) interface — Spring generates implementation. Cleanest API for inter-service calls. Recommended: WebClient for new code. Feign Client for microservice-to-microservice calls with service discovery. RestTemplate only for maintaining existing code.
92. What is Spring Boot’s @Scheduled annotation and how is it used?
- @Scheduled is used to schedule Spring bean initialization order at application startup
- @Scheduled marks a method to be executed automatically at fixed intervals or according to a cron expression — enabling scheduled task execution like cleaning up sessions, sending reports, or syncing data
- @Scheduled can only be used with millisecond intervals and does not support cron expressions
- @Scheduled requires a separate scheduling server component like Quartz to function
Answer : B Explanation: Spring Scheduling enables automatic task execution without external tools. Setup: @EnableScheduling on @SpringBootApplication class (or any @Configuration class). @Scheduled options: @Scheduled(fixedRate=5000) — execute every 5000ms (5 seconds), regardless of previous execution time. @Scheduled(fixedDelay=5000) — wait 5 seconds AFTER previous execution completes. @Scheduled(initialDelay=10000, fixedRate=5000) — wait 10 seconds before first execution, then every 5 seconds. @Scheduled(cron=”0 0 9 * * MON-FRI”) — cron expression: run at 9:00 AM Monday to Friday. Cron format: second minute hour day-of-month month day-of-week. Example: @Component public class ReportScheduler { @Scheduled(cron=”0 0 0 * * ?”) // every midnight public void generateDailyReport() { … } }. Thread model: by default, scheduled tasks run in a single thread — if one task runs slow, it delays others. Configure thread pool: @Bean public TaskScheduler taskScheduler() { return new ThreadPoolTaskScheduler(); // configure pool size }. Concurrency: @Scheduled methods are NOT concurrent by default — Spring waits for completion before next execution with fixedDelay. For concurrent execution, use @Async along with @Scheduled. Distributed scheduling: for clustered environments, use ShedLock (prevents multiple instances running the same scheduled task simultaneously) or Quartz Scheduler.
93. What is the difference between @Controller and @RestController in Spring?
- @RestController creates REST APIs; @Controller cannot handle HTTP requests at all
- @Controller returns view names (for server-side rendering with Thymeleaf/JSP); @RestController = @Controller + @ResponseBody — every method return value is automatically serialized as the HTTP response body (JSON/XML), bypassing view resolution
- @Controller is for older Spring applications; @RestController only works in Spring Boot
- @RestController and @Controller both return views — the difference is response encoding only
Answer : B Explanation: @Controller (for MVC web applications with server-side rendering): @Controller public class UserController { @GetMapping(“/users”) public String listUsers(Model model) { model.addAttribute(“users”, userService.findAll()); return “users/list”; // returns VIEW NAME → ViewResolver finds users/list.html } }. Returns a String view name. Spring’s ViewResolver resolves it to a template file. @RestController (for REST APIs returning data): @RestController @RequestMapping(“/api/users”) public class UserApiController { @GetMapping public List<User> getUsers() { return userService.findAll(); // List<User> auto-serialized to JSON } }. @RestController = @Controller + @ResponseBody. @ResponseBody tells Spring: “Write the return value directly to the HTTP response body — don’t resolve a view.” Jackson serializes the return value to JSON automatically. Mixing both in one controller: @Controller can use @ResponseBody on individual methods. @RequestMapping(“/users”) public class UserController { @GetMapping(path=”/view”) public String showPage(Model model) { return “userView”; } // returns view @GetMapping(path=”/api”, produces=”application/json”) @ResponseBody public List<User> getUsers() { return users; } // returns JSON }. In modern applications: use @RestController for API controllers, @Controller for Thymeleaf-based server-rendered views (if using SSR), or exclusively @RestController with a separate React/Angular frontend.
94. What is Global Exception Handling in Spring Boot using @ControllerAdvice?
- Global exception handling in Spring Boot means catching all exceptions in a single try-catch in the main method
- @ControllerAdvice is a Spring annotation that defines a global exception handler class — @ExceptionHandler methods within it intercept exceptions thrown by any controller, allowing centralized error handling with consistent error response format instead of try-catch in every controller
- @ControllerAdvice only handles database-related exceptions and ignores web layer exceptions
- Global exception handling requires registering a custom Filter in the servlet container configuration
Answer : B Explanation: @ControllerAdvice + @ExceptionHandler provides centralized, consistent exception handling: Without global handler: every controller method needs try-catch, inconsistent error responses, code duplication. With @RestControllerAdvice (= @ControllerAdvice + @ResponseBody): @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ErrorResponse handleNotFound(ResourceNotFoundException ex) { return new ErrorResponse(404, ex.getMessage(), LocalDateTime.now()); } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ValidationErrorResponse handleValidation(MethodArgumentNotValidException ex) { List<String> errors = ex.getBindingResult().getFieldErrors().stream().map(e -> e.getField()+”: “+e.getDefaultMessage()).collect(Collectors.toList()); return new ValidationErrorResponse(400, “Validation failed”, errors); } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ErrorResponse handleGeneral(Exception ex) { log.error(“Unexpected error”, ex); return new ErrorResponse(500, “Internal server error”, LocalDateTime.now()); } }. ErrorResponse is a custom DTO class with the error fields. Custom exceptions: @ResponseStatus(HttpStatus.NOT_FOUND) on the exception class itself sets the status. ResponseEntityExceptionHandler: Spring’s base class for @ControllerAdvice that handles common Spring MVC exceptions (MethodArgumentNotValidException, HttpMessageNotReadableException, etc.) — extend it and override specific methods. ProblemDetail (Spring 6+): RFC 7807 standard error response format built into Spring.
95. What is the difference between HashMap, LinkedHashMap, and TreeMap in Java?
- LinkedHashMap stores more entries than HashMap; TreeMap stores fewer entries than both
- HashMap has no ordering guarantee (O(1) operations); LinkedHashMap maintains insertion order (O(1) operations); TreeMap maintains sorted key order (O(log n) operations, keys must be Comparable)
- All three maps are identical in behavior — only the class names differ for legacy reasons
- TreeMap is always the best choice because it provides both ordering and fast access simultaneously
Answer : B Explanation: Three commonly used Map implementations: HashMap: backed by a hash table. get/put/remove: O(1) average, O(n) worst case (all keys in same bucket — very rare with good hashCode()). No ordering guarantee — iteration order may change between runs (and after resizes). Allows one null key and multiple null values. Use when: ordering doesn’t matter, maximum performance needed. Most commonly used Map. LinkedHashMap: extends HashMap, adds a doubly linked list maintaining order. Options: Insertion order (default) — iterates in the order elements were inserted. Access order — recently accessed elements come last (useful for LRU cache). get/put/remove: O(1) — same as HashMap, slight memory overhead for linked list. Use when: you need a Map with predictable iteration order. Implement LRU cache: new LinkedHashMap<>(16, 0.75f, true) — access-ordered. TreeMap: backed by a Red-Black tree. get/put/remove: O(log n). Keys must implement Comparable or provide a Comparator. Sorted in natural key order or custom Comparator order. Additional methods: firstKey(), lastKey(), headMap(), tailMap(), subMap() — range views. Does NOT allow null keys (NullPointerException). Use when: need keys sorted, need range queries, implement a sorted dictionary. EnumMap (bonus): for enum keys, O(1) operations, extremely efficient — use whenever your keys are enum values.
96. What is the Spring @Async annotation and how does it enable asynchronous processing?
- @Async makes all Spring beans run asynchronously in a background process without any configuration
- @Async marks a Spring method to be executed in a separate thread asynchronously — the caller continues immediately without waiting for the result — enabled by @EnableAsync and requiring a configured TaskExecutor
- @Async is only for database operations and cannot be used with business logic methods
- @Async requires the Spring WebFlux reactive framework to provide asynchronous capabilities
Answer : B Explanation: @Async enables non-blocking method execution in Spring: Setup: @EnableAsync on @SpringBootApplication or @Configuration class. Usage: @Service public class EmailService { @Async public void sendEmail(String to, String body) { // runs in a separate thread Thread.sleep(5000); // simulate slow email send System.out.println(“Email sent to ” + to); } }. The caller: emailService.sendEmail(“user@example.com”, “Hello”); // returns immediately, email sent asynchronously. Return types with @Async: void — fire and forget. Future<T>: Future<String> future = asyncMethod(); future.get(); // blocks until result. CompletableFuture<T> (recommended): @Async public CompletableFuture<String> processAsync() { return CompletableFuture.completedFuture(“result”); }. Caller: CompletableFuture<String> cf = service.processAsync(); cf.thenAccept(result -> …); // non-blocking continuation. Thread pool configuration: @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); executor.setThreadNamePrefix(“Async-“); executor.initialize(); return executor; }. Self-invocation problem: same as @Transactional — @Async doesn’t work when called from the same class (bypasses proxy). Solution: inject the bean or split into different classes. Use cases: sending emails, push notifications, generating reports, calling slow external APIs.
97. What are JPA entity relationships and what is the role of CascadeType?
- CascadeType determines which database table columns are included in JOIN operations
- CascadeType in JPA controls which persistence operations performed on a parent entity are automatically propagated (cascaded) to its child entities — options include PERSIST, MERGE, REMOVE, REFRESH, DETACH, and ALL
- CascadeType only affects the database trigger behavior and has no Java-side effects
- CascadeType.ALL must always be used for all JPA relationships — other types are deprecated
Answer : B Explanation: CascadeType controls how operations propagate through entity relationships: @OneToMany(cascade=CascadeType.PERSIST): saving the parent automatically saves the children. @OneToMany(cascade=CascadeType.REMOVE): deleting the parent automatically deletes the children. @OneToMany(cascade=CascadeType.MERGE): merging the parent automatically merges the children. @OneToMany(cascade=CascadeType.REFRESH): refreshing the parent refreshes the children from the database. @OneToMany(cascade=CascadeType.DETACH): detaching the parent also detaches the children. @OneToMany(cascade=CascadeType.ALL): all of the above. Practical example: @Entity public class Order { @OneToMany(mappedBy=”order”, cascade=CascadeType.ALL, orphanRemoval=true) private List<OrderItem> items; }. When you save an Order with items: entityManager.persist(order); — items are also persisted automatically (due to CascadeType.PERSIST). When you delete an order: entityManager.remove(order); — items are also deleted (CascadeType.REMOVE). orphanRemoval=true: removes OrderItem from database when it’s removed from the items collection: order.getItems().remove(item); — item is deleted from DB on next flush. Important caution: CascadeType.REMOVE on @ManyToMany is dangerous — deleting one side could delete the shared entities. Use CascadeType.PERSIST and CascadeType.MERGE for @ManyToMany. Use CascadeType.ALL only for @OneToMany where child entities are completely owned by the parent (composition relationship).
98. What is Spring Cloud Config and why is it needed in microservices?
- Spring Cloud Config is a code generator that creates configuration classes for Spring services
- Spring Cloud Config provides a centralized, externalized configuration server for distributed microservices — all services retrieve their configuration from one central server instead of maintaining separate application.properties files in each service
- Spring Cloud Config is only for securing configuration files with encryption features
- Spring Cloud Config replaces all Spring annotations with externalized configuration files
Answer : B Explanation: In a microservices architecture with 20+ services, managing configuration becomes complex: Without Config Server: each service has its own application.properties. Updating a database URL requires redeploying ALL services that use it. Different instances of the same service may have inconsistent config. Secrets (passwords, API keys) spread across many files. With Spring Cloud Config Server: One Git repository (or Vault, filesystem) stores all configurations. {service-name}.yml per service in Git. Config Server exposes REST API: GET /user-service/default → returns user-service’s configuration. Config clients (each microservice) fetch config from server at startup. Server: @SpringBootApplication @EnableConfigServer public class ConfigServerApp { }. application.properties: spring.cloud.config.server.git.uri=https://github.com/myorg/config-repo. Client (user-service): bootstrap.properties: spring.config.import=configserver:http://config-server:8888, spring.application.name=user-service. Benefits: Single source of truth for all configuration. Change config without redeploying services (with @RefreshScope). Encrypt sensitive values (spring.datasource.password stored as {cipher}ENCRYPTED_VALUE). Git history gives you config change audit trail. Environment-specific config: user-service-dev.yml, user-service-prod.yml. Spring Cloud Bus: broadcast config refresh to all instances simultaneously using Kafka or RabbitMQ. Alternatives: HashiCorp Vault (secrets management), AWS Parameter Store/Secrets Manager, Kubernetes ConfigMaps/Secrets.
99. What is the purpose of the @GeneratedValue annotation in JPA/Hibernate?
- @GeneratedValue automatically generates Java source code for entity class boilerplate methods
- @GeneratedValue specifies how the primary key value should be automatically generated by the persistence provider — with strategies including AUTO, IDENTITY, SEQUENCE, and TABLE
- @GeneratedValue generates random UUIDs for all fields in an entity, not just the primary key
- @GeneratedValue is only compatible with integer primary keys and cannot be used with Long or String
Answer : B Explanation: @GeneratedValue works with @Id to automatically assign primary key values: @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; GenerationType.AUTO: Hibernate picks the best strategy for the database automatically. Default. Usually uses SEQUENCE for databases that support it (PostgreSQL, Oracle), IDENTITY for others (MySQL). GenerationType.IDENTITY: uses database auto-increment column (AUTO_INCREMENT in MySQL, SERIAL in PostgreSQL). @GeneratedValue(strategy=GenerationType.IDENTITY). Inserts without knowing the ID first — Hibernate fires INSERT then retrieves the generated ID. Cannot batch inserts efficiently (Hibernate issue). GenerationType.SEQUENCE: uses a database sequence object. Best practice for PostgreSQL, Oracle. @GeneratedValue(strategy=GenerationType.SEQUENCE, generator=”user_seq”) @SequenceGenerator(name=”user_seq”, sequenceName=”user_id_seq”, allocationSize=50). allocationSize=50: Hibernate allocates 50 IDs from the sequence at once, uses them locally — efficient batching. Recommended for high-performance applications. GenerationType.TABLE: uses a special table to simulate sequences. Portable but slow (requires separate table access). Rarely used. UUID Primary Keys: @Id @GeneratedValue(generator=”UUID”) @GenericGenerator(name=”UUID”, strategy=”org.hibernate.id.UUIDGenerator”) private UUID id. Or in Spring Boot with Hibernate 6: @Id @UuidGenerator private UUID id. UUID PKs are better for microservices (globally unique without coordination).
Cybersecurity Careers: Salaries, Jobs, and How to Break In With Zero Experience
100. What are the most important Advanced Java concepts and frameworks for modern Java backend development?
- Modern Java backend development only requires knowing JDBC and Servlets — all frameworks are optional
- Modern Java backend development requires proficiency in Spring Boot (REST APIs, DI, auto-configuration), Spring Data JPA with Hibernate (ORM), Spring Security (JWT/OAuth2), Java 8+ features (Streams, Lambdas, Optional), multithreading (ExecutorService, CompletableFuture), microservices patterns (Spring Cloud), Docker/Kubernetes, and testing (JUnit 5, Mockito, @SpringBootTest)
- Modern Java backend development has moved entirely to Kotlin — Java itself is no longer used
- Only one framework (either Spring or Hibernate) is sufficient for all modern Java backend needs
Answer : B Explanation: Modern Java backend development (2025) technology stack: Core Java: Java 17+ (LTS) features — records (immutable data classes), sealed classes, pattern matching, text blocks, switch expressions. Java 21 virtual threads (Project Loom) — thread-per-request model at massive scale. Web Framework: Spring Boot 3.x with Jakarta EE 9+ (javax → jakarta package). Spring WebFlux for reactive applications. Data Access: Spring Data JPA with Hibernate 6.x. Spring Data repositories eliminating DAO boilerplate. Database migrations: Flyway or Liquibase. Connection pooling: HikariCP. Security: Spring Security 6 with OAuth2/OIDC. JWT for REST API authentication. Keycloak for enterprise identity management. Messaging: Apache Kafka (event streaming), RabbitMQ (message queuing) via Spring AMQP. Microservices: Spring Cloud (Config, Eureka, Gateway, Resilience4j). Docker + Kubernetes for containerization and orchestration. Testing: JUnit 5 + Mockito + AssertJ. @SpringBootTest for integration tests. Testcontainers for real database testing. Build: Maven or Gradle. Performance tools: Actuator + Micrometer → Prometheus → Grafana. Documentation: Springdoc OpenAPI (Swagger UI). Emerging: GraalVM Native Image (instant startup). Spring AI (LLM integration). The Java/Spring ecosystem continues to be dominant for enterprise backend development — understanding this full stack is the pathway to Java backend roles at top companies.
