Writing Your First Method
By the end of this lesson, you'll be able to:
- Write a simple method with no parameters and no return value
- Call a method from elsewhere in a class
- Explain what void means as a return type
Prerequisites: "What Is a Method?"
A method that does something, returns nothing
public void greetCustomer() {
System.debug('Welcome to the store!');
}
public void greetCustomer() {—voidas the return type means "this method performs an action but doesn't hand back a value." No parameters either — empty( ).System.debug('Welcome to the store!');— the action this method performs.}— closes the method.
Calling it looks like this:
greetCustomer();
greetCustomer();— notice there's nothing to store the result in — because there is no result, just an action.
A real business example: Hospitality (Front Desk)
public void logCheckIn(String guestName) {
System.debug(guestName + ' checked in at ' + System.now());
}
logCheckIn('J. Ndlovu');
logCheckIn('T. Adebayo');
public void logCheckIn(String guestName) {— takes one parameter, the guest's name.System.debug(guestName + ' checked in at ' + System.now());— logs the guest's name along with the current moment.}— closes the method.- (blank line)
logCheckIn('J. Ndlovu');— calls it for the first guest.logCheckIn('T. Adebayo');— calls it again for a second guest, same method, different argument.
A hotel's front-desk system logs every check-in the same way — one method, called once per guest, instead of writing out the same System.debug line by hand for every arrival.
Common mistakes
- Forgetting the parentheses when calling a method. Writing
greetCustomer;instead ofgreetCustomer();doesn't call the method at all — it's simply invalid. - Trying to store the result of a void method.
String x = greetCustomer();is a compile error — there's no value to store.
Exercise
Write a void method called logShift that debugs "Shift started." Then call it once.
Show hint
public void logShift() { System.debug('Shift started.'); }
Writing Your First Method 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
This lesson writes and calls a real method for the first time — the simplest possible shape, one that does something but doesn't hand back a value.