Lesson 7 of 20

Methods

Methods

Methods are named blocks of code that can accept parameters and return values.

static int add(int a, int b) {
    return a + b;
}
  • static — can be called without creating an object
  • int — return type (use void for no return value)
  • Parameters are typed and comma-separated

Method Overloading

Java allows multiple methods with the same name if their parameter types differ:

static int max(int a, int b) { return a > b ? a : b; }
static double max(double a, double b) { return a > b ? a : b; }

System.out.println(max(3, 7));      // 7
System.out.println(max(3.5, 2.1));  // 3.5

Return Types

static String greet(String name) {
    return "Hello, " + name + "!";
}
static void printLine() {
    System.out.println("---");
}

Your Task

Implement and call three static methods:

  • multiply(int a, int b) → returns a * b
  • average(double a, double b, double c) → returns the average
  • repeat(String s, int n) → returns s repeated n times

Print multiply(6, 7), average(1.0, 2.0, 3.0), and repeat("ha", 3).

TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.