Static analysis with SonarLint
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite compiles and its tests pass, yet a reviewer spots a file that is never closed and a password in the source. Could a tool have told you the moment you typed it?
What static analysis finds: bugs, smells, security hotspots
Static analysis is finding problems in code by reading it, without running it. A tool matches your code against hundreds of rules for known mistakes.
Example 1 shows a bug that compiles and passes small tests: == on two Integer objects.
Example 1 · A bug static analysis catches: == on Integer
import java.util.HashMap;import java.util.Map;
public class BoxedEqualsDemo { static Map<String, Integer> stock = new HashMap<>(); static Map<String, Integer> reserved = new HashMap<>();
/** Is everything in stock already reserved? (Static analysis flags the == below.) */ static boolean fullyReservedBuggy(String sku) { return stock.get(sku) == reserved.get(sku); // compares two Integer OBJECTS }
static boolean fullyReserved(String sku) { return stock.get(sku).equals(reserved.get(sku)); // compares the numbers }
public static void main(String[] args) { stock.put("MOB-IP15", 8); reserved.put("MOB-IP15", 8); stock.put("ACC-AD141", 120); reserved.put("ACC-AD141", 120); stock.put("BK-CLEAN", 300); reserved.put("BK-CLEAN", 300);
for (String sku : new String[] {"MOB-IP15", "ACC-AD141", "BK-CLEAN"}) { System.out.println(sku + ": with == " + fullyReservedBuggy(sku) + ", with equals " + fullyReserved(sku)); } }}MOB-IP15: with == true, with equals true ACC-AD141: with == true, with equals true BK-CLEAN: with == false, with equals true
What this code does
==compares twoIntegerobjects, not their values. Java reuses objects for -128 to 127, so 8 and 120 "work" and 300 fails: a bug that hides in testing with small numbers.- Sonar's rule
java:S4973flags this line as you type it.equals(orObjects.equals, which is also null-safe) compares the numbers.
A static analyser knows hundreds of rules about code that is likely wrong. Sonar's tools sort findings into three kinds: bugs (code that will probably misbehave, like == on boxed numbers), code smells (code that works but is hard to maintain, like an unused variable) and security hotspots (code that needs a human security review, like a hard-coded password).
Each rule has a key such as java:S4973 and a page that explains why it matters and how to fix it. The analyser cannot prove your logic is right; it finds known patterns of mistakes, quickly, on every line.
Find the bug
What would Sonar flag?
Each snippet has one line a static analyser reports. Tap it, then read the fix.
Tap the line that compares the wrong thing.
Round 1 of 3SonarQube for IDE in IntelliJ and VS Code
SonarQube for IDE (called SonarLint until late 2024) is a free plugin for IntelliJ IDEA, VS Code and Eclipse. It analyses each file as you edit it and underlines the findings in the editor.
Example 2 is a ShopLite service opened in the IDE: ten lines of code, five findings, all found before anything runs.
Example 2 · src/main/java/com/shoplite/report/DailyReportService.java with SonarQube for IDE
Runs in: IntelliJ IDEA or VS Code with SonarQube for IDE
package com.shoplite.report;
import java.io.FileWriter;import java.io.IOException;import java.math.BigDecimal;import java.util.List;
import org.springframework.stereotype.Service;
@Servicepublic class DailyReportService {
private static final String SMTP_PASSWORD = "Shop#Lite2026";
public void writeReport(List<OrderSummary> orders, String file) throws IOException { FileWriter writer = new FileWriter(file); BigDecimal total = BigDecimal.ZERO; for (OrderSummary o : orders) { if (o.customerId() == o.createdBy()) { writer.write(o.id() + "," + o.total() + "\n"); } } System.out.println("Report written: " + file); }}SonarQube for IDE: Current File (5 findings) Bug java:S2095 line 16 Use try-with-resources or close this "FileWriter" in a "finally" clause. Bug java:S4973 line 19 Use the "equals" method if value comparison was intended. Hotspot java:S2068 line 13 "PASSWORD" detected here, make sure this is not a hard-coded credential. Code smell java:S1481 line 17 Remove this unused "total" local variable. Code smell java:S106 line 23 Replace this use of System.out by a logger.
What this code does
- Five problems in ten lines, all found without running anything: a leaked file handle, a boxed comparison, a secret in Git, a dead variable and printing instead of logging.
- Each finding links to its rule page. The fixes are the ones from earlier modules: try-with-resources,
Objects.equals, configuration from the environment, delete the variable, an SLF4J logger.
The IDE lists the findings in its own tool window with the rule key and an explanation. Install it from the IDE's plugin marketplace (IntelliJ: Settings → Plugins; VS Code: Extensions) and search for "SonarQube for IDE".
In connected mode it downloads your team's rules from a SonarQube server or SonarQube Cloud, so everyone sees the same findings in the IDE as in CI.
Fix the error
Fix the finding
Each finding names a rule. Pick the replacement for the highlighted line.
Round 1 of 3
Open the report file so it always closes.
Error
java:S2095 Use try-with-resources or close this "FileWriter" in a "finally" clause.
Compiler warnings with -Xlint
-Xlint:all is a javac option that turns on every warning: unsafe generics (unchecked, rawtypes), a switch case without break (fallthrough), deprecation and more.
Example 3 compiles one small class twice: first with the default javac, then with -Xlint:all.
Example 3 · javac -Xlint:all finds a fall-through bug
import java.util.ArrayList;import java.util.List;
public class XlintDemo { @SuppressWarnings("rawtypes") static List skusFromOldApi() { // an old API that returns a raw List List skus = new ArrayList(); skus.add("MOB-IP15"); return skus; }
static String label(String status) { String text = ""; switch (status) { case "PLACED": text = "Placed"; // no break: falls through case "SHIPPED": text = "On the way"; break; default: text = status; } return text; }
public static void main(String[] args) { List<String> skus = skusFromOldApi(); // unchecked conversion System.out.println(skus.get(0)); System.out.println(label("PLACED")); }}$ javac XlintDemo.java
Note: XlintDemo.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
$ javac -Xlint:all XlintDemo.java
XlintDemo.java:8: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
skus.add("MOB-IP15");
^
where E is a type-variable:
E extends Object declared in interface List
XlintDemo.java:27: warning: [unchecked] unchecked conversion
List<String> skus = skusFromOldApi(); // unchecked conversion
^
required: List<String>
found: List
XlintDemo.java:17: warning: [fallthrough] possible fall-through into case
case "SHIPPED":
^
3 warnings
$ java XlintDemo
MOB-IP15
On the wayWhat this code does
- Without
-Xlint, javac only prints a vague note and says nothing about theswitch. With it, the fall-through is reported, and the run shows the bug: aPLACEDorder is labelled "On the way". - The
uncheckedwarnings point at the rawList: the compiler cannot check that onlyStringvalues go in, so a wrong type would fail later, far from its cause.
javac itself is a static analyser, but by default it prints only a short note about some warnings. In Maven, add -Xlint:all to the compiler plugin's compilerArgs, and consider failOnWarning once the existing warnings are fixed, so new ones cannot creep in.
Warnings are cheap to fix when they appear and expensive once there are hundreds.
Predict the output
Does it fall through?
Follow the switch. This is the kind of bug -Xlint:fallthrough reports.
Round 1 of 2
What is text when status is "SHIPPED"?
Fixing vs suppressing a finding, and SonarQube in CI
A suppression tells the analyser to ignore one finding in one place, such as @SuppressWarnings("unchecked") on one method, with a comment that says why.
In CI, one Maven command sends the analysis and the JaCoCo report to SonarQube, and can fail the build:
mvn verify sonar:sonar \ -Dsonar.host.url=https://sonar.example.com \ -Dsonar.token=$SONAR_TOKEN \ -Dsonar.qualitygate.wait=trueExample 4 · Suppressing narrowly, with a reason
import java.util.ArrayList;import java.util.List;
public class SuppressDemo { /** An old payment library we cannot change returns a raw List of Strings. */ @SuppressWarnings("rawtypes") static List legacyGatewayRefs() { List refs = new ArrayList(); addRef(refs, "UPI-7781"); addRef(refs, "UPI-7782"); return refs; }
@SuppressWarnings({"rawtypes", "unchecked"}) // part of the same legacy adapter static void addRef(List refs, String ref) { refs.add(ref); }
/** * Suppressed on purpose, as narrowly as possible: one method, one warning type, one reason. * The library documents that every element is a String, and we copy into a typed list at once. */ @SuppressWarnings("unchecked") static List<String> gatewayRefs() { return new ArrayList<>(legacyGatewayRefs()); }
public static void main(String[] args) { List<String> refs = gatewayRefs(); for (String ref : refs) { System.out.println("Payment reference " + ref); } }}Payment reference UPI-7781 Payment reference UPI-7782
What this code does
- The raw types come from a library we cannot change, so the warnings are expected here. Each
@SuppressWarningssits on one small method and names only the warnings that method causes; with-Xlint:allthis file compiles with no warnings. - The rest of the code only sees
List<String>, so the unsafe part stays inside one small adapter instead of spreading.
Almost always, fix the finding. Suppress only when the rule is wrong for this exact place, for example a raw List returned by a library you cannot change, and then as narrowly as you can: @SuppressWarnings("unchecked") on one method, with a comment saying why. Never suppress a whole class to make a report green.
A SonarQube quality gate is the pass-or-fail rule for a build, such as "no new bugs, no unreviewed hotspots, at least 80% coverage on new code". Example 4 shows a suppression done right.
Order of execution
Handle one finding
Put the steps in the order a careful developer takes them.
Next step
Check your understanding
12 quick questions