Java Formatter (Eclipse)

Tuesday, 31 December 2013, 17:56

Tags: Eclipse

In Eclipse it is possible to configure how Java source code has to be formatted. When a Java file is open in Eclipse the code can be formatted by clicking right -> Source -> Format or by using the shortcut Ctrl + Shift + F.

An export of my formatter settings can be found here. My settings are based on the standard Eclipse settings with some small adaptions. The most important changes are listed below. (Window -> Preferences -> Java -> Code Style -> Formatter)

  • Line Wrapping
    • Maximum line width of 100
    • Never join already wrapped lines
  • Comments
    • Maximum line width of 100
    • Never join lines
  • Enable the Off/On tags

The last option is useful when you have a piece of code you don't want to format. By adding the annotation @formatter:off before the code and @formatter:on after the code, formatting will be disabled for the code between these annotations. The next code snippet shows an example of the annotations usage.