Posts

Infinite Loop in REST API

Infinite Loop in REST API Infinite Loop in REST API Problem: The following code is making an infinite loop when calling /products/{id}. Why? @RestController @RequestMapping("/products") public class ProductController { @GetMapping("/{id}") public Product getProduct(@PathVariable Long id) { return getProduct(id); } } Copy Code The issue in the Infinite Loop in REST API question is that the method is calling itself recursively without a base case, causing a StackOverflowError due to infinite recursion. Problematic Code: @GetMapping("/{id}") public Product getProduct(@PathVariable Long id) { return getProduct(id); // Recursive call without exit condition } Copy Code Fix: Instead of recursively calling getProduct(id), the method should fetch the product...

NullPointerException in Java

The following code throws a NullPointerException. Identify and fix the issue. A NullPointerException (NPE) occurs when you try to call a method or access a property on an object reference that is null. It is one of the most common exceptions in Java. Common Causes: Calling methods on a null object reference. Accessing or modifying fields of a null object. Attempting to iterate over a null collection. Solution: You can prevent a NullPointerException by checking if the object is null before performing operations on it. The following code throws a NullPointerException. Identify and fix the issue. @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public ResponseEntity getUserById(@PathVariable Long id) { return ResponseEntity.ok(userService.getUserById(id).g...