Reference · module 3
Methods
Everything this module explains, on one page.
Writing a method
Define and call a method with parameters.
- A method is a named block of code. static void greet(String name) { ... } declares one: void means it returns nothing, and name is a parameter of type String.
- Every parameter needs its type: static int add(int a, int b). Parameters are separated by commas, and each one is a local variable inside the method.
- Call a method by name with arguments in brackets: greet("Ana"); The arguments must match the parameters in number, order and type.
The mistake you are about to make
static int add(a, b)
static int add(int a, int b)
In Python and JavaScript parameters have no types, so the names seem enough. Java requires a type before every parameter, or it does not compile.
Returning a value
Return results from methods and use them.
- return sends a value back to the caller and ends the method: static int square(int n) { return n * n; } Then int x = square(4); stores 16.
- The returned value must match the declared type. A method declared int must return an int on every path, or the program does not compile.
- Printing is not returning. A method that only prints shows a number on screen, but the caller gets nothing it can calculate with.
The mistake you are about to make
static int square(int n) { System.out.println(n * n); }
static int square(int n) { return n * n; }
Seeing the number printed feels like the method gave it back. Only return hands a value to the caller, and an int method without it does not compile.
Scope and overloading
Know where a variable exists and use methods with the same name.
- A variable declared inside a method exists only in that method. Two methods can each have their own x, and they never see each other's.
- Braces make a block, and a variable declared in a block ends with it. The i of a for loop cannot be used after the loop.
- Overloading means several methods with the same name but different parameters: add(int a, int b) and add(double a, double b). Java picks one by the argument types.
The mistake you are about to make
for (int i = 0; i < 3; i++) {} System.out.println(i);
int i; for (i = 0; i < 3; i++) {} System.out.println(i);
The loop has finished and i was 3 at the end, so it seems still available. It was declared inside the for, so it ends with the loop.