Typing less to produce more is a feature of any modern IDE. IDEA provides top tier code completion support, as well as many other code generation, file template, and refactoring features.
Code Completion: Leveraging code completion is essential to productivity:
Ctrl+Space |
Basic. Completes the names of in-scope classes, methods, fields and keywords. Also complete paths, when appropriate |
Ctrl+Shift+Space |
Smart Type. Displays a suggestion list where the type of the object required can be inferred from the code, such as in the right hand side of assignments, return statements, and method call parameters |
Ctrl+Alt+Space |
Class Name. Completes the names of classes and interfaces. Accepts camel case matching on input |
Ctrl+Alt+Shift+Space |
Complete Word. Similar to Basic. |
Ctrl+Shift+Enter |
Complete Statement. Adds closing punctuation and moves cursor to next line |
Alt+Slash |
Expand Word. Cycles through suggested work choices, highlighting the prototype in the editor |
Confused by all the options? Just start using them and let muscle memory take over. It works.
Code Generation: Letting IDEA infer the code you want to create and drop in the appropriate template can be a huge time saver.
Ctrl+O |
Override Methods... quickly specify a parent method to override and create a stub implementation |
Ctrl+I |
Implement Methods... quickly specify a parent method to implement and create a stub |
Code->Delegate Methods... |
Delegate Methods... creates adapter classes by delegating method calls to member fields. A small wizard guides you through the delegation |
Ctrl+Alt+T |
Surround With... surrounds the current selection with a variety of code wrappers, like if/else, for, try/catch, synchronized, Runnable, and more |
Generate (Alt+Insert) provides its own set of powerful options for code generation:
Constructor |
Select any of your object's fields from a list to create a constructor with the proper parameters and body |
Getter |
Select a field from a list to create an accessor method |
Setter |
Select a non-final field from a list to create a mutator method |
equals() / hashCode() |
Provides a dialog to automatically create equals() and hashCode() methods based on your object's fields |
Live Templates are fragments of commonly occurring code, which can be inserted into the active file in a variety of ways. Learning the live templates will save you many, many keystrokes. A full list is available in Settings (Ctrl+Alt+S) Live Templates (K).
To insert a live template, press Ctrl+J followed by the following keys:
psf |
public static final |
thr |
throw new |
itar |
Iterate elements of an array |
sout |
Prints a string to System.out |
itco |
Iterate elements of collection |
soutm |
Prints the current class and method name to System.out |
ritar |
Iterate elements of array in reverse order |
soutv |
Prints the value of a variable to System.out |
toar |
Stores members of Collection in Array |
psvm |
main() method declaration |
Logging live templates are very useful, but many projects use log4J or Commons Logging instead of System.out. Replace the System.out calls with your framework within Settings (Ctrl+Alt+S) Live Templates (K).
Surround with Live Template (Ctrl+Alt+J) will surround the current selection with a block of code. Some of the useful surrounds are:
B |
Surround with { } |
R |
Surround with Runnable |
C |
Surround with Callable |
Use the existing surrounds templates to create your own, like surround with SwingUtilities.invokeLater() or new Thread().start()
Live Template in Multiple Languages: Many live templates exist for languages other than Java. JSP, XML, Spring definitions, and more all exist. Here are some examples of templates from other platforms and toolsets:
sb |
Creates an XML based Spring bean definition |
sbf |
Creates an XML based Spring bean definition instantiated by a factory method (many more Spring intentions exist, too) |
itws |
Generate Axis web service invocation (many more flavors of web services supported, too) |
CD |
Surround with CDATA section |
T |
Surround with <tag></tag> |
The free keymap from JetBrains provides a larger list of live templates. Post the keymap next to your monitor to learn the live templates quickly.
Refactoring: IDEA offers excellent refactoring support. Refactoring is aware of comments, reflection, Spring, AOP, JSP, and more. When the refactoring features are unsure on the safety of a refactoring, a preview mode is invoked so that you can verify the changes. Refactoring works on more than just Java code too: many refactorings exists for XML files as well as other languages. Learning the refactoring tools (and reading the refactoring literature, for that matter) is well worth your time. Here are some of the more common refactorings:
Rename |
Shift+F6 |
Renames a package, class, method, field or variable |
Move |
F6 |
Moves an entity |
Change Signature |
Ctrl+F6 |
Change the method or class name, parameters, return type, and more |
Extract Method |
Ctrl+Alt+M |
Moves the current selection to a new method, replacing duplicates if found |
Inline |
Ctrl+Alt+N |
Takes a method, variable, or inner class and replaces usages with a unique definition |
Introduce Variable |
Ctrl+Alt+V |
Moves the selected expression into a local variable |
Introduce Field |
Ctrl+Alt+F |
Moves the selected local variable into a field, prompting you for how initialization should occur |
Introduce Constant |
Ctrl+Alt+C |
Moves the selected variable or field into a static final field, replacing duplicates if found |
Introduce Parameter |
Ctrl+Alt+P |
Moves the selected local variable into a parameter argument, updating any callers in the process |
Extract Interface |
|
Moves a set of methods from the object onto an interface, updating callers to reference the interface if possible |
Pull Member Up |
|
Move a method from a subclass up to an interface or parent class |
Encapsulate Fields |
|
Provides getter and/or setters for the selected field |
Ctrl+Shift+J will join two lines together, which is a sort of shorthand for inline variable.
Improve Your Project's Quality
IDEA's features aren't just about writing code faster, they are also about coding more accurately. Understanding the intentions, inspections, and analysis tools are key to keeping code high quality.
Intentions: Keeps code clean by flagging potential problems in the Editor pane as they occur, and then offers an automated solution. An available intention is signaled by a lightbulb appearing in the left gutter, and the suggested fix can be applied by pressing Alt+Enter. There are several types of intentions:
- "Create from usage" intentions allow you to use new objects and methods without defining them first. Need a new method? Just call it from code and IDEA will prompt you to create it, inferring the parameter and result types. This works for classes, interfaces, fields, and variables. If the missing reference is in all capital letters, then IDEA will even create a constant for you.
- "Quick fix" intentions find common mistakes and makes context-based suggestions on how to fix them. Examples of issues flagged with a quick fix are assigning a value to the wrong type or calling a private method.
- "Micro-refactorings" fix code that compiles but could be improved. Examples are removing an unneeded variable and inverting an if condition.
Some of the intentions or fixes might violate your coding standard. Luckily, they can all be configured within Settings (Ctrl+Alt+S) Intentions (Q)
Intentions and Quick Fixes are indicated by different icons in the left gutter, but in practice there is little need to differentiate between the two:
|
Intention available |
|
Quick Fix available |
Inspections: Keeps code clean by detecting inconsistencies, dead code, probable bugs, and much, much more. The near-1000 default inspections can do a lot to enforce common idioms and catch simple bugs across the project. There are way too many inspections to list, but here are examples to provide a flavor of what inspections can do:
- Flag infinite recursion or malformed regular expression
- Catch error handling issues like continue within finally block or unused catch parameter
- Find threading issues like await() outside a loop or non-thread safe access
- Error on Javadoc issues like missing tags or invalid links
Inspections work with many languages and tools beyond the Java language, like Spring, JSF, Struts, XML, JavaScript, Groovy, and many others. The inspection set is highly configurable through Settings (Ctrl+Alt+S) Errors (6). Each inspection can carry its own set of options, and most can be shown as warnings or errors within the IDE. When an inspection violation is shown in the right gutter, Alt+Enter triggers the suggestions to be shown.
Some inspections appear within the Editor pane, while others appear within the Inspection pane when they are run as a batch. To run inspections for a scope, go to Analyze -> Inspect Code in the menu.
Inspection settings can be configured and shared across the team. An "IDE" inspection profile is saved within the user's $HOME directory, but a "Project" profile is saved within the IDEA project file. This means a shared, version controlled project file can be created which contains the team's inspections.
Code Analysis: Provides several different views of dependencies and duplicates within your project. These tools help you modularize your code and find areas of potential reuse. All of the following features are available from the Analyze menu.
The Dependency Viewer provides a split tree-view of your project with a list panel at the bottom. From here you can navigate the dependencies or mark certain undesirable dependencies as illegal. Which analysis feature chosen determines what the Viewer displays:
Dependencies |
Left: Your packages. Right: Packages your code depends on |
Backward Dependencies |
Left: Your packages. Right: Packages that depend on your code. Bottom: Line by line usages |
Cyclic Dependencies |
Left: All of your packages that have a cyclic dependency. Right: The objects that form the cycle. Bottom: Line by line usages |
Not all analysis tools report to the Dependency Viewer, however. Module Dependencies uses a separate panel to display dependencies across all the included modules within the project. This is useful for multi-module projects. Dependency Matrix launches the Dependency Structure Matrix in a separate window. This tool helps you visualize module and class dependencies across the project using a colored matrix.
Locate Duplicates: Finds suspected copy and pastes within your project or desired scope. Use this to find and consolidate duplicate modules or statements. The results are displayed in the Duplicates pane, which ranks the copy/paste violations and allows you to extract methods on the duplicates by simply clicking the Eliminate duplicates icon ().
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}