Define and call a method
18 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)To define a method, you write its header and its body. To call it, you write its name with brackets, like greet();.
The parts of a method
A greeting is needed in many places, so it gets its own method. The first line, the header, gives the method its name; the lines inside { }, the body, run on every call.
static void greet() { System.out.println("Good morning, students!");}public static void greet(). Both work in these programs; for now, always write static.Where a method goes
Write greet inside main, and Java stops with illegal start of expression. A method goes inside the class but outside every other method, above or below main.
Example 1 · A method above main
public class Greeting { static void greet() { System.out.println("Good morning, students!"); }
public static void main(String[] args) { greet(); }}Good morning, students!
What this code does
greetsits inside the class, between its opening{andmain. It could just as well go after the closing}ofmain.- Java always starts at
main, wherever it is in the file, so the greeting prints once: from the call.
Find the bug
Spot the method bug
Select the line that is wrong.
This should print Hello!
Round 1 of 4What happens at a call
main prints a line, calls greet(), then prints again. In what order do the lines appear? A call makes Java jump into the method, run its whole body, and come back to the line after the call.
Trace the code
Follow Java into the method and back
Variables
None yet.
Output
Class starts
Line 3Java starts at main and runs its first line.
main.A method can call another method
A class list starts with a header: a line, a title, another line. Any method can call another, so printHeader() calls printLine(), and each call returns to the method that made it.
Example 2 · A method that calls another
public class Header { public static void main(String[] args) { printHeader(); System.out.println("Roll 1: Aman"); }
static void printHeader() { printLine(); System.out.println("CLASS 12 - B"); printLine(); }
static void printLine() { System.out.println("------------"); }}------------ CLASS 12 - B ------------ Roll 1: Aman
What this code does
maincallsprintHeader, andprintHeadercallsprintLinebefore and after the title.- When
printLineends, Java goes back toprintHeader, not tomain. - Only when
printHeaderends does Java return tomainand printRoll 1: Aman.
Name a method with a verb in camelCase, like printHeader, showMenu or calculateTotal, so that a call reads like an instruction (the same style as variable names (opens in a new tab)).
Next step
Check your understanding
8 quick questions