A method is a named block of code that does one job and can be called many times. Methods keep main short, let you test each piece on its own, and give each job a clear name. This lesson covers declaring methods, parameters and return values, overloading, variable-length arguments, recursion, and how Java passes arguments.
In this lesson you will learn
- The parts of a method declaration
- Return types, including
void - Method overloading
- Varargs (
int... nums) - Recursion, and why Java is “pass by value”
Declaring and Calling Methods
public class Main {
static int square(int n) {
return n * n;
}
static double average(int[] values) {
if (values.length == 0) return 0;
int sum = 0;
for (int v : values) sum += v;
return (double) sum / values.length;
}
static void greet(String name) { // void: returns nothing
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
System.out.println(square(7));
System.out.println(average(new int[]{70, 85, 90}));
greet("Tania");
}
}
Output
49
81.66666666666667
Hello, Tania!
A method declaration has these parts:
- Modifiers:
staticletsmaincall the method without creating an object. Methods on objects come in Java Classes and Objects. - Return type:
int,double, and so on, orvoidwhen nothing is returned. - Name and parameters:
square(int n). Each parameter needs a type. returnsends a value back and ends the method.average()returns early when the array is empty.
Overloading, Varargs, Recursion and Passing
public class Main {
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; } // overloading
static int add(int a, int b, int c) { return a + b + c; }
static int sum(int... nums) { // varargs
int total = 0;
for (int n : nums) total += n;
return total;
}
static int factorial(int n) { // recursion
return n <= 1 ? 1 : n * factorial(n - 1);
}
static void tryChange(int x, int[] arr) {
x = 100; // changes only the local copy
arr[0] = 100; // changes the array the caller sees
}
public static void main(String[] args) {
System.out.println(add(2, 3) + " " + add(2.5, 1.5) + " " + add(1, 2, 3));
System.out.println(sum() + " " + sum(4, 5, 6));
System.out.println(factorial(5));
int num = 1;
int[] data = {1, 2};
tryChange(num, data);
System.out.println(num + " " + data[0]);
}
}
Output
5 4.0 6
0 15
120
1 100
- Overloading: several methods can share a name if their parameter lists differ. Java picks the right
addfrom the argument types. - Varargs:
int... numsaccepts any number ofintarguments, including none, and treats them as an array. - Recursion:
factorialcalls itself on a smaller problem until it reaches the base casen <= 1. 5! = 120. - Pass by value: Java copies each argument. Changing the copy of
numhad no effect outside. The array copy, however, still points to the same array, soarr[0] = 100was visible to the caller.
Common Mistakes
- Missing return. A non-void method must return a value on every path, or the code does not compile.
- Overloading by return type only.
int f()anddouble f()cannot both exist; the parameters must differ. - Recursion without a base case, which ends in
StackOverflowError. - Calling an instance method from
static mainwithout an object.
Practice Exercises
Exercise 1. Write isPrime(int n) that returns true for prime numbers.
Show answer
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; (long) i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
Exercise 2. Write a recursive power(base, exp) for non-negative exp.
Show answer
static long power(long base, int exp) {
return exp == 0 ? 1 : base * power(base, exp - 1);
}
Frequently Asked Questions
Is Java pass by value or pass by reference?
Always pass by value. For objects and arrays the value copied is a reference, so a method can change the object’s contents but cannot make the caller’s variable point to a different object.
What is the difference between a method and a function?
In Java every function belongs to a class, so they are all called methods. static methods behave most like plain functions.
Summary
- A method has modifiers, a return type, a name and typed parameters.
voidmethods return nothing; others must return on every path.- Overloading needs different parameter lists; varargs take any number of values.
- Java passes copies of values; references let methods change shared objects.
Next: Java Classes and Objects.
