IntelliJ IDEA 2019.2 Help

Extract constant

The Extract Constant refactoring makes your source code easier to read and maintain. It also helps you avoid using hardcoded constants without any explanations about their values or purpose.

  1. In the editor, select an expression or declaration of a variable you want to replace with a constant.

  2. Press Ctrl+Alt+C to introduce a constant or select Refactor | Extract | Constant.

    extract constant

    Select a name from a list that opens or type your own name and press Enter.

  3. If you press Ctrl+Alt+C twice, the Extract Constant dialog opens.

    the Extract Constant dialog

  4. Specify additional options for the constant, for example, change its visibility, or move the constant to another class.

Example

Let's introduce a constant for the expression "string" that occurs twice throughout code.

Before

After

public class Class { public void method() { ArrayList list = new ArrayList(); list.add("string"); anotherMethod("string"); } private void anotherMethod(String string) { } }
public class Class { private static final String STRING ="string"; public void method() { ArrayList list = new ArrayList(); list.add(STRING); anotherMethod(STRING); } private void anotherMethod(String string) { } }
Last modified: 19 August 2019