Exercise 1 of 4
Your First Method
A method is a reusable block of code with a name.
static void hello() {
IO.println("Hello!");
}
void means: the method doesn't return anything, it just does something.
The method greet is already defined. Call it in main.
Starter code
void greet() {
IO.println("Welcome!");
}
void main() {
// Call greet()
}
Background
The call stack
When a method gets called, the JVM pushes a new stack frame onto the call stack. It holds the parameters, the local variables and the return address.
When the method ends, the frame is removed again and execution jumps back. Too many nested calls (e.g. endless recursion) → StackOverflowError.
Exercise 2 of 4
Method with a Parameter
Methods can take input values (parameters):
static void sayHello(String name) {
IO.println("Hello " + name);
}
The method printDouble takes a number and prints twice its value. Add the one missing line.
Starter code
void printDouble(int number) {
// Print number * 2
}
void main() {
printDouble(5);
printDouble(12);
}
Background
Pass by value
Java always passes parameters by value — the method gets a copy of the value. If you change the parameter inside the method, the original variable stays the same.
With objects, the reference gets copied — so you can change the object itself, but not the reference. That trips up beginners all the time.
Exercise 3 of 4
Return
Instead of just printing something, a method can return a value:
static int timesTwo(int x) {
return x * 2;
}
Instead of void you now write the return type (int), and return hands the value back.
Add the return line so that square returns the square of the number.
Starter code
int square(int n) {
// Return n * n
return 0;
}
void main() {
IO.println(square(4));
IO.println(square(7));
}
Background
void vs. return type
void = "this method returns nothing". Any other type (int, String, etc.) forces you to return a value with return.
The compiler checks that every possible path ends in a return. If you have an if without an else and only return inside it, Java complains — after all, the condition might be false.
Exercise 4 of 4
Two Parameters
Methods can have several parameters — separated by commas:
static int add(int a, int b) {
return a + b;
}
Fix the return line: return the larger of the two values.
Tip: You can write: if (a > b) return a; else return b;
Starter code
int max(int a, int b) {
// Return the larger value
return 0;
}
void main() {
IO.println(max(3, 7));
IO.println(max(10, 2));
}
Background
Method overloading
In Java you can have several methods with the same name, as long as their parameters differ. That's called overloading:
int max(int a, int b) and double max(double a, double b) can exist side by side. Java automatically picks the right version based on the types you pass in.