aspose file tools*
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
Author

why we make method parameters final.

Arav Kumar
Greenhorn

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.


Regards
Arav Kumar.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14345
    
  22

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
Hi,

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.


Regards,
Rok


SCJP, SCWCD
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39826
    
  28
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: http://aspose.com/file-tools
 
subject: why we make method parameters final.