final Parameters
What you'll learn: How to prevent accidental reassignment of method parameters inside the method body using the final keyword.
The Core Idea
When you declare a method parameter as final, you're telling Java: "This parameter's value cannot be changed inside this method." The parameter arrives with a value when the method is called, and that value is locked in—you cannot reassign it to something else.
Think of it like receiving a sealed envelope with instructions. You can read what's inside, you can use the information, but you cannot replace the paper inside the envelope with different instructions.
Why Use final on Parameters?
Using final on parameters helps prevent bugs. Sometimes in a long method, you might accidentally reassign a parameter, losing the original value you were passed. Marking it final makes the compiler stop you:
public void processAge(final int age) {
// age = age + 1; // Compilation error! Cannot assign to final parameter
int nextAge = age + 1; // This is fine—using the value, not changing it
System.out.println("Age: " + age);
System.out.println("Next year: " + nextAge);
}
The final keyword doesn't affect how you call the method—it only restricts what happens inside the method.
When to Use It
Many developers use final on parameters as a defensive practice, especially in methods with complex logic where accidentally overwriting a parameter could introduce subtle bugs. It's optional, but it adds a layer of safety.
Key Takeaway: The final keyword on method parameters prevents reassignment inside the method, protecting the original value and reducing the risk of accidental bugs.