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!');
}
void as the return type means "this method performs an action but doesn't hand back a value." Calling it looks like this:
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');
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
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.