• Post Reply Bookmark Topic Watch Topic
  • New Topic

Practically using final and main?  RSS feed

 
Pete Letkeman
Ranch Foreman
Posts: 906
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fairly often we see the following line or some variation of it

One variation that I came upon yesterday was

I've tested this and it compiles and run fine.
However I was wondering how practical is it to use final in the main method parameters?
I've used javap -c on a simple program which used final that way and then again on when final was not used and the output was the same for both.

Is there a practical difference to using final this way? If so what is it?
 
Stephan van Hulst
Saloon Keeper
Posts: 7985
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The final keyword rarely translates to different bytecode when applied to local variables (which method parameters are). The main() method is just a method like any other. I think final variables can have their values inlined, but only in the case of compile time constants.

Some people like to use the final keyword on method parameters to ensure themselves that they won't edit a variable that's only meant as input. Personally I find it a bit verbose.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It used to be required when passing the parameters on to an anonymous class' instance.Until Java7 that sort of code wouldn't compile because the parameter args wasn't marked final. The reason is that the anonymous Runnable class uses that parameter, and the lifetime of the object may be longer than that of the method. So the object takes a copy of the parameter and keeps it. But what if it is reassigned after that copy has been taken? That would mean the method has one object and the anonymous class's instance has a different object. If you mark the parameter final, the javac tool can “be confident” that it won't be changed.
I believe the Java8 version of javac checks through the method to confirm that args isn't reassigned, so the final becomes redundant.
 
Pete Letkeman
Ranch Foreman
Posts: 906
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your valuable insight into this Campbell Ritchie and Stephan van Hulst.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's a pleasure
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!