Parameters and Arguments
By the end of this lesson, you'll be able to:
- Distinguish between a parameter (the placeholder) and an argument (the actual value passed in)
- Write a method that accepts multiple parameters
- Call the same method with different arguments
Prerequisites: "Writing Your First Method"
Parameter vs argument
public void logOrder(String customerName, Decimal orderTotal) {
System.debug(customerName + ' ordered R' + orderTotal);
}
logOrder('Thabo', 450);
logOrder('Aisha', 1200);
public void logOrder(String customerName, Decimal orderTotal) {—customerNameandorderTotalare parameters — placeholders defined in the method signature.System.debug(customerName + ' ordered R' + orderTotal);— uses whatever values were passed in.}— closes the method.- (blank line)
logOrder('Thabo', 450);—'Thabo'and450are arguments — the actual values supplied on this call.logOrder('Aisha', 1200);— same method, different arguments, different behavior each time.
A real business example: Agriculture (Crop Yield Logging)
public void logHarvest(String fieldName, Decimal tonnes, String cropType) {
System.debug(fieldName + ' produced ' + tonnes + ' tonnes of ' + cropType);
}
logHarvest('North Field', 12.5, 'Maize');
logHarvest('South Field', 8.2, 'Wheat');
public void logHarvest(String fieldName, Decimal tonnes, String cropType) {— three parameters this time.System.debug(fieldName + ' produced ' + tonnes + ' tonnes of ' + cropType);— builds one log message from all three.}— closes the method.- (blank line)
logHarvest('North Field', 12.5, 'Maize');— one field's harvest.logHarvest('South Field', 8.2, 'Wheat');— a different field, different crop, same method.
One method definition, reused across every field and crop — exactly the point of parameters: write the logging behavior once, apply it to any combination of inputs.
Order matters
Arguments are matched to parameters by position, not by name. logOrder(450, 'Thabo') would compile-error here since 450 isn't a String — but if the parameter types happened to line up, swapping the order would silently pass the wrong value to the wrong parameter. Always match the order defined in the method signature.
Exercise
Write a void method describeProduct that takes a String name and a Decimal price, and debugs them combined into one sentence. Call it with any product.
Show hint
public void describeProduct(String name, Decimal price) { ... }
Parameters and Arguments Quiz
Leaderboard
- 1. Monde Masiza 1/1
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
Parameters let a method work on different data each time it's called — the same method logic, applied to whatever values you actually pass in.