Skip to lesson

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

ReportCard.javaJava
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("====================");    }}
Output
====================
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.

Three calls printLine(); in main all lead to the same method printLine, whose body prints the border once. Each call runs that one body, so the border prints three times but is written only once.

Example 2 · With a method: written once, called three times

ReportCardMethod.javaJava
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("====================");    }}
Output
====================
Name: Priya
====================
Marks: 450 / 500
====================

What this code does

  • printLine is the method. Its body, the line inside its { }, holds the border once.
  • Each printLine(); in main runs that body, so the output is exactly the same as before.
  • To change the border now, you edit one line, and main reads 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