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?
Check the condition for the "VIP" customer type and the multiplication.
The method returns 20% of the amount for "VIP" customers, so 1000 * 0.2 = 200.0.
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)?
Think about what happens when the items list is empty.
The method sets the status to "FAILED" if the items list is empty.
Choose the correct way to annotate a Spring Boot service method to ensure it runs within a transaction:
Look for the correct annotation spelling and usage for a writable transaction.
@Transactional is the correct annotation. Option A is misspelled. Option A marks the transaction as read-only, which is not suitable for updates. Option A disables transactions.
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?
Consider what happens if getItems() returns null and you call stream() on it.
If getItems() returns null, calling stream() on null causes NullPointerException. The order object itself being null would cause a different error earlier. Item price and quantity are primitives or boxed types but unlikely to cause NPE here. The stream() method is supported on collections.
In a typical Spring Boot application, what is the main purpose of the service layer?
Think about where the business rules and logic should live in the app.
The service layer contains business logic and acts as a bridge between controllers (which handle HTTP) and repositories (which handle data storage). Controllers do not contain business logic, repositories do not contain business rules, and views handle UI.