Software Development

How to Format Java Code from the Command Line

Properly formatted code is essential for enhancing readability, maintainability, and collaboration within development teams. While IDEs like Eclipse and IntelliJ IDEA offer built-in formatting tools, there are situations where formatting Java code directly from the command line proves to be more efficient, such as batch processing multiple files or standardizing code styles across projects.

This article delves into several tools and methods for formatting Java code from the command line.

1. Sample Unformatted Java Code

Here’s a sample of unformatted Java code that will be used for the examples:

public class Example{
public static void main(String[]args){System.out.println("Hello,world!");}}

This code lacks proper indentation, spacing, and structure. Each tool will be used to transform it into a clean, readable format.

2. Formatting Java Code Using Google Java Format

Google Java Format is a powerful tool designed to enforce a consistent style guide for Java code, ensuring readability and adherence to standards. It is simple, fast, and user-friendly, making it ideal for developers looking to streamline their code formatting process.

To get started, download the latest version of Google Java Format from the official releases page. Begin by saving your unformatted code in a file, such as Example.java. Next, download the required JAR file, and then run the formatter using a simple command to apply the formatting rules to your Java file.

java -jar ./google-java-format-1.25.2-all-deps.jar -r Example.java
  • ./google-java-format-1.25.2-all-deps.jar: The path to the JAR file. Here, the JAR file is in the current directory (./).
  • -r: Stands for “replace,” which reformats the provided file (Example.java) in-place, modifying the file directly.
  • Example.java: The Java file to be formatted.

This command reads Example.java, formats it according to the Google Java Style Guide, and saves the formatted result back into the same file. After running the command, the formatted file will look like this:

public class Example {
  public static void main(String[] args) {
    System.out.println("Hello,world!");
  }
}

3. Formatting Java Code Using Artistic Style (Astyle)

Artistic Style (Astyle) is a flexible and general-purpose code formatter that supports C, C++, and Java programming languages. Renowned for its lightweight design and simplicity, Astyle enables us to effortlessly maintain consistent and well-structured code formatting.

After downloading the tool, we can easily format our Java code by running a simple command in the terminal, which automatically applies the specified formatting rules.

astyle --squeeze-ws --style=java Example.java

Command Breakdown

  • astyle
    • Invokes the Artistic Style (Astyle) formatter tool.
  • --squeeze-ws
    • Squeeze/Reduce Whitespace: This option removes unnecessary blank lines from the code.
    • Multiple consecutive blank lines are reduced to a single blank line, helping to create a cleaner, more compact code structure.
  • --style=java
    • Apply Java Code Style: This option formats the code according to Java-style formatting rules.
    • In Java-style formatting:
      • Braces ({ and }) are placed on the same line as the control statement or method declaration.
      • Indentation is typically set to four spaces (default) unless overridden with another option.
  • Example.java
    • Specifies the file to be formatted.

Astyle will read the contents of Example.java, apply the specified formatting options, and save the changes in place by default.

4. Using idea.sh to Format Java Code from the Command Line

To format Java code using the idea.sh script, first locate the script, which is typically found in the bin directory of our IntelliJ IDEA installation. This script allows us to apply IntelliJ IDEA’s configured code style settings directly from the command line. Once located, we can format a single Java file by executing a simple command:

/path-to-intellij/bin/idea.sh format -allowDefaults Example.java

Command Breakdown

  • /path-to-intellij/bin/idea.sh: Invokes the idea.sh script, which is used to interact with IntelliJ IDEA from the command line.
  • format: Specifies the action to be performed. In this case, it tells the idea.sh script to format the provided file(s) using the code style settings configured in IntelliJ IDEA.
  • -allowDefaults (Optional Parameter): This option allows the formatter to use default code style settings for formatting when no custom settings are explicitly defined in the IntelliJ IDEA project or user settings.

5. Conclusion

In this article, we explored various tools and methods for formatting Java code directly from the command line, including Google Java Format, Artistic Style (Astyle) and IntelliJ IDEA‘s idea.sh script. Each tool offers unique features to ensure your code adheres to consistent styling guidelines, making it more readable and maintainable.

6. Download the Source Code

This article explored how to format Java code using command line tools.

Download
You can download the full source code of this example here: Format Java Code via Command Line

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button