+ 3

Do I need to specify «final» modifier for ALL local immutable variables in Java?

In one Java book I read “In general, it’s a good idea to always declare variables as final, and constant fields as static final, if they don’t need to be reassigned“. When I started to code, I discovered that almost all my local variables are immutable. So here are my questions: 1. Is it a good practice to make all local immutable variables «final»? 2. Do you use «final» modifier for all your immutable local variables in your programs? 3. If not, when do you use «final» and when do you skip using this keyword? Please see the code snippets that illustrate my question. https://code.sololearn.com/cI9X7YFqf155/?ref=app

20th Jan 2020, 9:20 PM
Jegors Čemisovs
Jegors Čemisovs - avatar
2 Answers
+ 1
If you want make your variable value constant throughout your program, then declare it final. In that case, it will good to declare as final because, if it is final, it cannot possible to change at run time so references to constant field resolved at compile time.. If it is not final, then if you create 100 objects, then 100 variables instance you create with same value so wasting memory. If it is final, only 1 instance it creates..
20th Jan 2020, 9:37 PM
Jayakrishna 🇮🇳
Jayakrishna 🇮🇳 - avatar
+ 1
here you cant use final, (if class has not constructor or initial block) class Person { final int id; //error final String firstName; } public class Program { public static void main(String[] args) { Person p = new Person(); p.id=123; p.firstName ="John"; } }
20th Jan 2020, 10:23 PM
zemiak