Extract/Introduce variable
If you come across an expression that is hard to understand or it is duplicated in several places throughout you code, the Extract Variable refactoring can help you deal with those problems placing the result of such expression or its part into a separate variable that is less complex and easier to understand. Plus, it reduces the code duplication.
Starting with Java 1.8 and later versions, IntelliJ IDEA also lets you extract a functional type variable.
If your Java version supports the pattern matching (Java 14 preview or higher) and you are extracting a cast expression under the instanceof
check, IntelliJ IDEA may introduce a pattern variable at that instanceof
check instead of a normal local variable. Also, you can inline pattern variable since the Java 14 version. In this case, all the occurrences will be replaced with old-style cast expression.
You can use the Introduce Variable refactoring to extract variadic arguments into a new slice variable.
In the editor, select an expression or its part that you want to extract. You can also position the caret within the expression, in this case IntelliJ IDEA offers you a list of potential code selections.
Press Ctrl+Alt+V or from the main menu, select Refactor | Extract/Introduce | Variable.
- Select a name suggested in the popup or type your own and press Enter.
If IntelliJ IDEA finds more than one occurrence, it lets you specify a scope and extract just a part of the found occurrences and not just all of them.
You can also declare the variable you are extracting as
If you want to reassign the existing variable to a new one , press Ctrl+Alt+V. If you have more than one existing variable, IntelliJ IDEA displays a list to choose from.final
.You can press Shift+Tab to change a type of the variable.
If the In modal dialogs refactoring option is selected in the Refactorings area on the Code Editing page of the Settings/Preferences dialog Ctrl+Alt+S, IntelliJ IDEA opens the Extract Variable dialog for this refactoring.

Example
Let's extract the anotherClass.inValue()
variable that occurs twice throughout the code and give it a name number
.
Before | After |
---|---|
|
|