Methods and varargs
Write methods, overload them safely, and understand what Java actually passes to them.
Open this lesson in the learning hubKey points
- A method has a return type, a name and a parameter list.
voidmeans it returns nothing. - Overloading means same name, different parameter list. The compiler picks the match from the argument types.
- Java is always pass-by-value. Reassigning a parameter inside a method never affects the caller.
- That value can be a reference, so mutating the object a parameter points at is visible to the caller.
- Varargs
int... numbersaccepts zero or more arguments and arrives inside the method as an array. - Only one varargs parameter per method, and it must come last.
Example
import java.util.ArrayList;
import java.util.List;
public class Main {
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
static String greet(String name) {
return greet(name, "Hello");
}
static String greet(String name, String word) {
return word + ", " + name + "!";
}
static void tryToRename(String s) {
s = "changed";
}
static void addItem(List<String> cart) {
cart.add("book");
}
public static void main(String[] args) {
System.out.println("sum() = " + sum());
System.out.println("sum(1,2,3) = " + sum(1, 2, 3));
System.out.println("sum(array) = " + sum(new int[]{10, 20}));
System.out.println(greet("Ada"));
System.out.println(greet("Ada", "Welcome"));
String original = "kept";
tryToRename(original);
System.out.println("String arg after call: " + original);
List<String> cart = new ArrayList<>();
addItem(cart);
System.out.println("List arg after call: " + cart);
}
}
Pass-by-value always, but that value can be a reference to a mutable object.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.