Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 119 ยท Logging and Tooling

Code Quality and Static Analysis

Keep Java code clean and correct with formatters, Checkstyle, SpotBugs, PMD, Error Prone and SonarQube, plus build setup and code review habits that work.

Tests prove that the code does what you checked. They say nothing about the bugs you never thought to test. Static analysis fills part of that gap: tools read your source code (or compiled bytecode) without running it and flag patterns that are almost always wrong, such as comparing strings with ==, ignoring the result of trim(), or an empty catch block that hides failures. Formatters and style checkers take care of the rest of the noise, so humans can spend code review on design instead of brace placement.

In this lesson you will first run a set of bugs that compile without a single warning, then use the Java compiler itself as an analyzer, and finally build a tiny Error Proneโ€“style checker on the real javac syntax tree. After that you will meet the professional tool chain: formatters, Checkstyle, SpotBugs, PMD, Error Prone, SonarQube, and how to wire them into Maven or Gradle so the build fails before a bad change is merged. If your build tool is still new, read Maven in Depth or Gradle in Depth first.

Bugs that compile fine

The Java compiler only rejects code that breaks the language rules. Plenty of legal code is still wrong. Run this program and compare each line of output with what the author obviously meant.

Java Six bugs the compiler accepts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every line is a classic:

  1. == compares references. A string built at runtime is a different object from the literal, so the check is false even though the text matches. Use equals.
  2. Strings are immutable. trim() returns a new string, and the code throws it away.
  3. Arrays don't override toString(), so concatenation prints a type code and a hash. Use Arrays.toString(scores).
  4. Integer caches values from -128 to 127, so == happens to work for small numbers and silently breaks for larger ones.
  5. BigDecimal.equals treats 2.0 and 2.00 as different because their scale differs. Use compareTo for numeric equality.
  6. The set stored the tag under the hash of "java". After the field changes, the set looks in the wrong bucket and can't find its own element. Keys of hash-based collections must be immutable (records are a good fit, see Records).

Each of these is caught automatically by at least one tool in this lesson. That is the real argument for static analysis: it remembers every classic mistake so you don't have to.

The compiler is your first analyzer

Before adding any tools, turn on what you already have. javac has many optional warnings, grouped under lint categories: rawtypes, unchecked, deprecation, fallthrough, serial, try, this-escape and more. -Xlint:all enables them all, and -Werror turns warnings into errors so they can't pile up.

The javax.tools API lets a program run the compiler on a string of source code. The next example compiles a small class with all lint warnings enabled and prints each diagnostic, just like your IDE or build would.

Java javac with -Xlint:all

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler finds the missing break (the fallthrough category: label(1) returns "medium", not "low") and the raw List together with the unchecked add call on it. Then it compiles anyway, because these are warnings. Add "-Werror" to the options list and run again: compilation now fails, which is exactly what you want in a build.

In Maven, the same switches go into the compiler plugin:

XML
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <release>25</release>
    <compilerArgs>
      <arg>-Xlint:all</arg>
      <arg>-Werror</arg>
    </compilerArgs>
  </configuration>
</plugin>

In Gradle (Kotlin DSL) it is one block:

TEXT
tasks.withType<JavaCompile>().configureEach {
    options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror"))
}

When you switch on -Werror in an old project, you may get hundreds of errors at once. Enable the categories one by one (-Xlint:rawtypes,unchecked), fix them, and widen the list over time.

Formatting: stop arguing about style

The cheapest quality win is an automatic formatter. When the build formats every file the same way, diffs show only real changes and nobody comments on spacing again. The common choices:

  • google-java-format: Google's style, 2-space indentation, almost no options. Opinionated on purpose.
  • palantir-java-format: a fork with 4-space indentation and a 120-column line, popular for lambda-heavy code.
  • Your IDE's formatter, exported as a shared settings file. Works, but only if everyone uses the same IDE configuration.

Most teams run the formatter through Spotless, a Maven and Gradle plugin that can check or fix formatting for Java, Kotlin, SQL, Markdown and more:

XML
<plugin>
  <groupId>com.diffplug.spotless</groupId>
  <artifactId>spotless-maven-plugin</artifactId>
  <version>${spotless.version}</version> <!-- use the current release -->
  <configuration>
    <java>
      <palantirJavaFormat/>
      <removeUnusedImports/>
    </java>
  </configuration>
</plugin>
Terminal
mvn spotless:apply   # rewrite files in the standard format
mvn spotless:check   # fail the build if any file is not formatted (use this in CI)

Add an .editorconfig file at the project root too. IntelliJ IDEA, VS Code and Eclipse all read it, so basic settings match even before the formatter runs:

TEXT
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true

[*.java]
indent_style = space
indent_size = 4
max_line_length = 120

Checkstyle: conventions and structure

Checkstyle checks source code against a set of rules: naming conventions, Javadoc on public APIs, import order, line length, maximum method length, and some real bug patterns such as EmptyCatchBlock, MissingSwitchDefault, EqualsHashCode and FallThrough. It ships with two ready-made configurations, google_checks.xml and sun_checks.xml, and teams usually start from one of them and adjust.

A Checkstyle configuration is an XML tree of modules:

XML
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
  "https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
  <module name="LineLength">
    <property name="max" value="120"/>
  </module>
  <module name="TreeWalker">
    <module name="EmptyCatchBlock"/>
    <module name="EqualsHashCode"/>
    <module name="MissingSwitchDefault"/>
    <module name="MethodLength">
      <property name="max" value="60"/>
    </module>
    <module name="TypeName"/>
    <module name="AvoidStarImport"/>
  </module>
</module>

And the Maven plugin runs it during mvn verify:

XML
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-checkstyle-plugin</artifactId>
  <configuration>
    <configLocation>config/checkstyle.xml</configLocation>
    <violationSeverity>warning</violationSeverity>
    <failOnViolation>true</failOnViolation>
  </configuration>
  <executions>
    <execution>
      <goals><goal>check</goal></goals>
    </execution>
  </executions>
</plugin>

If you already use a formatter, turn off Checkstyle's whitespace and indentation rules. Two tools that disagree about formatting produce endless busywork.

How analyzers see your code

Checkstyle, PMD and Error Prone don't search your files with regular expressions. They parse the code into an abstract syntax tree (AST) and walk it, looking for node patterns. The JDK exposes javac's own tree through the com.sun.source API, so you can write a small checker yourself. This one has four rules: empty catch blocks, == against a string literal, a discarded result of a string method, and methods whose cyclomatic complexity (1 + the number of decision points) is too high.

Java A mini static analyzer on the javac syntax tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The checker reports the == on line 3, the ignored trim() on line 6, the empty catch on line 13 and a complexity of 9 for discount(). Two lessons hide in this small program:

  • Syntax alone is not enough. The "ignored result" rule only looks at method names. It would wrongly flag a trim() method on your own class that changes state. Real tools such as Error Prone and SpotBugs use full type information to know that the receiver is a java.lang.String.
  • Rules are cheap, judgment is not. A complexity limit of 5 is a heuristic. A clear switch over ten cases can be fine. Good teams tune thresholds and suppress findings with a written reason.

SpotBugs: bugs in the bytecode

SpotBugs (the successor of FindBugs) analyzes compiled .class files. Because it sees the code after compilation, with types resolved, it is good at finding real defects: possible null dereferences, ignored return values, equals without hashCode, wrong comparisons, unclosed streams, and thread-safety mistakes like inconsistent synchronization. Each finding has a code, for example ES_COMPARING_STRINGS_WITH_EQ (bug 1 above), RV_RETURN_VALUE_IGNORED (bug 2) or RC_REF_COMPARISON (bug 4).

XML
<plugin>
  <groupId>com.github.spotbugs</groupId>
  <artifactId>spotbugs-maven-plugin</artifactId>
  <version>${spotbugs-plugin.version}</version>
  <configuration>
    <effort>Max</effort>
    <threshold>Medium</threshold>
    <plugins>
      <!-- extra security rules: SQL injection, weak crypto, path traversal ... -->
      <plugin>
        <groupId>com.h3xstream.findsecbugs</groupId>
        <artifactId>findsecbugs-plugin</artifactId>
        <version>${findsecbugs.version}</version>
      </plugin>
    </plugins>
  </configuration>
</plugin>
Terminal
mvn compile spotbugs:check   # fail on findings
mvn spotbugs:gui             # browse findings in a desktop viewer

When a finding is a false positive, suppress it at the narrowest scope and write why. SpotBugs reads its own annotation from the spotbugs-annotations artifact:

Java
@SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Immutable list from List.copyOf")
public List<String> names() { return names; }

PMD: design smells and copy-paste

PMD works on the source AST, like the checker you just ran. Its rules focus on design and maintainability: unused private fields and methods, overly complex methods (CognitiveComplexity, CyclomaticComplexity), deeply nested if statements, empty catch blocks, and classes that do too much. It also includes CPD, the copy-paste detector, which finds duplicated blocks of code across the project.

Terminal
mvn pmd:check       # rule violations fail the build
mvn pmd:cpd-check   # duplicated code fails the build

PMD findings can be silenced with @SuppressWarnings("PMD.RuleName") on a declaration or a // NOPMD - reason comment on one line.

Error Prone: bug checks inside javac

Google's Error Prone plugs into the compiler itself, so its checks run on every build with full type information, and many of them are errors rather than warnings. Typical checks are ArrayToString (bug 3 above), DeadException (an exception created but never thrown), SelfAssignment, ReturnValueIgnored, MissingOverride and EqualsHashCode. Many checks also suggest an automatic fix.

It is enabled as a compiler plugin, roughly like this (the Error Prone documentation lists the exact flags and the extra JVM options needed on recent JDKs, which belong in .mvn/jvm.config):

XML
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <configuration>
    <compilerArgs>
      <arg>-XDcompilePolicy=simple</arg>
      <arg>-Xplugin:ErrorProne</arg>
    </compilerArgs>
    <annotationProcessorPaths>
      <path>
        <groupId>com.google.errorprone</groupId>
        <artifactId>error_prone_core</artifactId>
        <version>${errorprone.version}</version>
      </path>
    </annotationProcessorPaths>
  </configuration>
</plugin>

A popular companion is NullAway, an Error Prone plugin that makes NullPointerException a compile-time problem. You mark packages as non-null by default (for example with JSpecify's @NullMarked) and annotate only the values that may be missing with @Nullable.

SonarQube: the dashboard view

The tools so far run in the build and report per change. SonarQube (self-hosted) and SonarQube Cloud collect results over time: bugs, vulnerabilities, "code smells", duplication and test coverage (from JaCoCo), shown per project and per pull request. Its key idea is the quality gate: a pull request fails if new code has issues or too little coverage, so old projects can improve gradually without fixing everything at once.

Terminal
mvn verify sonar:sonar -Dsonar.host.url=https://sonar.example.com -Dsonar.token=$SONAR_TOKEN

In the IDE, the free SonarQube for IDE extension (formerly SonarLint) shows the same rules as you type.

Tool Analyzes Best at
Formatter (via Spotless) Source Consistent layout, zero debate
javac -Xlint Source, with types Raw types, fall-through, deprecation
Checkstyle Source AST Conventions, naming, Javadoc, size limits
PMD + CPD Source AST Design smells, complexity, duplicated code
SpotBugs (+ FindSecBugs) Bytecode Real defects, null handling, security bugs
Error Prone (+ NullAway) Inside javac Bug patterns at compile time, null safety
SonarQube All of the above + coverage Trends, quality gates on pull requests

You don't need all of them. A strong default for a new project is: a formatter, -Xlint:all -Werror, Error Prone or SpotBugs, and tests with coverage in CI.

Making quality automatic

Tools only help if they run every time. Put them where nobody can forget them:

  • In the build. Bind checks to mvn verify or Gradle's check task, so a local build and the CI build behave the same.
  • In CI on every pull request. A red build blocks the merge. Keep the checks fast; slow builds get bypassed.
  • Ratchet, don't boil the ocean. On a legacy codebase, fail only on new problems (SonarQube's "new code" gate, or a baseline file for SpotBugs or Checkstyle) and lower the baseline over time.
  • Suppress with a reason. Every suppression should say why, at the smallest scope possible. "Too many warnings" is not a reason, it is a backlog.

Code review habits

Automation catches patterns; reviewers catch meaning. Once the tools handle style and known bug patterns, a review can focus on what only humans see:

  • Correctness first. Does the change do what the ticket asks, including edge cases: empty input, null, very large values, concurrent calls, failures halfway through?
  • Tests that would fail. Is there a test that breaks if the new code is wrong? A test that passes no matter what is worse than none (see Unit Testing with JUnit 6).
  • Names and boundaries. Would a new team member understand the method from its name and parameters? Does the class still have one job?
  • Error handling and logging. No swallowed exceptions, useful messages, no secrets in logs (see Logging with SLF4J and Logback).
  • Small changes. Reviews of 200 lines find real problems; reviews of 2,000 lines get a quick "looks good". Ask for large changes to be split.
  • Be kind and specific. Comment on the code, not the person, and suggest a concrete alternative. Mark nitpicks as optional so the important comments stand out.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Integer a = 500, b = 500; What does a == b evaluate to, and why?

    == on two Integer objects compares references. Only values from -128 to 127 come from the shared cache, so two boxed 500s are different objects.
  2. 2. Which tool analyzes compiled bytecode rather than source code?

    SpotBugs reads .class files, so it sees resolved types and the code as the compiler produced it. Checkstyle and PMD parse source code, and a formatter only rewrites layout.
  3. 3. The mini analyzer flags code.trim(); by method name only. What is the weakness of this approach?

    Without type information the rule can't tell a String from any other class with a trim() method. Error Prone and SpotBugs use the resolved types to avoid this.
  4. 4. You enable -Xlint:all -Werror on a large old project and get 400 errors. What is the most practical approach?

    Ratcheting keeps the build green while preventing new problems. Huge clean-up changes are risky to review, and blanket suppression hides real bugs.
  5. 5. What is a SonarQube quality gate?

    The gate checks measures such as new bugs, vulnerabilities and coverage on new code, and fails the check when they are not met.

Summary

  • Static analysis finds bugs that compile fine: == on strings and boxed numbers, ignored return values, printed arrays, BigDecimal.equals, mutable hash keys, empty catch blocks.
  • Start with the compiler: -Xlint:all plus -Werror in Maven or Gradle.
  • Let a formatter (google-java-format or palantir-java-format via Spotless) own layout, and add an .editorconfig.
  • Checkstyle enforces conventions, PMD finds design smells and duplication, SpotBugs finds defects in bytecode, Error Prone (with NullAway) catches bug patterns inside javac, and SonarQube tracks it all with quality gates.
  • Analyzers walk the syntax tree; the best ones also use type information.
  • Run checks in the build and in CI, ratchet on old code, suppress only with a reason, and keep human review for correctness, tests, naming and design.

Next: How HTTP Works starts the web chapter with real requests and responses between a server and a client in one program.