Defining & calling methods
Return types, parameters, the return statement, and void.
Methods: named, reusable code
A method has a return type, a name, a parameter list, and a body. Use void when nothing is returned:
// returns an int
public static int add(int a, int b) {
return a + b;
}
// returns nothing
public static void greet(String name) {
System.out.println("Hello, " + name);
}
// calling:
int result = add(3, 4); // 7
greet("Ada"); // Hello, Ada
Key rules:
- Every non-void method must have a return on every reachable path — the compiler checks this ("missing return statement" is a compile error).
- A void method may have return; (with no value) to exit early.
- Arguments are matched to parameters by position, not name.
- Java is strictly typed — you cannot pass the wrong type without an explicit cast.