Bird
0
0

Given the code below, what will be the output when getUser(1) is called twice?

medium📝 component behavior Q13 of 15
Spring Boot - Caching
Given the code below, what will be the output when getUser(1) is called twice?
@Cacheable("users")
public User getUser(int id) {
    System.out.println("Fetching user from DB");
    return new User(id, "Name" + id);
}
AFetching user from DB printed twice, two User objects returned
BNo output printed, both calls return null
CFetching user from DB printed once, but both calls create new User
DFetching user from DB printed once, second call returns cached User
Step-by-Step Solution
Solution:
  1. Step 1: Understand @Cacheable behavior

    The first call runs the method and caches the result; subsequent calls return cached data.
  2. Step 2: Analyze output for two calls

    "Fetching user from DB" prints only once on first call; second call uses cache, no print.
  3. Final Answer:

    Fetching user from DB printed once, second call returns cached User -> Option D
  4. Quick Check:

    @Cacheable caches after first call [OK]
Quick Trick: First call runs method, next calls use cache [OK]
Common Mistakes:
  • Assuming method runs every time ignoring cache
  • Thinking cache returns null if not found
  • Confusing @Cacheable with @CachePut behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes