Tips and Tricks

Editing source

Content assist Content assist provides you with a list of suggested completions for partially entered strings. In the Java editor press Ctrl+Space or invoke Edit > Content Assist.

Content assist selection dialog

Content assist in Javadoc comments Content assist is also available in Javadoc comments.

Content assist for Javadoc comments

Content assist for variable, method parameter and field name completions

You can use content assist to speed up creation of fields, method parameters and local variables. With the cursor positioned after the type name of the declaration, invoke Edit > Content Assist or press Ctrl+Space.

Suggestions for field names

If you use a name prefix or suffix for fields, local variables or method parameters, then be sure to specify this in the Code Generation preference page (Window > Preferences > Java > Code Generation > Names).

Parameter Hints With the cursor in a method argument, you can see a list of parameter hints. In the Java Editor press Ctrl+Shift+Space or invoke Edit > Parameter Hints.

Parameter hint hover

Content assist on anonymous classes Content assist also provides help when creating an anonymous class. With the cursor positioned after the opening bracket of a class instance creation, invoke Edit > Content Assist or press Ctrl+Space.

Content assist for an anonymous class

This will create the body of the anonymous inner class including all methods that need to be implemented.
Toggle between inserting and replacing code assist When code assist is invoked on an existing identifier, code assist can either replace the identifier with the chosen completion or only do an insert. The default behaviour (overwrite or insert) is defined in Window > Preferences > Java > Editor > Code Assist.
You can temporarily toggle the behaviour while inside the content assist selection dialog by pressing the Ctrl key while selecting the completion.
Create Getter and Setters To create getter and setter methods for a field, select the field's declaration and invoke Source > Generate Getter and Setter.

Generate Getter and Setter dialog

If you use a name prefix or suffix be sure to specify this in the Code Generation preference page (Window > Preferences > Java > Code Generation > Names)
Delete Getters and Setters together with a field When you delete a field, Eclipse can offer deleting Getter and Setter methods for it. If you use a name prefix or suffix for fields, then be sure to specify this in the Code Generation preference page (Window > Preferences > Java > Code Generation > Names).
Create delegate methods To create a delegate method for a field select the field's declaration and invoke Source > Generate Delegate Methods. This adds the selected methods to the type that contains a forward call to delegated methods. This is an example of a delegate method:
public void addModifyListener(ModifyListener listener) {
    fTextControl.addModifyListener(listener);
}
Use Drag & Drop to create a method To create a method that has the same signature as an existing method, you can use Drag & Drop or Copy / Paste. For Drag & Drop (Windows), hold Ctrl+Shift while dropping to create a 'link'.
Use Drag & Drop for refactoring You can move Java compilation units between packages by Drag & Drop - all missing imports will be added and references updated.
Use Drag & Drop to move and copy Java code elements You can move and copy Java elements such as methods and fields by Drag & Drop. This will not trigger refactoring - only the code will be copied or moved.
You can easily put code of Java elements in the system clipboard When you select a set of methods, fields and types and press Ctrl + C (or invoke the Edit > Copy action), the source code of the selected elements is put in the system clipboard. You can then paste it (Ctrl + V or Edit > Paste) in another location within the workbench or even in other applications (such as your email program).
Use Templates to create a method You can define a new template (Preferences > Java > Editor > Templates) that contains a method stub. Templates are shown together with the Content Assist (Ctrl+Space) proposals.
There are also existing templates, such as 'private_method', 'public_method', 'protected_method' and more.
Use the Tab key to navigate between the values to enter (return type, name and arguments).

Content assist with new method template proposals

Use Quick Fix to create a new method Start with the method invocation and use Quick Fix (Ctrl+1) to create the method.

'Create method' quick fix

Use Content Assist to override a method Invoke Content Assist (Ctrl+Space) in the type body at the location where the method should be added. Content assist will offer all methods that can be overridden. A method body for the chosen method will be created.

'Override method' content assist

Use Quick Fix to add unimplemented methods To implement a new interface, add the 'implements' declaration first to the type. Without the need to save or build, the Java editor will underline the type to signal that methods are missing and will show the Quick Fix light bulb. Click on the light bulb or press Ctrl+1 (Edit > Quick Fix) to choose between adding the unimplemented methods or making your class abstract.

Quick Fix offering 'Add unimplemented methods' proposal

Add methods that override To create a method that overrides a method from a base class:
Select the type to add the methods to and invoke Source > Override / Implement Methods. This opens a dialog that lets you choose which methods to override.

'Override / Implement method' dialog

Local rename To quickly do a rename that doesn't require full analysis of dependencies in other files, use the 'local rename' Quick Assist. In the Java Editor, position the cursor in an identifier of a variable, method or type and press Ctrl+1 (Edit > Quick Fix)
The editor is switched to the linked edit mode (like templates) and changing the identifier simultaneously changes all other references to that variable, method or type.

Changing multiple identifiers using 'Local Rename' quick fix

Use Quick Fix to handle exceptions Dealing with thrown exceptions is made easy. Unhandled exceptions are detected while typing and marked with a red line in the editor.
  • Click on the light bulb or press Ctrl+1 to surround the call with a try catch block. If you want to include more statements in the try block, select the statements and use Source > Surround With try/catch Block. You can also select individual statements easily by using Edit > Expand Selection to and selecting Enclosing, Next or Previous.
  • If the call is already surrounded with a try block, Quick Fix will suggest adding the catch block to the existing block.
  • If you don't want to handle the exception, let Quick Fix add a new thrown exception to the enclosing method declaration

'Uncaught exception' quick fix proposals

At any time you can convert a catch block to a thrown exception. Use Ctrl+1 (Edit > Quick Fix) on a catch block.

'Replace catch clause with throws' quick assist

Less typing for assignments Instead of typing an assignment, start with the expression that will be assigned.

'Assign statement to local variable' quick assist

Now use Ctrl+1 (Edit > Quick Fix) and choose 'Assign statement to new local variable' and Quick Assist will guess a variable name for you.
Iterator iterator= vector.iterator();
Surround lines To surround statements with an if / while / for statement or a block, select the lines to surround and press Ctrl+1 (Edit > Quick Fix). This lists all templates that contain the variable ${line_selection}.

'Surround with templates' quick assist

Templates can be configured on Window > Preferences > Java > Editor > Templates. Edit the corresponding templates or define your own templates to customize the resulting code.
Create your own templates

You can create your own templates. Go to the Java > Editor > Templates preference page and press the New button to create a template. For example, a template to iterate backwards in an array would look like this:

for (int ${index} = ${array}.length - 1; ${index} >= 0; ${index}--){
   ${cursor}
}
Code assist can insert argument names automatically

You can have code assist insert argument names automatically on method completion. This behavior can be customized on the Java > Editor > Code Assist preference page (see the Fill argument names on method completion checkbox.) For example, when you select the second entry here:

code assist window

code assist will automatically insert argument names:

code assist inserted argument names

You can then use the Tab key to navigate between the insterted names.

Code assist can also guess filled argument names - basing on their declared types. This can be configured by the Guess filled argument names checkbox on the Java > Editor > Code Assist preference page.

Remove surrounding statement To remove a surrounding statement or block, position the cursor at the opening bracket and press Ctrl+1 (Edit > Quick Fix).

'Remove surrounding statement' quick assist

Structured selections You can quickly select Java code syntactically using the Structured Selection feature.
Highlight the text and press Ctrl+Shift+Arrow Up or select Edit > Expands Selection To > Enclosing Element from the menu bar - the selection will be expanded to the smallest Java-syntax element that contains the selection. You can then further expand the selection by invoking the action again.
Find the matching bracket To find a matching bracket select an opening or closing bracket and press Ctrl+Shift+P (Navigate > Go To > Matching Bracket). You can also double click before an opening or after a closing bracket: This selects the text between the two brackets.

Using 'double click' to select text between two brackets

Smart Javadoc Enter '/**' and press Enter. This automatically adds a Javadoc comment stub containing the standard @param, @return and @exception tags.

Result of 'Smart Javadoc'

The templates of the added comment can be configured in Window > Preferences > Java > Code Generation > Code and Comment > Comments
More speed in the Java editor You can speed up typing by:
  • Turning off problem indicators that appear while typing. Clear all check boxes in Window > Preferences > Java > Editor > Annotations.
  • Hiding the overview ruler. Clear the check box, Window > Preferences > Java > Editor > Appearance > Show overview ruler.
  • Turning off outline synchronization in the editor. Clear the check box, Window > Preferences > Java > Editor > Appearance > Synchronize outline selection on cursor move.
Use the local history to revert back to a previous edition of a method Whenever you edit a file, its previous contents are kept in the local history. Java tooling makes the local history available for Java elements, so you can revert back to a previous edition of a single method instead of the full file.

Select an element and use Replace With > Local History to revert back to a previous edition of the element.

Replace form local history dialog

Use the local history to restore removed methods Whenever you edit a file, its previous contents are kept in the local history. Java tooling makes the local history available for Java elements, so you can restore deleted methods selectively.

Select a container and use Restore from Local History to restore any removed members.

Restore from local history dialog

Customizable code generation The Java > Code Generation preference page allows you to customize generated code and comments in a similar way to normal templates. These code templates are used whenever code is generated. (These new templates are replacing the 'filecomment' and 'typecomment' templates previously used for code generation.)

Code templates preference page

The check box 'Automatically add comments...' lets you decide if features that create new methods or types add comments automatically or if they are only added explicitly with 'Add Javadoc Comment'.
Sort members You can Sort Members of a Java compilation unit according to a category order defined in the Java > Appearance > Member Sort Order preference page.
You'll find the action under Source > Sort Members
Wrap Strings

You can have String literals wrapped when you edit them. For example, if you have code like this:

String message= "This is some long message.";

position your caret after the "some" word and press Enter. The code will be automatically changed to:

String message= "This is some" + 
           " long message.";

This behavior can be customized in the Java > Editor > Typing preference page.

Searching

Locate variables and their read/write access You can locate variables and easily see their read/write status by selecting an identifier (variable, method or type reference or declaration) and invoking Search > Occurrences in File. This marks all references of this identifier in the same file. The results are also shown in the search view, along with icons showing the variable's read or write access.
You can search over several files by using the general search features (Search > References).

Read and write accesses to a field

Search for methods with a specific return type

To search for methods with a specific return type, use "* <return type>" as follows:

  1. Open the search dialog and click on the Java Search tab.
  2. Type '*' and the return type, separated by a space, in the Search string.
  3. Select the Case sensitive checkbox.
  4. Select Method and Declarations and then click Search.

Search for method with given return type

Find unused code The Java compiler detects unreachable code, unused variables, parameters, imports and unused private types, methods and fields
The setting is on the Java > Compiler preference page.

Compiler preference page

These settings are also detected as you type and a quick fix is offered to remove the unneeded code.

Code navigation and reading

Open on a selection in the Java editor There are two ways that you can open an element from its reference in the Java editor.
  • Select the reference in the code and press F3 (Navigate > Open Declaration)
  • Hold Ctrl and move the mouse pointer over the reference
Hyperlink style navigation The hyperlink style navigation can be configured in Preferences > Java > Editor > Navigation.
In-place outlines Press Ctrl+F3 in the Java editor to pop up an in-place outline of the element at the current cursor position. Or press Ctrl+O (Navigate > Show Outline) to pop up an in-place outline of the current source file.

Inplace outline

Go to next / previous method To quickly navigate to the next or previous method or field use
Ctrl+Shift+Arrow Up (Navigate > Go To > Previous Member) or Ctrl+Shift+Arrow Down (Navigate > Go To > Next Member)
Reminders in your Java code When you tag a comment in Java source code with "TODO" the Java compiler automatically creates a corresponding task as a reminder. Opening the task navigates you back to the "TODO" in the code. Use the Java > Task Tags preference page to configure any other special tags (like "FIXME") that you'd like to track in the task list.

Task tags in editor and task view

Select variables on endings in Open and Go To dialogs Open and Go To dialogs now support the end character '<'. To see all types in the Open Type dialog that end with "Test" enter the pattern "*Test<".
If '<' is not included in the pattern, a '*' will be appended to the pattern. If you enter "*Test" in the Open Type dialog you will see all types containing "Test" somewhere in the type name.
Make hovers sticky You can open the text from a hover in a scrollable window by pressing F2 (Edit > Show Tooltip Description). You can select and copy content from this window.

Window containing content of the hover

Hovers in the Java editor Did you know that using the modifier keys (Shift, Ctrl, Alt) you can see different hovers in the Java editor?
When you move the mouse over an identifier in the Java editor, by default a hover with the Javadoc extracted from the corresponding source of this element is shown. Holding down the Ctrl key shows you the source code.

Hover showing code of the element in the hover

You can change this behavior and define the hovers for other modifier keys in Preferences > Java > Editor > Hovers.
Open and configure external Javadoc documentation If you want to open the Javadoc documentation for a type, method or field with Shift+F2 (Navigate > Open External Javadoc), you have to first specify the documentation locations to the elements parent library (JAR, class folder) or project (source folder).
For libraries open the build path page (Project > Properties > Java Build Path), go to the Libraries, expand the node of the library where you can edit the 'Javadoc location' node. The documentation can be local on your file system or on a web server.

Configuring Javadoc location in the Java build path dialog

For types, methods or fields in source folders, go to the (Project > Properties > Javadoc Location).

Java views

Type hierarchy view supports grouping by defining type The type hierarchy method view lets you sort the selected type's methods by its defining types. For example, for AbstractList you can see that it contains methods that were defined in Object, Collection and List:

Sort members by the defining type in the type hierarchy

Tricks in the type hierarchy
  • Focus the type hierarchy on a new type by pressing F4 (Navigate > Open Type Hierarchy) on an element or a selected name
  • You can open the Hierarchy view not only on types but also on packages, source folders, JAR archives and Java projects.
  • You can Drag & Drop an element onto the Hierarchy view to focus it on that element.
  • You can change the orientation (from the default vertical to horizontal) of the Hierarchy view from the view's toolbar menu.
Find out where a method is implemented in the hierarchy To get an understanding of which types in a hierarchy override a method use the 'Show Members in Hierarchy' feature.
  • Select the method to look at and press F4 (Navigate > Open Type Hierarchy). This opens the type hierarchy view on the method's declaring type.
  • With the method selected in the Hierarchy view, press the 'Lock View and Show Members in Hierarchy' tool bar button
  • The hierarchy view now shows only types that implement or define the 'locked' method. You can for example see that 'isEmpty()' is defined in 'List' and implemented in 'ArrayList' and 'Vector' but not in 'AbstractList'

Lock view and show members in Hierarchy

Hierarchical vs. flat layout of packages An option on the Java Packages view (and Package Explorer view) allows you to change the way packages are displayed. Hierarchical displays packages in a tree, with sub-packages below packages; Flat displays them in the standard arrangement, as a flat list with all packages and sub-packages as siblings.
Flat packages layout Hierarchical package layout
Logical packages The Java Packages view (Java Browsing perspective) coalesces packages of the same name across source folders within a project. This shows the Packages view containing a logical package.

Java browsing perspective containing a logical package

Compress package names If your package names are very long you can configure that viewers show a compressed name. Configuration of the compression pattern is done in Preferences > Java > Appearance

Compression pattern configuration in the Java appearance preference page

Using this example, packages are rendered the following way:

Compressed package names

Various

JUnit Select a JUnit test method in a view and choose Run > Run As > JUnit Test. This creates a launch configuration to run the selected test.
Hide JUnit view until errors or failures occur You can make the JUnit view open only when there are errors or failures. That way, you can have the view set as a fast view and never look at it when there are no failing tests. While there are no problems in your tests you will see this icon Successfully running (the number of the little green squares will grow, indicating progress) while running them and this icon Successfully finished after they are finished. If, however, errors or failures occur, the icon will change to Failure or error occurred (or Finished with failure or error if tests are finished) and the JUnit view will appear. This behavior can be configured via the Java > JUnit preference page.
Structural compare of Java source A structural comparison of Java source ignores the textual order of Java elements like methods and fields and better shows which elements were changed, added, or removed.
For initiating a structural comparison of Java files you have two options:
  • Select two Java compilation units and choose Compare With > Each Other from the view's context menu. If the files have differences, they are opened into a Compare Editor. The top pane shows the differing Java elements; double clicking on one of them shows the source of the element in the bottom pane.
  • In any context where a file comparison is involved (e.g. a CVS Synchronization) a double click on a Java file not only shows the content of the file in a text compare viewer, but it also performs a structural compare and opens a new pane showing the results.

Structural compare of Java source

You can even ignore comments and formatting changes when performing the structural compare: turn on the Ignore Whitespace option via the Compare Editor's toolbar button, or the CVS Synchronization View's drop down menu.
Structural compare of property files A structural comparison of Java property files (extension: .properties) ignores the textual order of properties and better shows which properties were changed, added, or removed.
For initiating a structural comparison of property files you have two options:
  • Select two files in the Package Explorer or Navigator and choose Compare With > Each Other from the view's context menu. If the files have differences, they are opened into a Compare Editor. The top pane shows the affected properties; double clicking on one of them shows the source of the property in the bottom pane.
  • In any context where a file comparison is involved (e.g. a CVS Synchronization) a double click on a property file not only shows the content of the file in a text compare viewer, but it also performs a structural compare and opens a new pane showing the results.

Structural compare of property files

Define prefixes or suffixes for fields, parameters and local variables In addition to configuring the prefix or suffix for fields, you can also specify the prefix or suffix for static fields, parameters, and local variables. These settings on the Java > Code Generation preference page are used in content assist, quick fix, and refactoring whenever a variable name needs to be computed.

Name conventions in the code generation preference page

Organize Imports works not only on single files You can invoke Organize Imports on sets of compilation units, packages, source folders or Java projects.
Use project specific compiler settings Each project can decide to use the global compiler settings or to define project specific settings. Select the project and open the Java compiler page in the project properties (Project > Properties > Java Compiler)

Project specific Java compiler settings

You can also configure project specific settings for the Java Task tags (TODO tasks)
Use a specific JRE for a project When created, by default projects get the JRE added that is select in Preferences > Java > Installed JRE's. To set a project specific JRE open the project's Java Build path property page (Project > Properties > Java Build Path), open the Libraries page, select 'JRE System Library' and press Edit. In the 'Edit Library' dialog you can select to take the default JRE or a project specific JRE.

Edit JRE system library

Debugging

Stop in Main

You can use Stop in main in a Java Application launch configuration to cause your program to stop at the first executable line of the main method when you run it under debug mode.

Main tab with Stop in Main option selected

Conditional breakpoints You can use conditional breakpoints in Breakpoint Properties... to control when a breakpoint actually halts execution. You can specify whether you want the breakpoint to suspend execution only when the condition is true, or when the condition value changes.

Breakpoint properties dialog

Disabling breakpoints If you find yourself frequently adding and removing a breakpoint in the same place, consider disabling the breakpoint when you don't need it (using Disable Breakpoint in the breakpoint context menu or the Breakpoints view) and enabling it when needed again.

Disable Breakpoint action in the ruler context menu

Changing variable values

When a thread is suspended in the debugger, you can change the values of Java primitives and Strings in the Variables view. From the variable's context menu, choose Change Variable Value.

Change variable value dialog

Variable values in hover help When a thread is suspended and the cursor is placed over a variable in the Java editor, the value of that variable is displayed as hover help.

Variable value hover in the editor

Drop to Frame When stepping through your code, you might occasionally step too far, or step over a line you meant to step into. Rather than restarting your debug session, you can use the Drop to Frame action to quickly go back to the beginning of a method. Select the stack frame corresponding to the Java method you wish to restart, and select Drop to Frame from its context menu. The current instruction pointer will be reset to the first executable statement in the method. Note that this works for non-top stack frames as well. Drop to frame is only available when debugging with a 1.4 or higher VM, or the J9 VM.
Hot code replace The debugger supports Hot Code Replace when debugging with a 1.4 or higher VM, or the J9 VM. This lets you make changes to code you are currently debugging. Note that some changes such as new or deleted methods, class variables or inner classes cannot be hot loaded.
Stepping into selections

The Java debugger allows you to step into a single method within a series of chained or nested method calls. Simply highlight the method you wish to step into and select Step into Selection from the Java editor context menu.

Stepping into selection

Controlling
your console
Output displayed in the console can be locked to a specific process via a drop-down menu in the Console view toolbar. There's also a new scroll lock button that stops the console from automatically scrolling as new output is appended.

Console view with process drop-down

Creating watch items A watch item is an expression in the Expressions view whose value is updated as you debug. You can create watch items from the Java editor by selecting an expression or variable and choosing Watch from its context menu or the top-level Run menu).
Watch points

A watch point is a breakpoint that suspends execution whenever a specified variable is accessed or modified. To set a watchpoint, select a variable in the Outline view and choose Add/Remove Watchpoint from its context menu. To configure a watchpoint, select the watchpoint in the Breakpoints view and choose Properties... from its context menu. The most important properties for this type of breakpoint are the Access and Modification checkboxes which control when the breakpoint can suspend execution.

Breakpoint properties dialog

Threads and Monitors view

The debugger's Threads and Monitors view shows which threads are holding locks and which are waiting to acquire locks.

Monitors view showing deadlock cycles

Step filters Step filters prevent the debugger from suspending in specified classes and packages when stepping into code. Step filters are established in Window > Preferences > Java > Debug > Step Filtering. Step filters are in effect when the Step with Filters action (on the debug toolbar and menu) is invoked. In the Debug view, the selected stack frame's package or declaring type can be quickly added to the list of filters by selecting Filter Type or Filter Package from the stack frame's context menu.
Using the scrapbook

If you want to experiment with API or test out a new algorithm, it's frequently easier to use a Java scrapbook page than create a new class. A scrapbook page is a container for random snippets of code that you can execute at any time without a context. To create a scrapbook page in the Java Perspective, select File > New > Scrapbook Page from the workbench menu, or click the New Scrapbook Page button New scrapbook toolbar buttonon the workbench toolbar. Enter whatever code you wish to execute, then select it. There are three ways to execute your code:

  • Execute the selected code and place the returned result in the Expressions view
  • Execute the selected code and place the String result right in the scrapbook page

    Scrapbook page displaying result

  • Execute the selected code (and ignore any returned result)

These actions are in the workbench toolbar and also in the scrapbook page's context menu.

Editing
launch
configurations
Holding down the Ctrl key and making a selection from the Run or Debug drop-down menu opens the associated launch configuration for editing. The launch configuration can also be opened from the context menu associated with any item in the Debug view.
Favorite launch configurations

Launch configurations appear in the Run/Debug drop-down menus in most recently launched order. However it is possible to force a launch configuration to always appear at the top of the drop-downs by making the configuration a 'favorite'. In the Debug > Launch History preference page, you can establish favorites by launch type (Run, Debug, External Tools).

Launch history preference page

Now, the Debug drop-down menu shows the specified configurations as favorites, with the rest of the configurations in history order.

Debug drop-down menu on workbench toolbar

Detail formatters

In the Variables & Expressions views, the detail pane shows an expanded representation of the currently selected variable. By default, this expanded representation is the result of calling toString() on the selected object, but you can create a custom detail formatter that will be used instead by choosing New Detail Formatter from the variable's context menu. This detail formatter will be used for all objects of the same type. You can view and edit all detail formatters in the Java > Debug > Detail Formatters preference page.

Detail formatter dialog

Running code with compile errors

You can run and debug code that did not compile cleanly. The only difference between running code with and without compile errors is that if a line of code with a compile error is executed, one of two things will happen:

  • If the 'Suspend execution on compilation errors' preference on the Java > Debug preference page is set and you are debugging, the debug session will suspend as if a breakpoint had been hit. Note that if your VM supports Hot Code Replace, you could then fix the compilation error and resume debugging
  • Otherwise, execution will terminate with a 'unresolved compilation' error

It is important to emphasize that as long as your execution path avoids lines of code with compile errors, you can run and debug just as you normally do.

Word wrap in Variables view The details area of the debugger's Variables and Expressions views supports word wrap, available from the view drop-down menu.

Word wrap action in Variables view drop-down menu

Code assist in the debugger

Code assist is available in many contexts beyond writing code in the Java editor:

  • When entering a condition for a breakpoint
  • In the Details pane of the Variables & Expressions view
  • When entering a Details Formatter code snippet
  • When entering code in a Scrapbook page
  • In the Display view

Display view code assist pop-up

Command line details You can always see the exact command line used to launch a program in run or debug mode by selecting Properties from the context menu of a process or debug target, even if the launch has terminated.

Command line details

Stack trace
hyperlinks

Java stack traces in the console appear with hyperlinks. When you place the mouse over a line in a stack trace, the pointer changes to the hand and the stack trace is underlined. Pressing the mouse button opens the associated Java source file and positions the cursor at the corresponding line.

Stack traces in Console view with hyperlinks

Copyright (c) 2000, 2003 IBM Corporation and others. All Rights Reserved.