Intellij Idea - automatically add final keyword to the generated variables

JavaIntellij Idea

Java Problem Overview


The new introduced code convention require to use the "final" keyword where possible.

The question is - is there a possibility to automatically generate the variables with this keyword ? For example - I select a code fragment:

"bla"+"bla"+"bla"

and press ctrl+alt+v - the IDE generates a variable like this:

String blaString = "bla"+"bla"+"bla";

but I need it to be

final String blaString = "bla"+"bla"+"bla";

P.S. I know about inspections and the possibility "fix them all", but it can't be used everywhere as there is a lot of old code that shouldn't be refactored without reason.

Java Solutions


Solution 1 - Java

Go to preferences -> Code Style -> Code Generation and enable "Make generated local variables final" in the "Final modifier" section. You can also try searching for "final" in preferences.

Solution 2 - Java

In IntelliJ 14.1.3

  1. Preferences > Editor > Code Style > Java
  2. To the far right ,there's a tab called Code Generation
  3. In the section called Final Modifier there are two choices: * Make generated local variables final * Make generated parameters final

Solution 3 - Java

For Windows User;

Go to File -> Settings -> Editor -> Code Style -> Select Preferred Language (Java) -> Checkbox -> Make generated local variables final, Make generated parameters final -> Apply -> OK

Solution 4 - Java

After selecting "introduce local variable" there is a little gear to the right of the variable name. Click that and check "Declare final". That variable will be marked as final and Intellij will remember your preference until changed.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStKillerView Question on Stackoverflow
Solution 1 - JavaJake WalshView Answer on Stackoverflow
Solution 2 - JavaAndreyView Answer on Stackoverflow
Solution 3 - JavaViraj PaiView Answer on Stackoverflow
Solution 4 - JavaSteven BayerView Answer on Stackoverflow