A method is a named, reusable block of code that performs one specific job. Writing logic once as a method and calling it wherever it is needed avoids repetition and gives each step in a program a clear, readable name.

A simple method

public void sayHello() {
  System.out.println("Hello");
}

Calling it is just as simple: sayHello(); runs the code inside exactly as if it had been typed inline, but with a name that explains what it does.

Passing information in with parameters

public void greet(String name) {
  System.out.println("Hi " + name);
}

Calling greet("Ann") prints "Hi Ann". The parameter name acts as a placeholder that receives whatever value is passed in at the call site, and a method can accept several parameters separated by commas.

Returning a result

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

Replacing void with a real type, here int, allows the method to send a value back to whoever called it, which can then be stored or used immediately: int total = add(2, 3);

Overloading: same name, different parameters

Java allows multiple methods to share the same name as long as their parameter lists differ, which is called overloading. This lets related operations read naturally under one shared name:

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

Variable-length parameter lists

When the exact number of arguments is not known ahead of time, varargs, written with three dots, lets a method accept any number of values of a given type:

public int sum(int... numbers) {
  int total = 0;
  for (int n : numbers) total += n;
  return total;
}

This single method now accepts sum(1, 2), sum(1, 2, 3, 4), or even no arguments at all.

Static versus instance methods

A static method belongs to the class itself and can be called without creating an object, useful for utility operations that do not depend on any particular object's data. An instance method, the more common kind, operates on the specific object it is called on and can access that object's own fields.

Why methods matter

  • They eliminate repeated code, since the same logic lives in one place.
  • They give each step of a program a clear, descriptive name, so code reads closer to plain language.
  • A bug only needs fixing once, in the method itself, rather than everywhere the logic was copied.

As a program grows, the difference between a tangle of repeated logic and a set of small, well-named methods is often the difference between code that is easy to maintain and code that quietly becomes impossible to change safely.