Command Palette

Search for a command to run...

PHASE 3Beginner ~28 min· topic 1 of 11

Topic 3.1

Methods: Naming a Piece of Work

In one line

A method is a named block of code you can run again and again by calling its name. Methods let you write a piece of work once, give it a clear name, and reuse it, which keeps programs short, readable and easy to fix.

Think of it like this

A recipe card for making tea. You write the steps once and put a name on the card: "Make tea". Whenever anyone wants tea, they don't re-invent the steps. They say "make tea", follow the card, and come back to what they were doing. A method is that recipe card, and calling the method is saying its name.

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

Method
A named block of code inside a class that runs when you call it. Other languages call it a function.
Declare / define
Write the method: its header and its body. Declaring it doesn't run it.
Call / invoke
Run a method by writing its name followed by brackets, like printBanner();. Both words mean the same thing.
Caller
The code that calls a method. When the method finishes, control goes back to the caller.
Method header
The first line of a method, such as static void printBanner(). It tells you how to call the method and what it gives back.
Method body
The statements between { and } that run each time the method is called.
`void`
A keyword in the header meaning "this method gives nothing back". It just does its work.
`static`
Means the method belongs to the class itself, so you can call it without creating an object. For now, every method you write gets static. Topic 4.6 explains it fully.
Control flow
The order in which statements run. A method call makes control jump into the method and back.

Step by step

01The problem methods solve

Imagine a program that prints a banner (three lines of = and a title) at the start, after every section, and at the end. Without methods you'd copy the same three println lines five times.

Copies cause two problems. The program gets long and hard to read. Worse, when you want to change the banner, you must find and fix every copy, and it's easy to miss one. This is called duplication, and avoiding it is one of the first rules of good code (often called DRY: Don't Repeat Yourself).

A method fixes both problems: write the three lines once, give them a name, and call the name wherever you need the banner.

02Declare a method, then call it

Here printBanner is declared once and called twice. main is itself a method: the special one the JVM calls first when your program starts (Topic 0.5).

Notice that printBanner is declared *above* main here, but it could just as well sit below it. Order inside a class doesn't matter for methods.

Main.javawhole filejava
public class Main {
    static void printBanner() {          // declaration: header + body
        System.out.println("==========");
        System.out.println("  HECTAL  ");
        System.out.println("==========");
    }

    public static void main(String[] args) {
        printBanner();                    // call #1
        System.out.println("Lesson starts");
        printBanner();                    // call #2
    }
}
terminal
$ javac Main.java
java Main
── expected output ──
==========
HECTAL
==========
Lesson starts
==========
HECTAL
==========

03What a call really does: jump, run, return

When the JVM reaches printBanner(); in main, it pauses main at that line, remembers where it was, and starts running printBanner from its first statement.

When printBanner reaches its closing } (or a return;), the JVM goes back to main and continues with the very next statement. The method has no idea who called it. It just runs and returns.

Each call gets its own fresh set of local variables, kept in a stack frame. You'll meet frames properly in Topic 3.11; for now picture a stack of plates: each call puts a plate on top, and returning takes it off.

What a call really does: jump, run, returndiagram
Rendering diagram…

04Methods calling methods

A method can call another method, which can call another. Each call pauses the one before it, so the calls nest. The last one called is the first one to finish: this is exactly the last-in, first-out order of a stack.

Indented output makes the nesting visible. Read it top to bottom and you can trace every jump.

Main.javawhole filejava
static void a() {
    System.out.println("  enter a");
    b();
    System.out.println("  back in a");
}
static void b() {
    System.out.println("    in b");
}
// main: println("enter main"); a(); println("back in main");
terminal
$ java Main
── expected output ──
enter main
enter a
in b
back in a
back in main

05Leaving early with return

A void method normally ends at its closing brace. You can end it sooner with return;. This is handy for guard clauses: check for a bad situation at the top, handle it, and leave, so the rest of the method only deals with the normal case.

After return; nothing else in that call runs. The compiler even refuses code placed directly after a return in the same block, with error: unreachable statement.

Main.javawhole filejava
static void checkAge(int age) {
    if (age < 0) {
        System.out.println("Invalid age: " + age);
        return;                       // leave now
    }
    System.out.println("Age " + age + " is fine");
}

06What the compiler produces for a call

javac turns each method into its own block of bytecode in Main.class. A call to a static method becomes one instruction, invokestatic, that names the method and its type. You can see it with javap -c, the JDK's class-file disassembler.

The odd text hello:()V is the method's descriptor: () means no parameters and V means void. The JVM finds methods by name *and* descriptor, which is why two methods can share a name if their parameters differ (Topic 3.4).

terminal
$ javap -c Main
── expected output ──
static void hello();
Code:
0: getstatic #7 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #13 // String Hello
5: invokevirtual #15 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
 
public static void main(java.lang.String[]);
Code:
0: invokestatic #21 // Method hello:()V
3: invokestatic #21 // Method hello:()V
6: return
Output trimmed to the two methods. The program is `hello()` printing "Hello", called twice from main.

07Why static, for now

main is static, which means it runs without any object being created. A static method can directly call other static methods of the same class. If you forget static on your own method, the compiler stops you with non-static method ... cannot be referenced from a static context.

Non-static (instance) methods belong to objects, and you'll write them from Phase 4 onward (Topic 4.2). Until then, put static on every method you write.

Try it yourself

  1. 1

    Add a third method and trace it

    Copy "Nested calls return in reverse order". Before running, add a method d() that prints in d and call it from c() after its print. Write down the full output you expect, then run it and compare.

  2. 2

    Move a method below main

    In "Declare once, call many times", cut printBanner and paste it after main. Predict: does it still compile? Run it. (It does: method order inside a class never matters.)

  3. 3

    Remove static and read the error

    Delete the word static from sayStep. Run it and read the compiler message carefully: it names the method and says *static context*. Put static back.

Code & diagrams

Declare once, call many times New tab
Sign in to run this example in your browser.

Expected output

main starts
==========
  HECTAL  
==========
Step: wash your hands
Step: wash your hands
==========
  HECTAL  
==========
main ends
Nested calls return in reverse order New tab

Each call pauses its caller. The last method entered is the first to finish.

Sign in to run this example in your browser.

Expected output

enter main
  enter a
    enter b
      in c (deepest)
    back in b
  back in a
back in main
Guard clause with an early return New tab
Sign in to run this example in your browser.

Expected output

Invalid age: -3
Age 12: minor
Age 40: adult
Anatomy of a method declarationjava

Not a full program: a labelled fragment. Parameters and return values are Topic 3.2.

//  modifiers   return type   name          parameters
    static        void          printBanner   ()           {
        // body: runs each time printBanner() is called
        System.out.println("==========");
    }

//  a method that takes input and gives back a value (Topic 3.2)
    static        int           square        (int x)      {
        return x * x;
    }

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Forget static on your own method

Declare void greet() without static, then call greet(); from main.

Main.javawhole filejava
public class Main {
    void greet() { System.out.println("hi"); }
    public static void main(String[] args) {
        greet();
    }
}
terminal
$ javac Main.java
── what you'll see ──
Main.java:4: error: non-static method greet() cannot be referenced from a static context
greet();
^
1 error

Break #2

Put code after return

Add a System.out.println directly after a return; in the same block.

Main.javawhole filejava
static void stop() {
    return;
    System.out.println("never runs");
}
terminal
$ javac Main.java
── what you'll see ──
Main.java:4: error: unreachable statement
System.out.println("never runs");
^
1 error

Myth vs fact

Myth

A method runs when you declare it.

Fact

Declaring a method only describes the work. It runs each time it's called, and never if nobody calls it.

Myth

A method must be declared before the code that calls it, like in C.

Fact

In Java the compiler reads the whole class first, so methods can appear in any order.

Myth

Methods are only for code you repeat.

Fact

Even code used once is often clearer as a well-named method. validateOrder(); chargeCard(); sendEmail(); reads like a story.

Myth

Calling a method is slow, so big methods are faster.

Fact

The JIT compiler inlines small hot methods (copies their body into the caller), so the call usually costs nothing. Huge methods are actually harder for the JIT to optimise.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    HotSpot's JIT inlines a method into its caller when its bytecode is small (default -XX:MaxInlineSize=35 bytes for any call, -XX:FreqInlineSize=325 bytes for hot calls). Small methods are therefore free after warm-up, and inlining unlocks further optimisations such as escape analysis (Topic 3.11).

  • ▸

    Very large methods hurt: HotSpot skips JIT compilation of methods over 8000 bytes of bytecode (-XX:+DontCompileHugeMethods, on by default), so a giant generated switch can stay interpreted forever. And a single method's bytecode is capped at 64 KB, after which javac reports code too large.

  • ▸

    A static call compiles to invokestatic; instance calls use invokevirtual, interface calls invokeinterface, constructors and private methods invokespecial. Which one is used decides how the JVM finds the code to run, which is the root of overriding and polymorphism (Topic 5.4).

Remember this

  1. 1

    A method is a named block of statements inside a class. Writing it (the declaration) does nothing by itself. The code runs only when some other code calls it by name, for example printBanner();.

  2. 2

    When a method is called, Java pauses the caller, jumps into the method, runs its body from the top, and then returns to the exact spot it left, continuing with the next statement. A method can call other methods, so these jumps nest like boxes inside boxes.

  3. 3

    Every method declaration has a header and a body. The header static void printBanner() says: static (belongs to the class, so main can call it directly), void (gives nothing back), the name printBanner, and an empty parameter list (). The body is the code between { and }.

  4. 4

    Names follow camelCase and usually start with a verb: printReport, calculateTax, isValid. A good name tells the reader what happens without reading the body. If you can't find a short name, the method is probably doing too much.

  5. 5

    In Java every method lives inside a class, and you can't declare one method inside another. Methods may be written in any order in the class: main can call a method declared further down, because the compiler reads the whole class before checking calls.

  6. 6

    A void method can stop early with a bare return;. Methods are not just tidiness: they are the unit the JVM compiles, optimises and shows in stack traces, so small, well-named methods make errors easier to find (Topic 0.7).

Explain it without notes

01

What happens, step by step, when main calls a method and that method finishes?

02

Why does duplicating code instead of writing a method cause bugs over time?

03

Why can't main call a method that isn't marked static?

04

What makes a good method name? Give two good and two bad examples.

Practice

01

Write a program with a method printLine() that prints 20 dashes, and use it to print a framed message: a line, Welcome to Java, a line.

02

Write printSquare() that prints a 3x3 block of # using two nested loops, and call it twice with a blank line in between.

03

Write three methods morning(), afternoon() and evening() that each print a greeting, and a method fullDay() that calls all three in order. Call fullDay() from main.

Trade-offs

  • ↔

    Many tiny methods make each piece easy to name and test, but too many one-line wrappers force the reader to jump around. Extract a method when it has a clear name and a single job.

  • ↔

    Long methods keep everything in one view but hide structure and resist reuse. A method longer than a screen is usually several methods waiting to be extracted.

Done when you can

  • Done when you can declare a static void method and call it from main.

  • Done when you can trace the output of nested method calls by hand.

  • Done when you can use return; to leave a void method early.

  • Done when you can explain the non-static method ... static context error and fix it.

  • Done when you can choose clear, verb-first names for methods.