Bird
0
0

Given the following Spring Boot code snippet, what will be the output when getData() is called twice?

medium📝 component behavior Q13 of 15
Spring Boot - Caching
Given the following Spring Boot code snippet, what will be the output when getData() is called twice?
@EnableCaching
@Service
public class DataService {
  private int count = 0;

  @Cacheable("dataCache")
  public String getData() {
    count++;
    return "Call number: " + count;
  }
}
A["Call number: 1", "Call number: 1"]
B["Call number: 2", "Call number: 2"]
C["Call number: 0", "Call number: 1"]
D["Call number: 1", "Call number: 2"]
Step-by-Step Solution
Solution:
  1. Step 1: Understand caching effect on method calls

    The first call to getData() runs the method, increments count to 1, and caches the result.
  2. Step 2: Analyze second call behavior

    The second call returns the cached result without running the method again, so count stays 1.
  3. Final Answer:

    ["Call number: 1", "Call number: 1"] -> Option A
  4. Quick Check:

    Cache returns same result on repeated calls [OK]
Quick Trick: Cached method runs once; repeated calls return cached result [OK]
Common Mistakes:
  • Assuming count increments on every call despite caching
  • Ignoring that @Cacheable caches method output
  • Confusing cache key usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes