← Chapter 5 — Arrays, Memory & Methods

21. Methods

mixed

Description

Methods group a named piece of behavior so it can be reused. A well-named method makes a program read like a sequence of useful actions.

Methods can accept parameters and return a result. Keep each method focused on one job so it is easy to test and change.

Subtopics

Parameters

Description

Parameters receive input when a method is called.

Explanation

They act as local variables inside that method.

Example

static void greet(String name) { }

Return values

Description

A return statement sends a result back.

Explanation

The declared return type must match the returned value.

Example

static int add(int a, int b) { return a + b; }

Explanation

static methods belong to the class and can be called from main directly. Instance methods belong to objects, which you will explore in object-oriented programming.

Example

public class MethodDemo {
    static int total(int first, int second) {
        return first + second;
    }

    public static void main(String[] args) {
        System.out.println(total(42, 50));
    }
}

Key points

  • Methods organize reusable behavior.
  • Parameters provide input.
  • return sends a result back.

Open reference