CodeBlanks Logo Icon CodeBlanks

final parameters

Learn immutability with final parameters.

final parameters

If you mark a parameter as final, it cannot be reassigned inside the method. This prevents accidental changes to the parameter and clearly shows the intent of the code.

static int doubleOf(final int x) {
  // x = 10; // compile error
  return x * 2;
}

Here, reassigning x is a compile error. final parameters become especially important in lambdas and inner classes; there, outer variables must be effectively final.

Practical use of final

final parameters are not always necessary; but they make intent clear. Especially when the method body is long, guaranteeing that the parameter does not change is valuable.

static void printArea(final int width, final int height) {
  int area = width * height;
  System.out.println("Area: " + area);
}

Here width and height are constant throughout the method. This gives confidence to whoever reads the code. On the call side, final has no effect.

Practice Compute area (with final)

Define a static void method called printArea; parameters final int width, final int height. The body should compute the area and print it as Area: <area>. Call printArea(5, 3) from main.

Starter code

Main.java
public class Main {
  public static void main(String[] args) {
    // Call the method with 5 and 3
  }
  // Define the printArea method here
}

Sample solution

Main.java
static void printArea(final int width, final int height) {
  System.out.println("Area: " + (width * height));
}
// inside main:
printArea(5, 3);

Expected output

Area: 15

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a compile error in a method with a final int x parameter?

  • int y = x + 1;
  • x = 10; Correct answer
  • return x * 2;
  • System.out.println(x);

Explanation: A final parameter cannot be reassigned.

2 Fill in the blank: final parameter

Question
static int doubleOf(____ int x) {
  return x * 2;
}
Answer
static int doubleOf(final int x) {
  return x * 2;
}

Explanation: With final int x, the parameter cannot be changed.

3 Match keyword to role

Term Meaning
static Defines at class level
final Prevents reassignment
void Returns no value
return Hands a value out

All lessons in Beginner