Sunday, 3 August 2025

Code Formatting Control in Java: Using @formatter:off and @formatter:on

When working in Java, most developers use automatic code formatters in their IDEs like IntelliJ IDEA or Eclipse. These formatters help to keep code clean and consistent, but sometimes, they change things you didn’t want them to.

Have you ever written a nicely aligned comment, an ASCII diagram, or a table in Javadoc, only to see it get messed up by your formatter? That's where @formatter:off and @formatter:on come in.

 

These special comments let you turn off the auto-formatter temporarily, so you can keep your code or documentation exactly how you want it. Once you're done, you turn formatting back on. It’s like telling your IDE, “Hands off — I’ve got this part.”

 

In this post, we’ll learn what these formatter tags are, when and how to use them, and how they’re supported in popular tools like IntelliJ, Eclipse, and Spotless. If you’ve ever struggled with keeping your code layout, this guide is for you.

 

1. Introduction

Most developers use an automatic code formatter in their code editor or IDE (like IntelliJ IDEA or Eclipse). A code formatter is a tool that automatically cleans up your code’s layout, like adding proper indentation, fixing spacing, aligning braces, and so on.

 

This helps:

·      Make your code easier to read.

·      Keep everyone on a team writing code in a consistent style.

·      Save time by not having to format everything by hand.

 

But sometimes, the formatter can be too aggressive, meaning it changes parts of your code that you want to keep exactly as they are.

 

1.1 Common Problems That Happen

 

a. ASCII Diagrams or Visual Layouts

 

Example

public class FileProcessingPipeline {

    public void runPipeline() {

        // ┌────────────────┐
        // │  Input Source  │
        // └──────┬─────────┘
        //        │
        //        ▼
        // ┌────────────────┐
        // │   Preprocessor │
        // └──────┬─────────┘
        //        │
        //        ▼
        // ┌────────────────┐
        // │   Processor    │
        // └──────┬─────────┘
        //        │
        //        ▼
        // ┌────────────────┐
        // │   Formatter    │
        // └──────┬─────────┘
        //        │
        //        ▼
        // ┌────────────────┐
        // │ Output Writer  │
        // └────────────────┘

        // Steps would be called here in order
    }

   
}

After code formatting it change like below.

 


b. Tables in Javadoc

If you create a table in your Javadoc using text, the formatter might shift lines around and ruin the alignment:

/**
 * User Information Table:
 *
 * +------------+-----+-------------+----------------------+------------------+
 * | Name       | Age | Occupation  | Email                | Registered Date  |
 * +------------+-----+-------------+----------------------+------------------+
 * | Alice      | 28  | Engineer    | alice@example.com    | 2021-03-15       |
 * | Bob        | 35  | Designer    | bob.design@example.com | 2020-11-30     |
 * | Charlie    | 22  | Student     | charlie@univ.edu     | 2023-01-05       |
 * | Diana      | 41  | Manager     | diana@corp.com       | 2019-07-19       |
 * +------------+-----+-------------+----------------------+------------------+
 *
 * <p>
 * Columns:
 * <ul>
 * <li><b>Name</b> - Full name of the user</li>
 * <li><b>Age</b> - Current age</li>
 * <li><b>Occupation</b> - Current profession</li>
 * <li><b>Email</b> - Contact email address</li>
 * <li><b>Registered Date</b> - Date the user registered in the system</li>
 * </ul>
 */

After formatting it change like below.

 


c. Legacy Code

Sometimes you’re working with old code written in a very specific format. Changing it could cause bugs or confusion. A formatter might reformat it without understanding why it was written that way.

 

d. Aligned Comments

You might write comments like this

    int count    = 10;  // number of items
    int maxLimit = 100; // maximum allowed

A formatter might remove the spacing before the comments, making them harder to read in a block.


While formatters try to make your code clean and consistent, they don’t always understand the meaning or importance of certain formatting. This can be frustrating when you’ve spent time making something readable, only for the formatter to undo your work.

 

2. The Hidden Gems: @formatter:off and @formatter:on

@formatter:off and @formatter:on are special comments (not actual Java code or annotations) that tell your IDE or code formatter to stop and start formatting automatically.

 

They are not part of the Java language itself, they are just instructions to the code formatting tool, like saying:

 

“Hey formatter, don’t touch the next few lines.”

“Okay formatter, you can start again now.”

 

This is very helpful when you want to keep specific formatting exactly as you typed it, and prevent the formatter from changing it.

 

Even though they look like annotations (@something), they are not Java annotations. Instead, they are just inline comments that some IDEs recognize.

 

Example

 

// @formatter:off

 

Which tools support these instructions?

These formatter tags are recognized by:

·      Eclipse (out of the box)

·      IntelliJ IDEA (you need to enable it)

·      Spotless (depends on the formatter engine you use, Google Java Format ignores it, but Eclipse formatters might support it)

 

Here’s a simple code snippet showing how to use them:

// @formatter:off
int valueA    = 10;  // aligned comment
int valueLong = 20;  // aligned comment
int shortV    = 30;  // aligned comment
// @formatter:on

Without @formatter:off, your formatter might collapse everything like this:

int valueA = 10; // aligned comment
int valueLong = 20; // aligned comment
int shortV = 30; // aligned comment

 

3. Best Practices for Using @formatter:off and @formatter:on

Using @formatter:off and @formatter:on can be very helpful, but like any powerful tool, it's important to use it carefully and responsibly. Here are some best practices to follow.

 

3.1 Don’t Overuse It

Just because you can turn off the formatter doesn't mean you should do it everywhere. Auto-formatting helps keep your code:

 

·      Clean

·      Consistent

·      Easy to read, especially in large teams

 

If you turn off formatting too often, your code might start looking messy or inconsistent, which defeats the purpose of using a formatter in the first place.

 

3.2. Use It Only When You Really Need To

Use @formatter:off only around specific blocks where you absolutely need to preserve the exact layout, such as:

 

·      Javadoc tables

·      ASCII diagrams

·      Aligned comments

·      Legacy code where formatting affects logic or readability.

 

Example

// @formatter:off
/**
 * +----------+--------------+
 * | Name       | Role       |
 * +------------+------------+
 * | Ram        | Developer  |
 * | Krishna    | Designer   |
 */
// @formatter:on

 

3.3 Leave a Comment Explaining Why

If you turn off formatting for a section, it's a good habit to leave a short comment explaining why. This helps other developers (or future you!) understand the reason.

 

Example

// @formatter:off
// Table format must be preserved for documentation readability
/**
 * +----------+------------+
 * | Column A | Column B   |
 * +----------+------------+
 */
// @formatter:on

 

4. Final Thoughts

4.1 When Should You Use @formatter:off?

Use this feature only when auto-formatting makes your code harder to read, and you have a good reason to keep your own formatting.

 

Examples include:

·      Tables or diagrams in Javadoc

·      Aligned comments for better visual structure

·      Preserving formatting in legacy code or custom layouts

 

You shouldn't use it just because you don't like the formatter's style, formatters help teams write consistent code. But when readability truly depends on your layout, that’s the right time to reach for @formatter:off.

 

4.2 Your Code, Your Way - Without Fighting the Formatter

Instead of turning off formatting for your entire file or disabling your formatter altogether, @formatter:off and @formatter:on let you:

 

·      Keep control where it matters

·      Let the formatter work everywhere else

 

This means your code stays mostly clean and consistent, but also preserves your intent in areas that require special formatting.

 

In summary, think of @formatter:off as a temporary "pause" button for formatting, use it only when needed, and your code will be both clean and human-friendly.

 

  

You may like

Miscellaneous

Programmatically import certificate to cacerts file in Java

Command to check CPU temperature in Mac

Quick guide to Java DecimalFormat class

Compress and decompress a string in Java

Discover and load the implementations of a service using ServiceLoader in Java

No comments:

Post a Comment