Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 201 ยท Methods

Methods

Learn Java methods - why they matter, how to define and call them, static methods, void methods, return in brief, naming conventions and how to split a program into methods.

Every program you've written so far lives inside one method, main. That works for twenty lines. At two hundred lines, main becomes a wall of code where the same steps repeat, a bug fixed in one copy survives in another, and nobody can see the overall plan. Methods fix this. A method is a named block of code that does one job. You write it once and call it by name whenever you need that job done.

You've been calling methods since your first lesson: IO.println(...), word.length(), Math.max(a, b), Arrays.sort(scores). In this lesson you'll write your own. You'll learn the parts of a method declaration, how calls move through a program, what static and void mean, how methods look in compact source files compared with classic classes, and how to choose good names and good boundaries.

Why methods?

  • No repetition. If the same five lines appear in three places, put them in a method. A fix or improvement then happens in one place.
  • Readable code. printReceipt(order) says what happens. The reader can skip how unless they care. A well-split main reads like a table of contents.
  • Smaller problems. You can write, test and debug a 10-line method on its own, then stop thinking about its details.
  • Reuse. A good method, like isLeapYear(year), can be used by code its author never imagined.

Your first method

Here's a method that prints a decorated title, called three times from main:

Java Define once, call many times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A method declaration has a header and a body:

Java
void printBanner() {     // header: return type, name, parameter list
    ...                  // body: the statements that run on each call
}
  • Return type. void means the method gives no value back; it just does something. Methods that compute a value name its type instead, such as int or String.
  • Name. printBanner, written in camelCase.
  • Parameter list in parentheses. Empty here; the next section adds parameters.
  • Body in braces, which runs every time the method is called.

A method call is the name followed by parentheses: printBanner();. Forgetting the parentheses is an error: Java would look for a variable named printBanner.

The order of methods in a file doesn't matter. printBanner could come after main, and many programmers put main first so a reader sees the big picture immediately. What matters is that methods sit side by side: Java doesn't allow declaring a method inside another method.

How a call works

When Java reaches a call, it jumps into the method, runs its body from the top, and when the body finishes, it jumps back to just after the call. Methods can call other methods, which can call more, and each one returns to exactly where it was called from:

Java Following the flow of calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java keeps track of this with the call stack. Each call pushes a frame holding that method's local variables and the spot to return to; finishing the method pops its frame. That's why the stack traces you see when an exception occurs list one line per method: they're a snapshot of the call stack. Recursion explores the call stack in depth.

flowchart TB
    subgraph Stack["Call stack (the top frame is the method that is running)"]
        direction TB
        F3["square(n = 4)"]
        F2["area(width = 4)"]
        F1["main()"]
    end
    F1 -->|"calls"| F2
    F2 -->|"calls"| F3

Each call adds a frame on top of the stack. When square returns, its frame is removed and area carries on.

Parameters and return values: a first look

Most methods need input and many produce a result. Parameters are variables listed in the header that receive values from the caller. A return type other than void promises a result, which the method hands back with return:

Java A method with input and output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

isLeapYear(int year) takes one int and returns a boolean. Because it returns a value, a call to it is an expression: you can use it in a condition, store it in a variable or pass it on. describe takes an int and returns nothing, so its call is a statement on its own.

The details (multiple parameters, how arguments are copied, return rules, returning several values) are the topic of Parameters and Return Values.

Methods in compact files and in classes

Since Java 25, a file with a top-level void main() is a compact source file. Java wraps everything in it in an invisible class, so the methods you write beside main are simply methods of that class, and they can call each other directly. That's the style you've used so far.

In a traditional file, you write the class yourself. The classic main is static, and a static method can call another method directly only if that one is static too:

Java Static methods in a classic class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

static means the method belongs to the class itself, not to any particular object. You can call it with no object at all, either by its plain name from inside the same class or as ClassName.method(...) from anywhere else. That's exactly how you call Math.sqrt and Arrays.sort: they're static methods of the Math and Arrays classes.

If you forget static on a helper and call it from public static void main, the compiler stops you:

TEXT
error: non-static method printConversion(double) cannot be referenced from a static context

A non-static (instance) method needs an object to run on, and static main doesn't have one. Adding static to the helper is the usual fix for programs like these. Once you build your own classes, instance methods become the norm; Static vs Instance Methods explains when each is right.

Why do compact files not need static? Their main is an instance main method (allowed since Java 25), and Java creates an object of the hidden class to run it. Instance methods can call other instance methods directly, so everything just works. Both styles are correct; you'll see public static void main(String[] args) in most existing code, tutorials and job interviews.

The anatomy of a full method header

As you go further, headers gain more parts. Here's a complete one, with every piece labeled:

flowchart TB
    m["public static"] --> lm["modifiers"]
    r["int"] --> lr["return type"]
    n["add"] --> ln["method name"]
    p["(int a, int b)"] --> lp["parameters"]
    b["{ return a + b; }"] --> lb["body"]

The parts of a method declaration, from left to right.

Java
public static int clamp(int value, int min, int max) throws IllegalArgumentException
//  โ”‚      โ”‚     โ”‚   โ”‚    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ parameters โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€ exceptions it may throw
//  โ”‚      โ”‚     โ”‚   โ””โ”€ name
//  โ”‚      โ”‚     โ””โ”€ return type
//  โ”‚      โ””โ”€ static: belongs to the class
//  โ””โ”€ access modifier: who may call it
  • Access modifiers (public, private, ...) control which other code may call the method; they're covered in Access Modifiers. In a single-file program you can leave them out.
  • throws lists exceptions the method may pass to its caller (Throwing Exceptions).

Only the return type, name, parentheses and body are required. The name plus the parameter types form the method's signature: clamp(int, int, int). Two methods in the same class can share a name if their signatures differ, which is called Method Overloading.

Naming methods

Methods do things, so name them with verbs, in camelCase, starting with a lowercase letter:

Kind of method Naming pattern Examples
performs an action verb or verb phrase printReport, sendEmail, sortByDate
computes a value what it returns, often with a verb calculateTotal, average, toFahrenheit
answers yes/no is, has, can, should isEmpty, hasPermission, canVote
reads a property get + noun getName, getBalance

Good names make comments unnecessary: if (isLeapYear(year)) reads like English. If you can't find a short name that says what a method does, it probably does too much.

How to split a program into methods

Good methods are small and focused: one job, done completely, at one level of detail. A useful test: describe the method in one sentence without the word "and". Here's a small report program where main only states the steps and each helper does one of them:

Java main as a table of contents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice how easy it is to change one thing. Want a new grading scale? Only letterGrade changes. Want the report in a different layout? Only the print methods change. That's the payoff of focused methods.

Some guidelines that serve professionals well:

  • Keep methods short. Most methods in good codebases fit on one screen, and many are under 15 lines. If you're scrolling, look for a piece to extract.
  • One level of abstraction. main above talks in big steps; the details live one level down. Mixing printReport() calls with low-level string fiddling in the same method makes both harder to follow.
  • Extract repeated code, but don't force it. Two lines that happen to look alike aren't always the same idea.
  • Prefer returning values to printing. letterGrade returns a grade instead of printing it, so it can be reused in a file export, a test or a web page. Keep computing and printing in separate methods where you can.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this compact program print? void a() { IO.print("1"); b(); IO.print("3"); } void b() { IO.print("2"); } void main() { a(); a(); }

    Each call to a() prints 1, calls b() which prints 2, then returns and prints 3. main calls a() twice, so the sequence repeats.
  2. 2. What does the return type void mean?

    void methods don't produce a value, so their call can't be used inside an expression. Parameters are a separate matter.
  3. 3. In a classic public class Main, public static void main(String[] args) calls void helper() (no static). What happens?

    A static method has no object to run an instance method on. Make helper static, or create an object first. Compact files avoid this because their main is an instance method.
  4. 4. Which is the best name for a method that checks whether a username is already taken?

    Methods that answer yes/no read best with is/has/can prefixes, in camelCase starting with a lowercase letter. doCheck says nothing about what is checked.
  5. 5. Which statement about methods in Java is true?

    Java resolves calls across the whole class, so order doesn't matter. Methods can't be nested, and every call needs parentheses, even an empty pair.

Summary

  • A method is a named block of code; you declare it once and call it by name with parentheses.
  • A declaration has a return type (void for none), a name, a parameter list and a body; methods sit side by side in any order.
  • A call jumps into the method and returns to just after the call when it finishes; the call stack tracks this.
  • static methods belong to the class and can be called without an object, as Math.max is; static main can call only static methods directly.
  • In compact source files, main is an instance method, so helpers don't need static.
  • Name methods with camelCase verbs (printReport, isEmpty), and keep each one small and focused on one job.

Next: Parameters and Return Values, where you'll pass data into methods, get results back and learn exactly how Java copies arguments.