Java Code Formatting

Info: For IntelliJ and Eclipse formatting files, see Code Formatting.

Code Formatting Guidelines

  • Use four spaces for indentation. Do not use tabs.
  • Save all files using UTF-8 encoding.
  • A blank line between the class declaration and the first variable declaration can improve readability, but this is optional.

Import Statements

In Eclipse, configure the following import order (this will apply globally in your IDE):

  • Package import order:
    • java
    • javax
    • org
    • com
  • No specific order is defined for static imports; place them after the above groups.
  • Set the threshold for wildcard imports (.*) to 99 for both regular and static imports.
  • Enable the option to avoid creating imports for types that start with a lowercase letter.

Indentation and Line Length

  • Maximum line length: 120 characters.
  • If a line exceeds 120 characters, wrap it according to these rules:
    • Break after a comma.
    • Break before an operator.
    • Prefer breaking at higher-level expressions rather than nested ones.
    • Indent wrapped lines by 8 spaces.
    • For method signatures, place each argument on a new line and indent by 8 spaces.

Examples:

// Prefer breaking at higher-level expressions longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // For method signatures, align each argument on a new line, indented by 8 spaces someMethod( int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) { ... } // Indent 8 spaces for wrapped conditions to improve readability if ((condition1 && condition2) || (condition3 && condition4) ||!(condition5 && condition6)) { doSomethingAboutIt(); }

Commenting Standards

  • Use Javadoc notation for header comments and comments above methods.
  • Example header comment:
/** * Brief description of what the code does or its purpose. */
  • For comments inside methods, use line comments (//). Place comments on their own line above the code they describe.
  • Avoid block comments (/* ... */) except when temporarily disabling code. Do not use trailing comments at the end of a line.
  • Do not commit commented-out code; use Git for code history.

Examples:

public void someMethod() { ... // This is a line comment // for multiple lines messageService.send(message); /* notifyAdministrator(); logger.info("Sent message to administrator"); */ count++; // DO NOT USE this comment style }

Field and Variable Declarations

  • Declare only one field per line. Do not align field names.
  • Avoid declaring multiple fields in a single line.
  • Do not align variable names for visual effect.
public class Declarations { // Correct int number; String text; // Incorrect: multiple declarations in one line int first, second, last; // Incorrect: aligning field names Date expiryDate; List<String> driverNames;
  • Avoid variable shadowing (ghosting), where a local variable has the same name as a higher-level variable.
int count; ... myMethod() { if (condition) { int count = 0; ... } ... }

Whitespace Usage

  • Use spaces and blank lines as needed for clarity.
  • Always add a space between a keyword and the opening parenthesis.
while (true) { ... } if (condition) { ... }
  • Do not add a space between a method name and its opening parenthesis.
  • Separate operands and casts with a space.
(a + b) / (2 - 4) someMethod((int) d);

Formatting Fluent APIs

When breaking fluent API calls across multiple lines, use a double indent (8 spaces) and place the dot at the start of the new line.

myFluentObject.performThisOperation() .performAnotherOperation() .performThisToo(someOtherFluentObject.setSomething("foo") .setBarToo(true));

Code Block Usage

  • Always use curly braces for code blocks, even for single statements.
  • Place the opening brace on the same line as the condition.
while (true) { ... } if (condition) { ... } else if (condition) { ... } else { ... } // DO NOT USE if (condition) if (condition) ... if (condition) ... else if (condition) ... else { ... }

Naming Conventions

Identifier TypeConventionsExamples
PackagesUse only lowercase letters. Do not use numbers or dashes.java.util org.onehippo.forge.myproject
ClassesUse nouns in mixed case. Capitalize the first letter of each internal word. Use whole words; avoid acronyms and abbreviations unless widely accepted (e.g., URL, HTML). For acronyms, capitalize only the first letter (e.g., HtmlParser).Account LogProcessor HtmlParser
InterfacesFollow the same conventions as classes. Do not prefix with "I" or suffix with "Interface".AccountService UserDao Plugin
MethodsUse verbs or active phrases in mixed case. Start with a lowercase letter. Capitalize the first letter of each internal word. Keep names expressive but not overly long.viewAccount() getUserById() calculateRevenue()
VariablesUse mixed case, starting with a lowercase letter. Capitalize internal words. Do not start with underscores or meaningless characters. Use short, meaningful names. Avoid single-character names except for temporary variables (e.g., 'i' in loops).firstName count revenueStrategy
ConstantsUse all uppercase letters with words separated by underscores (_).DEFAULT_LOGIN_URL IFN_CODE MINUTES_IN_DAY

Logging Practices

  • Use debug-level logging extensively and thoughtfully. Log key actions and decision points to support troubleshooting.
  • Use ERROR level only for unrecoverable errors or those requiring user action.
  • Use WARN level for all other warning conditions.
  • Expose stack traces only at debug level. At higher levels, log only informative messages to avoid cluttering logs with stack traces.
  • Logging at appropriate levels helps diagnose issues, especially in client environments where only logs may be available.
Share Feedback
Page: /about/platform-development/java-code-formatting
Section: About
Category *
Java Code Formatting | Bloomreach Content Documentation