Inspectopedia Help

'if' can be replaced with 'switch'

Reports if statements that can be replaced with switch statements.

The replacement result is usually shorter and clearer.

Example:

void test(String str) { if (str.equals("1")) { System.out.println(1); } else if (str.equals("2")) { System.out.println(2); } else if (str.equals("3")) { System.out.println(3); } else { System.out.println(4); } }

After the quick-fix is applied:

void test(String str) { switch (str) { case "1" -> System.out.println(1); case "2" -> System.out.println(2); case "3" -> System.out.println(3); default -> System.out.println(4); } }

This inspection only reports if the language level of the project or module is 7 or higher.

Use the Minimum number of 'if' condition branches field to specify the minimum number of if condition branches for an if statement to have to be reported. Note that the terminal else branch (without if) is not counted.

Use the Suggest switch on numbers option to enable the suggestion of switch statements on primitive and boxed numbers and characters.

Use the Suggest switch on enums option to enable the suggestion of switch statements on enum constants.

Use the Only suggest on null-safe expressions option to suggest switch statements that can't introduce a NullPointerException only.

Inspection options

Here you can find the description of settings available for the 'if' can be replaced with 'switch' inspection, and the reference of their default values.

Minimum number of 'if' condition branches

3

Suggest switch on numbers

Not selected

Suggest switch on enums

Not selected

Only suggest on null-safe expressions

Default: Selected

Inspection Details

Available in:

IntelliJ IDEA 2024.2, Qodana for JVM 2024.2,

Plugin:

Java, 242.SNAPSHOT

Last modified: 20 February 2024