Java method overloading, varargs, and pass by value
Overloading lets several methods share a name if their parameter lists differ. The compiler picks the one that fits the argument types. A varargs parameter, written int..., accepts any number of arguments and is seen inside the method as an array.
Java
class Main {
static int sum(int a, int b) {
return a + b;
}
static double sum(double a, double b) {
return a + b;
}
static int sum(int... values) {
int total = 0;
for (int v : values) {
total += v;
}
return total;
}
static void bump(int x) {
x++;
}
static void bumpAll(int[] values) {
for (int i = 0; i < values.length; i++) {
values[i]++;
}
}
public static void main(String[] args) {
System.out.println(sum(2, 3));
System.out.println(sum(2.5, 3.0));
System.out.println(sum(1, 2, 3, 4, 5));
int n = 10;
bump(n);
int[] data = {1, 2, 3};
bumpAll(data);
System.out.println(n + " " + data[0] + data[1] + data[2]);
}
}