Beginner 20 min read

Return Values

By the end of this lesson, you'll be able to:

  • Write a method that returns a value using return
  • Store a method's return value in a variable
  • Explain why return immediately exits the method

Prerequisites: "Parameters and Arguments"

Returning a value

public Decimal calculateDiscount(Decimal price, Decimal percentOff) {
    Decimal discountAmount = price * (percentOff / 100);
    return discountAmount;
}

Decimal savings = calculateDiscount(200, 15);
System.debug(savings); // 30

return discountAmount; hands the computed value straight back to the caller, which stores it in savings. Unlike the void methods from earlier lessons, this one produces something usable.

return exits immediately

public String classifyAge(Integer age) {
    if (age < 18) {
        return 'Minor';
    }
    return 'Adult';
}

The moment return runs, the method ends right there — nothing after it in that path executes. If age is 12, return 'Minor'; fires and return 'Adult'; is never even reached.

A real business example: Real Estate (Commission Calculator)

public Decimal calculateCommission(Decimal salePrice, Decimal commissionRate) {
    return salePrice * (commissionRate / 100);
}

Decimal commission = calculateCommission(1500000, 5);
System.debug(commission); // 75000

A real estate agent's commission calculation is exactly this shape: take inputs, compute one number, hand it back — clean, testable, and reusable for every sale.

Exercise

Write a method Decimal calculateTotal(Decimal price, Integer quantity) that returns price times quantity. Call it and store the result.

Show hint

return price * quantity;

APEX

Return Values Quiz

1. What happens the moment a return statement executes?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

A method with a real return type hands a value back to whoever called it — that value can be stored, used in an expression, or passed straight into another method.