Why use methods?
14 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A method is a named block of code that does one job. You write it once, and run it whenever you need it just by using its name.
The same lines, again and again
A report card prints the same border line three times, so the line is typed three times. To change the border, you must find and fix every copy.
Example 1 · Without a method: repeated lines
public class ReportCard { public static void main(String[] args) { System.out.println("===================="); System.out.println("Name: Priya"); System.out.println("===================="); System.out.println("Marks: 450 / 500"); System.out.println("===================="); }}==================== Name: Priya ==================== Marks: 450 / 500 ====================
What this code does
- The border line
====================is typed three times. - To make it
--------------------, you must edit three lines. Miss one, and the card looks wrong.
Write once, call many times
Put the border in one place and give it a name. A method is that named block, and writing its name with brackets, printLine();, calls it: Java runs its lines.
Example 2 · With a method: written once, called three times
public class ReportCardMethod { public static void main(String[] args) { printLine(); System.out.println("Name: Priya"); printLine(); System.out.println("Marks: 450 / 500"); printLine(); }
static void printLine() { System.out.println("===================="); }}==================== Name: Priya ==================== Marks: 450 / 500 ====================
What this code does
printLineis the method. Its body, the line inside its{ }, holds the border once.- Each
printLine();inmainruns that body, so the output is exactly the same as before. - To change the border now, you edit one line, and
mainreads like a list of steps.
main is a method too: Java calls it first when the program starts. The first line, static void printLine(), is taken apart in the next lesson, Define and call a method (opens in a new tab).
Methods you already use
You have called methods since your first program. Round brackets right after a name, as in println("Hi") or sc.nextInt(), mean a method call: someone else wrote the method, and you use it.
Classify
Method call or not?
Tap a line, then tap where it belongs.
Next step
Check your understanding
7 quick questions