← Java from Scratch
Lesson 24 of 88 · 10 XP
Method parameters
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
static void hit(String who, int damage) {
System.out.println(who + " takes " + damage);
}
static int sum(int... xs) { // varargs: any number of arguments, an array inside
int s = 0;
for (int x : xs) s += x;
return s;
}
hit("Orc", 25);
sum(1, 2, 3); // 6
sum(); // 0
In Java everything is passed by value. For primitives it's a copy of the number — the method won't change the variable outside. For objects and arrays the reference is copied: a method can change the contents of an array, but it can't "swap" the array itself for the caller.
static void reset(int[] a) { a[0] = 0; } // changes outside too
static void replace(int[] a) { a = new int[3]; } // doesn't change anything outside
Java has no default parameters — overloading is used instead (the next lesson).
Task. Finish static void addToAll(int[] a, int k) (add k to every element) and
static int max(int... xs).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.