Java Methods (Functions) — Define, Call & Return Values
Methods (also called functions) let you organize code into reusable, named blocks. Instead of writing the same logic repeatedly, you define it once and call it whenever needed.
Defining a Method
public static int add(int a, int b) {
return a + b;
}
Anatomy
accessModifier static returnType methodName(parameterList) {
// method body
return value;
}
| Part | Example | Purpose |
|---|---|---|
| Access modifier | public |
Who can call it |
static |
static |
Belongs to class, not object |
| Return type | int |
Type of value returned |
| Method name | add |
How you call it |
| Parameters | int a, int b |
Input values |
return |
return a + b; |
Output value |
Calling a Method
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(5, 3);
System.out.println(result); // 8
System.out.println(add(10, 20)); // 30
}
}
void Methods — No Return Value
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
// no return statement needed
}
// Usage
greet("Alice"); // Hello, Alice!
You can use return; (without a value) to exit a void method early:
public static void printIfPositive(int n) {
if (n <= 0) return; // early exit
System.out.println(n);
}
Parameters and Arguments
Parameters are the variables in the method definition. Arguments are the values you pass when calling.
// parameters
public static double area(double width, double height) {
return width * height;
}
// arguments
double result = area(5.0, 3.0);
Pass by Value
Java always passes arguments by value:
public static void tryToChange(int x) {
x = 100; // only changes the local copy
}
int num = 5;
tryToChange(num);
System.out.println(num); // still 5
For objects, the reference is passed by value — you can modify the object’s fields but can’t reassign the reference.
Method Overloading
Multiple methods with the same name but different parameter lists:
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
public static int add(int a, int b, int c) {
return a + b + c;
}
// Java picks the right method based on arguments
System.out.println(add(2, 3)); // calls int version → 5
System.out.println(add(2.5, 3.5)); // calls double version → 6.0
System.out.println(add(1, 2, 3)); // calls 3-param version → 6
Overloading is based on:
- Number of parameters
- Types of parameters
- Order of parameter types
Return type alone does not differentiate overloaded methods.
Varargs — Variable Number of Arguments
public static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
System.out.println(sum(1, 2, 3)); // 6
System.out.println(sum(10, 20, 30, 40)); // 100
System.out.println(sum()); // 0
Rules:
- Only one varargs parameter per method
- Must be the last parameter
public static void log(String level, String... messages) {
for (String msg : messages) {
System.out.println("[" + level + "] " + msg);
}
}
Returning Multiple Values
Java methods return one value. For multiple values, use:
An Array
public static int[] minMax(int[] arr) {
int min = arr[0], max = arr[0];
for (int n : arr) {
if (n < min) min = n;
if (n > max) max = n;
}
return new int[]{min, max};
}
A Custom Object (preferred)
record MinMax(int min, int max) {}
public static MinMax findMinMax(int[] arr) {
// ... calculate
return new MinMax(min, max);
}
Complete Example
public class MathUtils {
public static boolean isEven(int n) {
return n % 2 == 0;
}
public static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
System.out.println(isEven(4)); // true
System.out.println(isPrime(17)); // true
System.out.println(factorial(5)); // 120
}
}
Best Practices
- One purpose per method — a method should do one thing well.
- Descriptive names —
calculateTax()notcalc(). - Keep methods short — if it’s over 20 lines, consider splitting.
- Limit parameters — more than 3-4 suggests you need an object.
- Return early — use guard clauses instead of deep nesting.
Quick Exercises
- Write a method
power(int base, int exp)that returns base raised to exp. - Write overloaded
maxmethods for 2 and 3 integers. - Write a method
isPalindrome(String s)that checks if a string reads the same forwards and backwards.
Summary
| Concept | Example |
|---|---|
| Define | public static int add(int a, int b) |
| Call | add(5, 3) |
| Void method | public static void greet(String name) |
| Overloading | Same name, different parameters |
| Varargs | int... numbers |
| Return | return value; |
What’s Next?
Methods use variables — but where a variable is accessible matters. Let’s learn about variable scope: Variable Scope.