Methods
A method is a named block of code that performs one task. Methods let you reuse code instead of copying it, give operations meaningful names, and break big problems into small, testable pieces. You've been using methods all along — println, length, Math.max — now you'll write your own.
Defining and calling a method
void greet() { System.out.println("Welcome to the shop!"); } void main() { greet(); greet(); }
Welcome to the shop! Welcome to the shop!
A method declaration has a return type (void means "returns nothing"), a name, parentheses for parameters, and a body. Call it by writing its name followed by parentheses.
Parameters
void greet(String name, int visits) { System.out.println("Hello " + name + ", visit number " + visits); } void main() { greet("Ana", 3); greet("Ben", 1); }
Hello Ana, visit number 3 Hello Ben, visit number 1
Parameters are variables listed in the declaration; arguments are the actual values passed in the call. They're matched by position and type.
Returning a value
double priceWithVat(double net) { return net * 1.23; } boolean isEven(int n) { return n % 2 == 0; } void main() { double gross = priceWithVat(10.0); System.out.println(gross); System.out.println(isEven(7)); System.out.println(priceWithVat(priceWithVat(1))); }
12.3 false 1.5129
The return type says what kind of value comes back; return sends it. A method call can be used anywhere a value of that type can — even as another call's argument.
Early return
String classify(int age) { if (age < 0) { return "invalid"; } if (age < 18) { return "minor"; } return "adult"; } void main() { System.out.println(classify(-5)); System.out.println(classify(12)); System.out.println(classify(40)); }
invalid minor adult
return ends the method immediately. Handling special cases first and returning early keeps the main logic flat. A non-void method must return a value on every path, or it won't compile.
static methods in a class
public class Main { static int square(int x) { return x * x; } public static void main(String[] args) { System.out.println(square(9)); } }
81
In the traditional class form, helper methods called from static main must also be static — you'll see this everywhere. (In compact source files that isn't necessary.) Lesson 24 explains static fully.
Why methods matter
- Reuse: write the logic once, call it many times.
- Naming:
isEligibleForDiscount(order)explains itself. - Testing: small methods with clear inputs and outputs are easy to test (lesson 54).
- Change: fix a bug in one place.
Good methods do one thing, have descriptive verb-based names, and are short enough to read at a glance.
Try it yourself
Write a method that converts Celsius to Fahrenheit and use it in a loop.
-10°C = 14.0°F 0°C = 32.0°F 10°C = 50.0°F 20°C = 68.0°F 30°C = 86.0°F 40°C = 104.0°F