Example
| Before | After |
|---|---|
public void method() { int a=1; int b=2; int c=a+b; int d=a+c; } |
public void method() { int a=1; int b=2; int c=add(a,b); int d=add(a,c); } ... private int add(int a, int b) { return a+b; } |
public ArrayList method() { String[] strings = {"a","b","c"}; ArrayList list = new ArrayList(); for (int i=0; i < strings.length; i++) {list.add(strings[i]);} return list; } |
public ArrayList method() { String[] strings = {"a","ab","abc"}; ArrayList list=add(strings); return list; } private ArrayList add(String[] strings) { ArrayList list = new ArrayList(); for (int i=0; i < strings.length; i++) {list.add(strings[i]);} return list; } |
- In the editor, select a block of code to be transformed into a method or a function.
Tip
The code fragment to form the method does not necessarily have to be a set of statements. It may also be an expression used somewhere in the code.
- On the main menu or on the context menu of the selection, choose or press Ctrl+Alt+MCtrl+Alt+M.
- In the Extract Method dialog box that opens, specify the name of the new method.
- To create a static method, select the Declare Static check box.
- In the Parameters area, do the following:
- Specify the variables to be passed as method parameters, by selecting/clearing the corresponding check boxes; if a parameter is disabled, a local variable of the corresponding type, with the initial value ... will be created in the extracted method, so that you will have to enter the initializer with an appropriate value manually.
- Rename the desired parameters, by double-clicking the corresponding parameter lines and entering new names.
- In the Visibility area define the method's visibility scope.
- Check the result in the Signature Preview pane and click OK to create the method. The selected code fragment will be replaced with a method call. Additionally, IntelliJ IDEA will propose to replace any similar code fragments found within the current class.
Tip
You can extract methods from the repetitive code fragments, which IntelliJ IDEA finds in course of the duplicates analysis. The encountered duplicates display in the Duplicates tool window, where you can try to replace them with method calls.

