ToolActToolAct

Java Formatter

Input Java
Output
Lines: 1Characters: 0Bytes: 0
Lines: 1Characters: 0

What is Java Formatting?

The Java Formatter reorganizes Java code with consistent indentation, line breaks, and structure so classes, methods, blocks, generics, annotations, and control flow are easier to read. It helps with pasted snippets, generated code, review preparation, learning examples, and files that look inconsistent because of different editor settings. Formatting improves readability and teamwork, but it does not automatically fix program logic, compile errors, missing imports, API misuse, or project-specific style rules. In production repositories, the output should be compared with the team’s formatter, build tool, or CI convention so a formatting pass does not create unnecessary diff noise.

How to Use

How to use

  1. Paste or type Java code in the left input box
  2. Select indent size (2 spaces, 4 spaces, or Tab)
  3. Click 'Format' to beautify code, or 'Minify' to compress
  4. View results on the right (with syntax highlighting)
  5. Click 'Copy' to copy to clipboard

Options Description

Indent SizeChoose between 2 spaces, 4 spaces, or Tab indentation
FormatBeautify code with proper indentation and line breaks
MinifyRemove whitespace and comments to reduce file size

Code Tips

  • Formatting improves readability but does not compile or type-check Java code, so run your normal build or IDE checks after editing.
  • Minifying Java source is rarely useful for production builds; keep readable formatting for reviews, stack traces, and future maintenance.

Use Cases

Cleaning up pasted Java before code reviewWhen a method body has been copied from chat, documentation, or a ticket comment with inconsistent spacing, this formatter quickly restores readable indentation and line breaks around braces and statements. It is especially useful for small snippets where you want a code-reviewable shape without opening a full IDE project.
Preparing compact examples for docs or bug reportsThe minify mode strips comments and extra whitespace so a Java example can fit into an issue field, log annotation, or reproduction note without scrolling. Because parsing and minification happen entirely in the browser, internal package names, half-finished DTOs, or proprietary code from a private branch can be reshaped without ever leaving the page, which matters when sharing a reproducer that still contains customer identifiers.
Spotting obvious structure mistakes in short snippetsThe built-in validation checks bracket balance while respecting strings, character literals, and comments, so it can catch a missing brace or parenthesis before you paste the snippet elsewhere. It is not a compiler, but it is a fast sanity pass for interview exercises, documentation samples, and isolated utility methods.
Align generated code with project indentationSwitch between 2-space, 4-space, and tab indentation so generated getters, Lombok output, or IDE exports match the surrounding file. Skip running this on a whole module before checking the team's Google Java Style, Checkstyle, or Spotless config, otherwise the formatter pass will create a noisy diff.
Format enum and annotation-heavy snippets safelyPast enums with constants, methods, and annotation arrays often collapse into unreadable walls of text in chat. Reformat them so each constant and its arguments sit on their own line, then verify imports and the public modifier are still present after the rewrite. Google Java Style mandates 4-space indentation with a 100-column line width, while Eclipse's default profile uses 2-space tabs and IntelliJ's bundled style often extends to 120 columns; running this formatter without first checking the team profile will produce diffs even when the code is otherwise valid. Import order rules (static imports first, then java.*, then javax.*, then external, then local) are also style-specific, and generic angle-bracket spacing in Map<String, List<Integer>> versus the older Map <String, List<Integer>> form is normalized to no-space by Google Style.

Technical Principle

Java formatting is built on lexical analysis and AST construction. The lexer scans the source character by character and produces tokens: keywords (class, public, static, and the other reserved words), identifiers (variable and class names), literals (numbers, strings, characters), operators (+, -, ==, &&, ...), separators ({ } ( ) ; ,), and comments (//, /* */). The parser turns the token stream into an abstract syntax tree (AST) following the Java Language Specification, recognizing class definitions, method bodies, statement blocks, control flow structures, annotations, and other syntactic units. The formatter walks the AST and regenerates the code following a style guide such as Google Java Style: indentation increases with block depth, line width is capped at 100 columns, operators get spaces on both sides, commas are followed by a space, and opening braces stay on the same line (K&R style). Annotation handling is a special case in Java formatting: a single annotation stays on the same line as the method; longer annotation lists are broken across lines aligned on the parameters, with each annotation on its own line.

  • Lexical analysis: recognize the 50 Java keywords, identifiers, literals, operators, and comments, and output a token stream.
  • AST construction: build the AST per JLS rules, correctly handling classes, methods, control flow, lambdas, and try-with-resources.
  • Indentation rules: Google style uses 4 spaces per level by default, with a 100-column line width; lines over the limit are wrapped automatically.
  • Line break strategy: long method chains, parameter lists, and annotations wrap on commas or dots, with continuation lines aligned to the first character of the previous line.
  • Annotation handling: a single annotation stays on the same line; multiple annotations can be on one line or one-per-line, decided by length and parameter alignment rules.
  • Comment preservation: keep // and /* */ comments in their original positions; removal is an option during minification.

Examples

Formatting a Class Definition

Input:  public class User{private Long id;private String name;public User(Long id,String name){this.id=id;this.name=name;}}
Output:
public class User {
  private Long id;
  private String name;

  public User(Long id, String name) {
    this.id = id;
    this.name = name;
  }
}

Formatting a Method Chain

Input:  List<String> result=list.stream().filter(s->s.startsWith("a")).map(String::toUpperCase).sorted().collect(Collectors.toList());
Output:
List<String> result = list.stream()
    .filter(s -> s.startsWith("a"))
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());

Wrapping Annotations

Input:  @Override public ResponseEntity<User> getUser(@PathVariable Long id,@RequestParam(defaultValue="10") int size){...}
Output:
@Override
public ResponseEntity<User> getUser(
    @PathVariable Long id,
    @RequestParam(defaultValue = "10") int size) {
  ...
}

FAQ

Which Java style does it use?

Common defaults are Google Java Style or Sun/Oracle conventions: 4-space indent, K&R brace style, 100-column line width. Some builds expose options to switch styles. The exact rules of any style guide are subtle - run the formatter, read the output, and lock in a config.

Does the formatter understand modern Java?

It depends on the parser version. Records, sealed classes, switch expressions, text blocks, and pattern matching are recent additions; older parsers may not handle them. Try a snippet - if it formats cleanly, you're fine; if it throws, check the parser version.

Will it fix imports or unused variables?

No. Formatting only changes whitespace and brace placement. Static analysis (organize imports, remove unused) needs a real IDE or tool like google-java-format with --skip-removing-unused-imports off.

Is my source uploaded?

No. Formatting runs in your browser via a JS-based Java parser. Code is not transmitted. Avoid pasting proprietary code if your security policy prohibits any web tool exposure.

Will it match what IntelliJ or Eclipse produces?

Likely not exactly. Each IDE has its own formatter with thousands of options. Use this for ad-hoc formatting; for team consistency, use a CI-enforced tool like google-java-format or Spotless wired into your build.

Can it minify Java?

Java is a compiled language - minification doesn't apply the way it does to JS. Class file optimization is what compilers and ProGuard do at build time. This page is for source-level formatting only.

Why does my code have extra blank lines added?

Many style guides require a blank line between class members or between methods. The formatter inserts them to comply. If you prefer compact code, override the relevant style options.