The constructor expects a body and an HttpStatus enum, not an int.
Step 2: Identify the incorrect use of status code
Passing 201 as int causes a compilation error; should use HttpStatus.CREATED instead.
Final Answer:
Using int 201 instead of HttpStatus enum -> Option B
Quick Check:
Use HttpStatus.CREATED, not int 201 [OK]
Hint: Use HttpStatus enum, not int, for status codes [OK]
Common Mistakes:
Passing int instead of HttpStatus enum
Forgetting to import HttpStatus
Assuming String body is invalid
5. You want to create a Spring Boot controller method that returns 201 Created when a new user is successfully added, 400 Bad Request if the input is invalid, and 401 Unauthorized if the user is not logged in. Which code snippet correctly implements this behavior?
hard
A. public ResponseEntity<String> addUser(boolean validInput, boolean loggedIn) {
if (!loggedIn) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");
}
if (!validInput) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid input");
}
return ResponseEntity.status(HttpStatus.CREATED).body("User created");
}
B. public ResponseEntity<String> addUser(boolean validInput, boolean loggedIn) {
if (!validInput) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");
}
if (!loggedIn) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid input");
}
return ResponseEntity.status(HttpStatus.CREATED).body("User created");
}
C. public ResponseEntity<String> addUser(boolean validInput, boolean loggedIn) {
if (!loggedIn) {
return new ResponseEntity<>("Unauthorized", 401);
}
if (!validInput) {
return new ResponseEntity<>("Invalid input", 400);
}
return new ResponseEntity<>("User created", 201);
}
D. }
;)102 ,"detaerc resU"(>gnirtS
Solution
Step 1: Verify correct use of HttpStatus enums
public ResponseEntity<String> addUser(boolean validInput, boolean loggedIn) {
if (!loggedIn) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Unauthorized");
}
if (!validInput) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid input");
}
return ResponseEntity.status(HttpStatus.CREATED).body("User created");
} uses HttpStatus.UNAUTHORIZED, HttpStatus.BAD_REQUEST, and HttpStatus.CREATED enums correctly.
Step 2: Check logical order and syntax
This code checks !loggedIn first, then !validInput, then returns 201. Options B, C, and D misuse status codes or pass ints to constructors instead of using HttpStatus enums.
Final Answer:
Uses HttpStatus enums with correct logic: !loggedIn (401), !validInput (400), then 201 -> Option A
Quick Check:
Use HttpStatus enums and correct logic order [OK]
Hint: Check login first, then input, use HttpStatus enums [OK]
Common Mistakes:
Passing int status codes instead of HttpStatus enums
Mixing up 400 and 401 status codes
Incorrect order of condition checks
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.