Methods
Prerequisites: Multidimensional arrays
A method is a named, reusable block of code — every method in Java declares both a return type and the type of each parameter.
Syntax
static int add(int a, int b) {
return a + b;
}
static void greet(String name) {
System.out.println("Hello, " + name);
}
Example
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
System.out.println(square(4));
}
Expected output
16
Common mistakes
- Declaring a return type of
intbut having a code path that doesn't return a value — this is a compile error ("missing return statement"), not something discovered at runtime. - Using
voidbut still trying toreturna value.
Practice
Write a method isEven(int n) that returns true if n is even.
Show solution
static boolean isEven(int n) {
return n % 2 == 0;
}