Bird
Raised Fist0
Spring Bootframework~20 mins

Business logic in services in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Spring Boot Service Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Spring Boot service method?

Consider this service method that calculates a discount based on customer type:

public double calculateDiscount(String customerType, double amount) {
    if ("VIP".equals(customerType)) {
        return amount * 0.2;
    } else if ("Regular".equals(customerType)) {
        return amount * 0.1;
    } else {
        return 0;
    }
}

What will calculateDiscount("VIP", 1000) return?

A0.0
B100.0
C200.0
DThrows NullPointerException
Attempts:
2 left
💡 Hint

Check the condition for the "VIP" customer type and the multiplication.

state_output
intermediate
2:00remaining
What is the state of the order after calling this service method?

Given this service method that updates an order status:

public void processOrder(Order order) {
    if (order.getItems().isEmpty()) {
        order.setStatus("FAILED");
    } else {
        order.setStatus("PROCESSED");
    }
}

If order.getItems() returns an empty list, what will be the order status after processOrder(order)?

A"PROCESSED"
B"PENDING"
Cnull
D"FAILED"
Attempts:
2 left
💡 Hint

Think about what happens when the items list is empty.

📝 Syntax
advanced
2:00remaining
Which option correctly implements a transactional service method?

Choose the correct way to annotate a Spring Boot service method to ensure it runs within a transaction:

A
@Transactional
public void updateInventory() { /* code */ }
B
@Transaction
public void updateInventory() { /* code */ }
C
@Transactional(readOnly = true)
public void updateInventory() { /* code */ }
D
@Transactional(propagation = Propagation.NEVER)
public void updateInventory() { /* code */ }
Attempts:
2 left
💡 Hint

Look for the correct annotation spelling and usage for a writable transaction.

🔧 Debug
advanced
2:00remaining
Why does this service method throw a NullPointerException?

Examine this service method:

public double calculateTotal(Order order) {
    return order.getItems().stream()
        .mapToDouble(item -> item.getPrice() * item.getQuantity())
        .sum();
}

Sometimes this method throws a NullPointerException. What is the most likely cause?

AThe getItems() method returns null instead of an empty list.
BThe order object is null when passed to the method.
CThe item price or quantity is null causing the exception.
DThe stream() method is not supported on the items list.
Attempts:
2 left
💡 Hint

Consider what happens if getItems() returns null and you call stream() on it.

🧠 Conceptual
expert
2:00remaining
Which statement best describes the role of services in Spring Boot architecture?

In a typical Spring Boot application, what is the main purpose of the service layer?

ATo handle HTTP requests and responses directly.
BTo contain business logic and coordinate data operations between controllers and repositories.
CTo manage database connections and execute SQL queries.
DTo render HTML views and manage user interface components.
Attempts:
2 left
💡 Hint

Think about where the business rules and logic should live in the app.

Practice

(1/5)
1. In Spring Boot, where should the main business logic of an application be placed?
easy
A. Inside a class annotated with @Service
B. Directly inside the controller methods
C. Within the repository interfaces
D. In the main application class

Solution

  1. Step 1: Understand Spring Boot layering

    Controllers handle HTTP requests, repositories handle data access, and services contain business logic.
  2. Step 2: Identify the correct annotation for business logic

    The @Service annotation marks classes that hold business logic in Spring Boot.
  3. Final Answer:

    Inside a class annotated with @Service -> Option A
  4. Quick Check:

    Business logic = @Service class [OK]
Hint: Business logic goes in @Service classes, not controllers or repos [OK]
Common Mistakes:
  • Putting business logic in controllers
  • Adding logic inside repository interfaces
  • Mixing business logic in the main application class
2. Which of the following is the correct way to declare a service class in Spring Boot?
easy
A. @Service public class UserService {}
B. public class UserService {}
C. @Repository public class UserService {}
D. @Controller public class UserService {}

Solution

  1. Step 1: Recognize the annotation for service classes

    Spring Boot uses @Service to mark service classes that contain business logic.
  2. Step 2: Check the options for correct annotation

    Only @Service public class UserService {} uses @Service correctly on the class declaration.
  3. Final Answer:

    @Service public class UserService {} -> Option A
  4. Quick Check:

    Service class = @Service annotation [OK]
Hint: Use @Service annotation to mark service classes [OK]
Common Mistakes:
  • Using @Repository or @Controller instead of @Service
  • Forgetting to add any annotation
  • Placing @Service on interfaces instead of classes
3. Given the following service method, what will be the output when calculateDiscount(150) is called?
public class DiscountService {
    public int calculateDiscount(int price) {
        if (price > 100) {
            return price * 20 / 100;
        } else {
            return price * 10 / 100;
        }
    }
}
medium
A. 20
B. 30
C. 10
D. 15

Solution

  1. Step 1: Check the input value and condition

    The input price is 150, which is greater than 100, so the first branch applies.
  2. Step 2: Calculate the discount

    Discount = 150 * 20 / 100 = 30, but since integer division is used, it remains 30.
  3. Final Answer:

    30 -> Option B
  4. Quick Check:

    Price > 100 -> 20% discount = 30 [OK]
Hint: Check conditions carefully and do integer math for discounts [OK]
Common Mistakes:
  • Choosing 20 thinking it's the percentage, not the amount
  • Confusing the else branch discount
  • Ignoring integer division effects
4. Identify the error in this service class code snippet:
@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    public void saveOrder(Order order) {
        orderRepository.save(order)
    }
}
medium
A. Service class must extend a base class
B. OrderRepository should not be autowired
C. Missing semicolon after orderRepository.save(order)
D. Method saveOrder should return a value

Solution

  1. Step 1: Review the method syntax

    The line orderRepository.save(order) is missing a semicolon at the end.
  2. Step 2: Validate other parts

    Autowired is correct, service classes don't need to extend base classes, and void return is allowed.
  3. Final Answer:

    Missing semicolon after orderRepository.save(order) -> Option C
  4. Quick Check:

    Missing semicolon = syntax error [OK]
Hint: Check for missing semicolons in method calls [OK]
Common Mistakes:
  • Thinking @Autowired is wrong here
  • Assuming service classes must extend something
  • Believing void methods must return a value
5. You want to add a new feature: calculate the total price after applying a discount and tax in your service. Which approach best follows Spring Boot's business logic principles?
public class PricingService {
    private final DiscountService discountService;
    private final TaxService taxService;

    public PricingService(DiscountService discountService, TaxService taxService) {
        this.discountService = discountService;
        this.taxService = taxService;
    }

    public double calculateFinalPrice(double price) {
        // Fill in logic here
    }
}
hard
A. Add calculation logic directly in the main application class
B. Calculate discount and tax inside controller, then call PricingService with final value
C. Put all calculation logic inside the repository layer
D. Implement calculateFinalPrice to call discountService and taxService methods, then combine results

Solution

  1. Step 1: Understand separation of concerns

    Business logic should be inside service classes, not controllers, repositories, or main class.
  2. Step 2: Use existing services inside PricingService

    Calling discountService and taxService methods inside calculateFinalPrice keeps logic modular and reusable.
  3. Final Answer:

    Implement calculateFinalPrice to call discountService and taxService methods, then combine results -> Option D
  4. Quick Check:

    Business logic in services, reuse other services [OK]
Hint: Keep logic in services and reuse other services for clean code [OK]
Common Mistakes:
  • Putting logic in controller or repository layers
  • Mixing logic in main application class
  • Duplicating discount and tax logic outside services