Skip to content
AgileLogics
5 min read

Methods

Prerequisites: Multidimensional arrays

A method is a named, reusable block of code — every method in Java declares both a return type and the type of each parameter.

Syntax

static int add(int a, int b) {
    return a + b;
}

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

Example

static int square(int n) {
    return n * n;
}

public static void main(String[] args) {
    System.out.println(square(4));
}

Expected output

16

Common mistakes

  • Declaring a return type of int but having a code path that doesn't return a value — this is a compile error ("missing return statement"), not something discovered at runtime.
  • Using void but still trying to return a value.

Practice

Write a method isEven(int n) that returns true if n is even.

Show solution
static boolean isEven(int n) {
    return n % 2 == 0;
}