File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes why we make method parameters final. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "why we make method parameters final." Watch "why we make method parameters final." New topic

why we make method parameters final.

Arav Kumar

Joined: May 27, 2008
Posts: 14
Hi to all Ranchers,

Please explain what is the reason and use to make method parameters final. In what circumstances we make method parameters final.

Arav Kumar.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15080

I wouldn't normally make method arguments final; arguments are passed by value, if you change the variable, it will not change the original variable in the calling method - so it doesn't really make sense to make arguments final.

There is one case in which you might want to do it: if you need to use the argument in an anonymous inner class. For a local variable (or argument) to be used in an anonymous inner class, it must be final. For example:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Rok Štelcer
Ranch Hand

Joined: Nov 03, 2009
Posts: 101

You should declare a parameter as final, when/if it’s going to be used in a local inner class.
For example:

Hope this helps.


Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46320
It is often unnecessary, but it can't do any harm to declare arguments final. That simply means you are promising the compiler you won't re-assign them in the method. Usually unnecessary (except when required for an anonymous inner class).
I agree. Here's the link:
subject: why we make method parameters final.
It's not a secret anymore!