Calling methods
Everything is passed by value. Including references, which is where the confusion starts.
int result = Math.max(a, b); // static — on the class
String upper = name.toUpperCase(); // instance — on an object
The values in the call are arguments; the names in the declaration are parameters.
Pass by value, always
Java has no pass-by-reference. Every argument is copied.
For primitives this is obvious:
void increment(int x) { x++; }
int n = 5;
increment(n); // n is still 5
For objects it is the part people get wrong. What is copied is the reference, so both the caller and the method refer to the same object. You can change the object:
void addItem(List<String> list) {
list.add("new"); // caller sees this
}
But reassigning the parameter changes only the local copy:
void replace(List<String> list) {
list = new ArrayList<>(); // caller sees nothing
}
“Java passes objects by reference” is a common phrase and it is wrong. It passes references by value. The distinction is exactly the difference between those two methods.
Overloading
Several methods may share a name if their parameters differ:
println(int)
println(String)
println(char[])
The compiler picks based on the compile-time types of the arguments, preferring an exact match, then widening, then boxing, then varargs. It is resolved at compile time, unlike overriding, which is resolved at run time.
Overloads that differ only in ways requiring boxing or a cast to distinguish are a reliable source of confusion. remove(int) and remove(Object) on List is the standard example: list.remove(2) removes the element at index 2, while list.remove(Integer.valueOf(2)) removes the value 2.
Varargs
static int sum(int... values) {
int total = 0;
for (int v : values) total += v;
return total;
}
sum(); // 0
sum(1, 2, 3); // 6
Inside the method values is an array. Varargs must be the last parameter, and there can be only one.
Return
return ends the method immediately. A method declared void may use a bare return to exit early, which is often clearer than wrapping the remainder in an if.