Search code examples
javaintellij-ideacode-metricscode-inspection

How to remove unused code in IntelliJ IDEA?


In IntelliJ, in a .java file, some unused code is greyed out indicating that the declared variable or function is never used. Unused imports are removed using Ctrl+Alt+O. Is there any shortcut to remove those unused declarations?


Solution

  • As @Magnilex pointed out, hover over the unused variable / method and hit alt + enter to open the intentions menu (if that's how its called).

    But in addition to this, don't just remove / safe delete this on variable, but choose "Fix all 'Unused declaration' problems in this file" which will not only get rid of this one, but of all.

    See here: IDEA safe delete interactions menu

    An alternative approach might be to us the "Run inspections by name" and run the "Unused declaration" inspection for your whole project / module / Package, whatever.

    This can be achieved by either right clicking on the editor, and chosing >Analyze >Run Inspection by Name from the context menu (or the keyboard short cut, which is ctrl+alt+shift+i by default). Then type "Unused declaration":

    IDEA run inspections Unused declaration

    This will inspect your code for unused declarations and display them in an overview:

    Idea inspection overview

    See also https://stackoverflow.com/a/56593832/2987273