Prev Next

Tools / PMD Source Code Analyzer Interview questions

Last updated

1. What is static code analysis? 2. What is PMD? 3. What does PMD stand for? 4. Which programming languages does PMD support? 5. What are the key features of PMD? 6. What types of problems can PMD detect? 7. What is a PMD ruleset? 8. What are the PMD rule categories? 9. What is rule priority in PMD? 10. How do you install PMD? 11. How do you run PMD from the command line? 12. What output formats does PMD support? 13. What is CPD in PMD? 14. How do you use PMD with Maven? 15. How do you use PMD with Gradle? 16. What is the PMD Rule Designer? 17. How do you suppress a PMD violation? 18. What is the quickstart ruleset in PMD? 19. What is the difference between PMD and Checkstyle? 20. What is the difference between PMD and SpotBugs? 21. How does PMD analyze source code internally? 22. What is an AST in PMD? 23. How do you reference and exclude rules in a custom ruleset? 24. How do you configure rule properties in PMD? 25. How do you exclude files from PMD analysis? 26. How do you create a custom PMD rule using XPath? 27. How do you write a custom PMD rule in Java? 28. Why does PMD need auxclasspath? 29. How do you fail a build on PMD violations? 30. How do you integrate PMD into a CI/CD pipeline? 31. What is the difference between @SuppressWarnings and NOPMD? 32. How does CPD detect duplicate code? 33. How do you tune CPD to ignore identifiers and literals? 34. How do you generate a SARIF report from PMD? 35. What is the difference between PMD 6 and PMD 7? 36. How does PMD incremental analysis work? 37. What is the difference between CyclomaticComplexity and CognitiveComplexity rules? 38. How do you speed up PMD on large codebases? 39. How do you adopt PMD on a legacy codebase with many violations? 40. How do you handle PMD false positives across a team? 41. Why might PMD miss a violation you expected? 42. How do you unit test a custom PMD rule? 43. How do you use violationSuppressXPath in a ruleset? 44. How do you troubleshoot PMD parse errors? 45. How does PMD work with Salesforce Apex? 46. How does PMD fit alongside SonarQube? 47. What is the difference between pmd:pmd and pmd:check in Maven? 48. How does the PMD rule chain improve performance? 49. How do you choose which PMD rules your team should enable? 50. Why does PMD flag a GodClass and how do you fix it?

1. What is static code analysis?

Static code analysis is the practice of inspecting source code for defects, risky patterns and style problems without executing it. A tool parses the code, builds a model such as an abstract syntax tree, and checks that model against a set of rules.

It catches issues early, usually at build time or inside the IDE, long before testing or production. Typical findings are unused variables, empty catch blocks, possible null dereferences and overly complex methods.

It complements unit tests and code reviews but does not replace them, because it cannot judge runtime behavior or business logic.

Take quiz
Which statement describes static code analysis?
Inspecting source code for problems without running it
Monitoring server memory in production
Measuring response time while the app runs under load
Replacing unit tests with automated deployments
When does static analysis usually flag issues?
Only after the application is deployed
Only during penetration testing
Only when users report bugs
Early, at build time or in the IDE

2. What is PMD?

PMD is an open-source static source code analyzer. It scans source files, matches them against rules and reports violations such as unused variables, empty catch blocks, unnecessary object creation and overly complex code.

It is written in Java and ships with hundreds of ready-made rules for Java, Apex, JavaScript, PL/SQL and other languages. You can run it from the command line, Maven, Gradle, Ant or an IDE plugin.

PMD also bundles CPD, a copy-paste detector that finds duplicated code, and you can add your own rules written in Java or XPath.

Take quiz
What does PMD do with your source files?
Scans them against rules and reports violations without running the code
Encrypts them before they are committed
Compiles them into bytecode for deployment
Executes them to measure runtime performance
Which tool bundled with PMD finds duplicated code?
JDB
JaCoCo
Javadoc
CPD

3. What does PMD stand for?

PMD is not an official acronym. The project documentation says the name does not stand for anything in particular.

Over the years people have invented backronyms such as Programming Mistake Detector or Project Mess Detector. They are good for a smile in an interview, but you should not present any of them as the official meaning.

If an interviewer asks, say the name is just a name, then move on to what the tool actually does: static analysis of source code.

Take quiz
What is the official expansion of PMD?
Package Management Descriptor
Program Memory Dump
It has none; the name is not an official acronym
Performance Monitoring Daemon
Which is a commonly quoted unofficial backronym for PMD?
Parallel Memory Debugger
Programming Mistake Detector
Portable Module Deployer

4. Which programming languages does PMD support?

PMD's deepest support is for Java, followed by Apex for Salesforce. Other languages are covered with a smaller rule set.

Language Notes
Java Largest rule set, with type resolution
Apex Salesforce rules for SOQL, DML, security and tests
Visualforce Mainly security rules for Salesforce pages
JavaScript ECMAScript rules, a smaller set
PL/SQL Rules for stored procedures and packages
XML / Maven POM XML-based rules, including POM checks
Kotlin, Swift Added in PMD 7 with a smaller rule set

CPD supports an even longer list of languages for duplicate detection. Support changes between releases, so check the documentation for your version.

Take quiz
Which language has the largest set of built-in PMD rules?
Modelica
Swift
Velocity
Java
Which Salesforce language does PMD analyze besides Visualforce?
Apex
Haskell
Elixir

5. What are the key features of PMD?

PMD is valued because it is free, fast and easy to customize. Its main features are:

  • Hundreds of built-in rules grouped into categories such as error prone and best practices
  • Custom rules written in Java or XPath
  • XML rulesets that select rules and tune their properties
  • Report formats such as text, XML, HTML, CSV, JSON and SARIF
  • Integration with the CLI, Maven, Gradle, Ant, CI servers and IDEs
  • CPD for copy-paste detection
  • Suppression through annotations and comments
  • An incremental analysis cache for faster repeat runs
Take quiz
Which feature lets teams add organization-specific checks?
Custom rules written in Java or XPath
Only the bundled quickstart ruleset
A fixed rule list that cannot be changed
What speeds up repeat PMD runs on unchanged files?
The incremental analysis cache
Renaming the ruleset file
Converting reports to HTML
Raising every rule priority

6. What types of problems can PMD detect?

PMD finds code that is probably wrong, wasteful or hard to maintain. It matches known patterns, so it flags suspicious constructs rather than proving a bug.

Problem type Example rules
Likely bugs EmptyCatchBlock, AvoidBranchingStatementAsLastInLoop
Dead code UnusedLocalVariable, UnusedPrivateMethod, UnusedPrivateField
Complexity CyclomaticComplexity, GodClass, ExcessiveParameterList
Performance AvoidInstantiatingObjectsInLoops
Style ControlStatementBraces, ClassNamingConventions
Security HardCodedCryptoKey, InsecureCryptoIv

Take quiz
Which is an example of dead code that PMD detects?
An unused private method
A slow database query
A missing network cable
A failing integration test
Which PMD category covers rules like HardCodedCryptoKey?
Code Style
Documentation
Multithreading
Security

7. What is a PMD ruleset?

A ruleset is an XML file that groups rules and tells PMD which ones to run. It can reference single rules or whole categories, and it can override a rule's priority or properties.

<?xml version="1.0"?>
<ruleset name="Team Rules"
         xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
  <description>Rules for our services</description>
  <rule ref="category/java/bestpractices.xml/UnusedLocalVariable"/>
  <rule ref="category/java/errorprone.xml/EmptyCatchBlock"/>
</ruleset>

Pass it with -R on the command line or point to it from the Maven or Gradle configuration. Keep it in version control so developers and the CI server run the same rules.

Take quiz
What format is a PMD ruleset file?
Plain CSV
XML
Java properties only
A compiled binary
What does the ref attribute of a rule element point to?
A Git branch name
A Maven dependency version
A rule or category defined in a PMD rule file

8. What are the PMD rule categories?

Since PMD 6, rules are grouped into eight categories. Each category has its own XML file per language, for example category/java/design.xml.

Category Focus
Best Practices Generally accepted good practices
Code Style Formatting and naming conventions
Design Sound design, such as complexity and coupling
Documentation Comments and documentation
Error Prone Constructs likely to cause bugs
Multithreading Concurrency problems
Performance Inefficient code
Security Potential vulnerabilities

You can enable a whole category and exclude the rules that are too noisy for your team.

Take quiz
Which category flags constructs that are likely to cause bugs?
Performance
Error Prone
Code Style
Documentation
Where would a thread-safety rule live?
Best Practices
Multithreading
Code Style
Documentation

9. What is rule priority in PMD?

Every rule carries a priority from 1 (highest) to 5 (lowest). It signals how serious a violation is, from a change that is absolutely required down to an optional improvement.

You can override the priority inside a ruleset and filter the report with the minimum priority option:

<rule ref="category/java/design.xml/GodClass">
  <priority>2</priority>
</rule>

Running with --minimum-priority 3 skips rules whose priority is lower than 3. Teams often fail the build on priorities 1 and 2 first and tighten the gate later.

Take quiz
Which priority number is the most severe?
3
5
1
What does --minimum-priority do?
Skips rules whose priority is lower than the given level
Limits how many files are scanned
Raises every rule to priority 1

10. How do you install PMD?

PMD needs no installer. It is a zip distribution that runs on a Java runtime.

  1. Make sure a Java runtime is installed.
  2. Download the pmd-dist-<version>-bin.zip file from the PMD releases page on GitHub.
  3. Unzip it to a folder of your choice.
  4. Add the bin folder to your PATH.
  5. Verify with pmd --version.

On macOS you can also use Homebrew. If you only need PMD inside a build, skip the download: the Maven and Gradle plugins fetch PMD as a dependency.

Take quiz
How do you verify the PMD installation?
Open a registry key
Run mvn install on the zip file
Run pmd --version from a terminal
Which build tools let you use PMD without a manual download?
Only Ant
Maven and Gradle plugins
None, a manual install is always required

11. How do you run PMD from the command line?

In PMD 7 you use the check subcommand with a source folder, one or more rulesets and an output format.

pmd check -d src/main/java -R rulesets/java/quickstart.xml -f text

  • -d or --dir: files or folders to analyze
  • -R: ruleset or rule references, comma separated
  • -f: report format
  • -r: write the report to a file
  • --aux-classpath: compiled classes and jars for type resolution

PMD 6 uses run.sh pmd (or pmd.bat) with the same -d, -R and -f options. The exit code is 4 when violations are found, so a script can fail on it.

Take quiz
Which option selects the ruleset in the PMD CLI?
-R
-f
-d
What exit code does PMD return when it finds violations?
2
4
0
1

12. What output formats does PMD support?

The -f option picks the report format and -r writes it to a file. Common formats include:

  • text and textcolor for the console
  • html for people to read
  • xml, json and csv for scripts and tools
  • sarif for code scanning platforms
  • checkstyle, codeclimate and junit for tools that already understand those formats

The exact list depends on the PMD version. Use XML, JSON or SARIF when another tool consumes the result and HTML when a person reads it.

Take quiz
Which format suits uploading results to GitHub code scanning?
text
csv
sarif
Which option writes the PMD report to a file?
-R (--rulesets)
-r (--report-file)
-d (--dir)

13. What is CPD in PMD?

CPD, the Copy/Paste Detector, finds duplicated code. It does not look for a specific pattern. Instead it compares sequences of tokens across files and reports blocks that repeat.

The key setting is the minimum tokens value. A lower number finds smaller duplicates but adds noise.

pmd cpd --minimum-tokens 100 --dir src --language java

CPD works for many languages, including some that PMD has no rules for. In Maven the goals are pmd:cpd and pmd:cpd-check.

Take quiz
What does CPD compare to find duplicates?
Test coverage percentages
Compiled class file sizes
Sequences of tokens across files
Git commit messages
What happens if you lower the minimum tokens value?
CPD ignores all duplicates
CPD reports smaller duplicates, usually with more noise
CPD scans only test code

14. How do you use PMD with Maven?

Add the maven-pmd-plugin to the build and bind its check goal.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-pmd-plugin</artifactId>
  <version>${pmd.plugin.version}</version>
  <configuration>
    <rulesets>
      <ruleset>config/pmd/ruleset.xml</ruleset>
    </rulesets>
    <failOnViolation>true</failOnViolation>
    <printFailingErrors>true</printFailingErrors>
  </configuration>
  <executions>
    <execution>
      <goals>
        <goal>check</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Run mvn pmd:pmd to only produce a report, or mvn verify to run check, which binds to the verify phase by default and runs pmd:pmd first.

Take quiz
Which goal fails the build when violations are found?
pmd:cpd
pmd:check
pmd:pmd
Which phase does pmd:check bind to by default?
clean
verify
deploy
compile

15. How do you use PMD with Gradle?

Apply the built-in pmd plugin and configure it in a pmd block.

plugins {
    id 'java'
    id 'pmd'
}

pmd {
    toolVersion = '<pmd-version>'
    ruleSetFiles = files('config/pmd/ruleset.xml')
    ruleSets = []
    ignoreFailures = false
}

Setting ruleSets = [] stops Gradle from also applying its default ruleset. The plugin adds pmdMain and pmdTest tasks, wires them into check and writes reports under build/reports/pmd.

Take quiz
Which Gradle task runs PMD against production code?
pmdSource
compilePmd
pmdProd
pmdMain
Which property keeps the build going despite violations?
ruleSetFiles = null
toolVersion = 'none'
ignoreFailures = true

16. What is the PMD Rule Designer?

The Rule Designer is a desktop tool for exploring the AST and writing rules. You paste a code sample, see its AST as a tree, type an XPath query and watch the matching nodes highlight immediately.

It also lists the attributes of each node, such as @Name, which you can use in XPath. Once the query works, you can export it into a rule definition. Start it with pmd designer in PMD 7 or designer.sh in PMD 6.

Take quiz
What is the Rule Designer mainly used for?
Compiling Java sources
Generating HTML reports
Installing PMD updates
Building and testing rules by inspecting the AST
Which command starts the Designer in PMD 7?
pmd designer
pmd check --gui
pmd draw

17. How do you suppress a PMD violation?

PMD gives several ways to silence a violation. Choose the narrowest one that works.

Method Example Scope
Annotation @SuppressWarnings("PMD.UnusedLocalVariable") Annotated class, method or field
Annotation, all rules @SuppressWarnings("PMD") Annotated element
Comment // NOPMD That line
Ruleset pattern <exclude-pattern> Matching files
XPath property violationSuppressXPath Matching nodes

Add a reason, for example // NOPMD - required by reflection, so reviewers know it was a deliberate decision.

Take quiz
How do you suppress one specific rule for one method?
Delete the ruleset file
@SuppressWarnings("PMD.RuleName") on the method
// NOPMD at the top of the file
What does // NOPMD do?
Suppresses violations reported on that line
Disables PMD for the whole project
Deletes the line before analysis

18. What is the quickstart ruleset in PMD?

rulesets/java/quickstart.xml is a curated ruleset shipped with PMD. It gives you sensible defaults without reading through hundreds of rules. It contains rules the PMD team considers broadly useful and low in false positives, and it lists more rules as comments that you can opt into.

Treat it as a starting point. Copy it into your repository, remove what does not fit and add what you need. The content changes between PMD releases, so review the release notes when you upgrade.

Take quiz
Why does PMD ship a quickstart ruleset?
To give a sensible default set of rules to start with
To replace the PMD CLI
To store analysis results
To run every rule in every language
How should you customize the quickstart ruleset?
Edit the file inside the PMD distribution
Copy it into your project and edit your copy
Delete it before every run

19. What is the difference between PMD and Checkstyle?

Both analyze Java source, and their rules overlap a little, but their goals differ. PMD looks for flaws and bad practices. Checkstyle enforces coding standards.

Aspect PMD Checkstyle
Main focus Flaws, bad practices, complexity Coding standards and formatting
Typical findings Unused variable, empty catch block Missing Javadoc, line length, indentation
Languages Java, Apex, JavaScript and more Mostly Java
Custom rules XPath or Java Configurable modules or Java checks

Many teams run both: Checkstyle for formatting and PMD for correctness and design.

Take quiz
Which tool primarily enforces formatting such as indentation and line length?
SpotBugs
Checkstyle
PMD
CPD
What is a key difference in scope?
PMD targets flaws and bad practices while Checkstyle targets coding standards
Both analyze bytecode only
PMD only checks formatting while Checkstyle only finds bugs

20. What is the difference between PMD and SpotBugs?

PMD analyzes source code, while SpotBugs analyzes compiled bytecode. That choice shapes what each tool finds.

Aspect PMD SpotBugs
Input Source files Compiled classes
Needs compilation No, though a classpath improves results Yes
Strength Bad practices, complexity, style, custom rules Bug patterns found through bytecode data-flow analysis
Custom checks Quick to write with XPath Needs a Java detector plugin

They are complementary. SpotBugs digs deeper into likely runtime bugs, and PMD is better at maintainability and house rules.

Take quiz
What does SpotBugs analyze?
Git history
The Maven POM only
Compiled bytecode
Raw source text only
Which tool can run without compiled classes?
SpotBugs
Neither, both always need compiled classes
PMD

21. How does PMD analyze source code internally?

PMD turns each source file into a tree and lets rules inspect that tree. The flow has six steps:

  1. Collect the files and pick the language version for each one.
  2. Parse every file into an AST with the language's parser.
  3. Build the symbol table and, for Java, resolve types using the auxiliary classpath.
  4. Run the rules. XPath rules query the tree and Java rules visit nodes.
  5. Collect violations with file, line, rule name, priority and message.
  6. Hand the violations to a renderer that writes text, XML, HTML, JSON or SARIF.
flowchart LR
A["Source files"] --> B[Parser]
B --> C[AST]
C --> D["Symbol table and types"]
D --> E["Rules visit nodes"]
E --> F[Violations]
F --> G[Renderer]

Files that cannot be parsed are reported as processing errors, and PMD continues with the rest.

Take quiz
What does PMD build from each source file before running rules?
An abstract syntax tree
A UML diagram
A compiled JAR
A heap dump
What turns collected violations into text, XML or SARIF output?
The parser
The classloader
A renderer

22. What is an AST in PMD?

An AST (abstract syntax tree) is a tree view of the structure of your code. Each node is a language construct such as a class declaration, a method declaration, an if statement or a method call.

PMD rules query or walk this tree instead of raw text, so they understand structure and are not confused by whitespace or line breaks. For example, in PMD 7 the method below is a MethodDeclaration containing a Block, which holds a LocalVariableDeclaration with a VariableId named x and a NumericLiteral 1.

void run() { int x = 1; }

Node names differ between languages and between PMD 6 and 7, for example ASTMethodDeclaration in Java rule code. Use the Rule Designer to see the exact tree for your snippet.

Take quiz
Why do PMD rules operate on an AST?
It stores results in a database
It makes the application run faster
It converts Java to bytecode first
It exposes code structure, so rules ignore formatting
Which tool lets you look at the AST of a snippet?
CPD
Maven Surefire
The Rule Designer

23. How do you reference and exclude rules in a custom ruleset?

Reference one rule by its full path, or reference a whole category and exclude the rules you do not want.

<rule ref="category/java/errorprone.xml">
  <exclude name="AvoidLiteralsInIfCondition"/>
  <exclude name="MissingSerialVersionUID"/>
</rule>

<rule ref="category/java/design.xml/CyclomaticComplexity">
  <priority>2</priority>
</rule>

Excluding is easier to maintain than listing dozens of rules by hand, because rules added to the category in a later release are picked up automatically. That can also create new violations after an upgrade, so pin the PMD version and read the release notes.

Take quiz
How do you enable a whole category except one noisy rule?
Reference the category and add an exclude for that rule
Delete the rule from PMD's jar
Rename the category file
What does priority 2 inside a rule reference do?
Limits the rule to two files
Runs the rule twice
Overrides that rule's priority in your ruleset

24. How do you configure rule properties in PMD?

Many rules expose properties with defaults. You override them inside the rule reference in your ruleset:

<rule ref="category/java/design.xml/CyclomaticComplexity">
  <properties>
    <property name="methodReportLevel" value="15"/>
  </properties>
</rule>

<rule ref="category/java/design.xml/ExcessiveParameterList">
  <properties>
    <property name="minimum" value="6"/>
  </properties>
</rule>

The documentation page of each rule lists its properties, types and defaults. A wrong property name or an invalid value makes PMD report a configuration error at startup, which is useful because typos do not silently pass.

Take quiz
Where do you find a rule's configurable properties?
Only in the JVM options
On that rule's documentation page
In the Git log
What does methodReportLevel control in CyclomaticComplexity?
The number of threads PMD uses
The maximum number of methods per class
The complexity at which a method is reported

25. How do you exclude files from PMD analysis?

There are a few places to exclude files, depending on how you run PMD.

  • Ruleset: add <exclude-pattern>.*/generated/.*</exclude-pattern>, a regular expression matched against the file path. include-pattern narrows it back.
  • Maven: use <excludes><exclude>**/generated/**/*.java</exclude></excludes> and excludeRoots for generated source folders.
  • Gradle: configure the task, for example pmdMain { exclude '**/generated/**' }.
  • CLI: only pass the folders you want to -d, or use a file list.

Generated code, vendored libraries and build output are the usual candidates, since violations there are not yours to fix.

Take quiz
Which ruleset element skips files matching a regex?
skip-files
omit
exclude-pattern
ignore-glob
In Maven, which element holds Ant-style path exclusions?
<ignoreFolders>
<excludes> with <exclude> entries
<skipPaths>

26. How do you create a custom PMD rule using XPath?

XPath is the quickest way to add a rule. Open the Rule Designer, paste a code sample, write a query that selects the offending nodes, then put it in a ruleset:

<rule name="NoFinalizeMethods"
      language="java"
      message="Do not declare finalize(); use try-with-resources or a Cleaner"
      class="net.sourceforge.pmd.lang.rule.xpath.XPathRule">
  <description>Flags methods named finalize.</description>
  <priority>3</priority>
  <properties>
    <property name="xpath">
      <value><![CDATA[
//MethodDeclaration[@Name = 'finalize']
      ]]></value>
    </property>
  </properties>
</rule>

Every node the query returns becomes a violation. Wrap the XPath in CDATA so characters such as < do not break the XML.

Take quiz
What does an XPath rule need to express its check?
A compiled class file for each rule
A database of past violations
A regular expression over raw bytes
An xpath property holding a query over AST nodes
Which tool helps you test the XPath before using it?
Javadoc
The Rule Designer
The Maven site plugin

27. How do you write a custom PMD rule in Java?

Use a Java rule when XPath cannot express the logic, for example when you need counters, helper methods or several checks combined. In PMD 7 you extend AbstractJavaRulechainRule and declare the node types you want:

public class NoFinalizeRule extends AbstractJavaRulechainRule {
    public NoFinalizeRule() {
        super(ASTMethodDeclaration.class);
    }

    @Override
    public Object visit(ASTMethodDeclaration node, Object data) {
        if ("finalize".equals(node.getName())) {
            asCtx(data).addViolation(node);
        }
        return data;
    }
}

Compile it into a jar, put the jar on PMD's classpath and reference the class in your ruleset with the class attribute. Add a test file for it, as covered in the testing question.

Take quiz
When should you choose a Java rule over XPath?
When the logic is too complex to express in XPath
When the code has no methods
When you want the rule to run on bytecode
Never, XPath is mandatory
Which call reports a violation in a PMD 7 Java rule?
asCtx(data).addViolation(node)
node.delete()
System.err.println(node)

28. Why does PMD need auxclasspath?

Some rules need the real type of a variable or the exact method being called. PMD reads only source files, so it cannot see types that live in your dependencies unless you give it the compiled classes and jars.

Pass them with --aux-classpath. Without it, type-aware rules can miss violations, and PMD may log warnings about types it could not resolve. For example, a rule that checks whether a variable is a java.util.List must resolve the declared type first.

pmd check -d src/main/java -R ruleset.xml --aux-classpath target/classes:libs/*

The Maven and Gradle plugins pass the project classpath for you, so the problem mostly shows up in standalone CLI runs.

Take quiz
What does --aux-classpath give PMD?
Compiled classes and jars used to resolve types
A cache folder for reports
A list of rules to skip
What can happen when the auxiliary classpath is missing?
PMD refuses to start
Type-aware rules may miss violations
Every rule automatically passes

29. How do you fail a build on PMD violations?

By default the PMD CLI exits with code 4 when it finds violations, so most CI systems fail the step on their own. Each tool also has its own switch:

Tool Setting
PMD 7 CLI --no-fail-on-violation turns the failure off
PMD 6 CLI -failOnViolation false
Maven failOnViolation and failurePriority on pmd:check
Gradle ignoreFailures, false by default

In Maven, failurePriority defaults to 5. Setting it to 3 fails the build only for violations of priority 1 to 3. That is a good way to start with a strict gate on serious issues and tighten it later.

Take quiz
Which Maven setting limits failures to higher-severity violations?
reportLevel
targetJdk
minimumTokens
failurePriority
How does a CI job learn that PMD found violations?
Through an email sent by PMD
Through a changed file timestamp
Through a non-zero exit code, which is 4

30. How do you integrate PMD into a CI/CD pipeline?

Run PMD after the build step and before merge or deployment, and publish the report so developers can read it.

flowchart LR
A["Commit or pull request"] --> B[Build]
B --> C["PMD check"]
C --> D{Violations above threshold?}
D -- Yes --> E["Fail build and publish report"]
D -- No --> F["Continue pipeline"]
  • GitHub Actions: the pmd/pmd-github-action action runs PMD and can produce SARIF for code scanning.
  • Jenkins: run mvn verify or the CLI, then publish pmd.xml with the Warnings Next Generation plugin to see trends.
  • Any CI: keep the ruleset in the repository and pin the PMD version so builds are repeatable.
Take quiz
Where in a pipeline should PMD usually run?
Only on developer laptops
After the build, before merge or deploy
Only after production deployment
Which Jenkins plugin can show PMD results as trends?
Email Extension
Warnings Next Generation
Credentials Binding

31. What is the difference between @SuppressWarnings and NOPMD?

Aspect @SuppressWarnings // NOPMD
Scope The annotated class, method, field or variable The single line
Rule targeting Can name one rule, such as PMD.UnusedLocalVariable Suppresses every violation on that line
Nature Part of the language, visible to IDEs and compilers Plain comment read by PMD
Languages Java and Apex Any language PMD analyzes

Use the annotation when you need to target one rule or cover a whole method. Use NOPMD for a one-line exception. The marker can be changed with --suppress-marker.

Take quiz
Which suppression can name one specific rule?
@SuppressWarnings("PMD.RuleName")
Renaming the file
// NOPMD on a line
Which suppression is tied to a single source line?
@SuppressWarnings on a class
// NOPMD
exclude-pattern in a ruleset

32. How does CPD detect duplicate code?

CPD works on tokens instead of text, using the Karp-Rabin string matching algorithm. In short:

  1. A language tokenizer splits each file into tokens.
  2. CPD slides a window of the minimum-token length over each file.
  3. Each window is hashed and equal hashes are matched.
  4. Matches are verified and reported with files and line ranges.

Whitespace and comments are not tokens, so reformatting copied code does not hide it. By default identifiers and literals do count, so a copy with renamed variables is not matched unless you use the ignore options.

Take quiz
Why does reformatting copied code not hide it from CPD?
CPD reads Git blame data
CPD compares tokens, not whitespace or comments
CPD reformats code before every commit
Which algorithm family does CPD use for matching?
Dijkstra shortest path
Karp-Rabin string matching
Quicksort partitioning

33. How do you tune CPD to ignore identifiers and literals?

CPD has options that make it treat near-copies as duplicates:

Option Effect
--ignore-identifiers Renamed variables and methods still match
--ignore-literals Different strings and numbers still match
--ignore-annotations Annotations are skipped
--ignore-literal-sequences Long literal lists, such as data tables, are skipped

To skip a block, wrap it in // CPD-OFF and // CPD-ON comments. Ignoring identifiers and literals finds more real duplication but also more false matches, so raise the minimum tokens a little when you turn them on.

Take quiz
Which option makes CPD treat renamed variables as the same?
--ignore-comments
--skip-lexical-errors
--ignore-identifiers
How do you skip a block of code in CPD?
Wrap it in // CPD-OFF and // CPD-ON comments
Rename the file to .skip
Prefix it with @NoCPD

34. How do you generate a SARIF report from PMD?

SARIF is a JSON standard for static analysis results. PMD 7 has a built-in renderer:

pmd check -d src/main/java -R ruleset.xml -f sarif -r pmd.sarif

In GitHub, upload the file with the github/codeql-action/upload-sarif action. The findings then appear as code scanning alerts in the repository and on pull requests. Editors such as VS Code can also open SARIF files locally.

Take quiz
What is SARIF?
A Java build tool
A PMD ruleset language
A code coverage format
A JSON-based standard format for static analysis results
Where can an uploaded SARIF file show alerts?
Docker Hub
GitHub code scanning
Maven Central

35. What is the difference between PMD 6 and PMD 7?

Area PMD 6 PMD 7
CLI run.sh pmd, single-dash options like -d pmd check with subcommands and long options like --dir
Java AST Older node structure Reworked Java grammar and AST
Custom rules Written against the old AST XPath and Java rules often need updates
Languages No Kotlin or Swift Kotlin and Swift added
Reports Fewer built-in formats Native SARIF output
Rules Original set Some renamed, moved or removed

To upgrade, read the migration notes in the release notes, run PMD 7 with your current ruleset, fix any unknown-rule errors, then port custom XPath and Java rules. The Rule Designer helps with the new AST.

Take quiz
Which command style is used in PMD 7?
pmd-scan
run.sh pmd only
pmd check
What typically breaks custom rules when upgrading to PMD 7?
Rulesets must be written in JSON
The Java AST was reworked, so rules need updates
Rules must be written in Kotlin

36. How does PMD incremental analysis work?

PMD can store results so unchanged files are not analyzed again. Enable it with --cache <file>.

On the next run PMD compares file checksums and a fingerprint of the ruleset, PMD version and classpath. If nothing changed for a file, its earlier violations are reused. If the ruleset, PMD version or classpath changed, the cache is invalidated and everything is analyzed again.

pmd check -d src -R ruleset.xml --cache build/pmd.cache

The Maven plugin exposes this as analysisCache. In CI, save and restore the cache file between runs, otherwise it brings no benefit. Use --no-cache to switch it off.

Take quiz
What invalidates PMD's incremental cache?
Changing the ruleset, PMD version or classpath
Running on a different weekday
Opening a file in an editor
Which option turns on the cache in PMD 7?
--incremental-off
--fast-forward
--cache <file>

37. What is the difference between CyclomaticComplexity and CognitiveComplexity rules?

Both flag methods that are hard to work with, but they measure different things.

Cyclomatic complexity counts decision points such as if, for, while, case, catch, && and ||. It approximates the number of independent execution paths, so it hints at how many test cases you need. A flat switch with ten cases scores high even though it reads easily.

Cognitive complexity measures how hard code is to understand. It adds a growing penalty for nesting and for breaks in linear flow, and it treats a flat switch or a chain of boolean operators more gently.

Aspect CyclomaticComplexity CognitiveComplexity
Measures Independent paths Readability
Nesting No extra cost Extra penalty per level
Flat switch Scores high Counts once
Default report level Methods at 10, classes at 80 Methods at 15
Best used for Estimating test effort Finding hard-to-read code

Using both is reasonable: cyclomatic complexity guides testing, and cognitive complexity guides refactoring.

Take quiz
Which metric adds an extra penalty for nested control flow?
Cyclomatic complexity
Cognitive complexity
Fan-out
Lines of code
What does cyclomatic complexity approximate?
The length of the method name
The memory used by a method
The number of independent execution paths

38. How do you speed up PMD on large codebases?

Most of the time goes into parsing files and running rules, so speed-ups come from doing less work or doing it in parallel.

  • Threads: use --threads, for example --threads 4 or --threads 1C for one per core.
  • Cache: enable --cache and persist the file between CI runs.
  • Scope: on pull requests, analyze only changed files by passing a list with --file-list.
  • Ruleset: remove rules nobody acts on, since every rule costs time.
  • Inputs: exclude generated code and build output.
  • Memory: raise the heap with the PMD_JAVA_OPTS environment variable if PMD is swapping or running out of memory.

To find slow rules, run with --benchmark, which prints timing per rule and per phase. Fix the biggest costs first instead of guessing.

Take quiz
Which option runs analysis in parallel?
--async-report
--threads
--batch
How can pull request builds be made faster?
Disable the parser
Run every rule on all branches
Analyze only changed files with a file list, plus a cache

39. How do you adopt PMD on a legacy codebase with many violations?

Turning on every rule on day one produces thousands of findings and teaches everyone to ignore the report. A staged approach works better:

  1. Run PMD once and count violations per rule to see where the noise is.
  2. Start with a small ruleset such as the quickstart, focused on error prone and best practices.
  3. Gate only new or changed code. PMD reports everything it finds, so teams usually analyze changed files or compare against a stored baseline report.
  4. Fix one rule at a time, using IDE quick fixes or refactoring tools where possible.
  5. Tighten gradually: fail on priority 1 and 2, then add 3, then add more rules.
  6. Track the total count per release so progress is visible.

Avoid blanket @SuppressWarnings("PMD") on classes. It hides real problems and removes the signal that PMD provides. When you must suppress, use the narrowest scope and add a reason.

Take quiz
What is a sound first step on a legacy codebase?
Start with a small ruleset and gate only new or changed code
Enable every rule and fail all builds
Delete files that have violations
Add a blanket suppression to every class
Why avoid blanket suppressions?
They hide real issues and remove PMD's signal
They make PMD crash
They are not valid Java

40. How do you handle PMD false positives across a team?

Treat each report as a question about the rule, not as an argument about the code. A simple triage order keeps things consistent:

  1. Reproduce it with a minimal snippet in the Rule Designer.
  2. Tune the rule if a property fixes it, for example a higher threshold.
  3. Scope it out with violationSuppressXPath if a pattern is always fine, such as test classes.
  4. Suppress narrowly for a single justified case, with a comment that explains why.
  5. Remove the rule from the shared ruleset if it is noisy everywhere.
  6. Report a bug to PMD on GitHub with the minimal sample and the PMD version if the rule is genuinely wrong.

Review ruleset changes in pull requests and note why a rule was removed, so the decision is not repeated every few months.

Take quiz
What is the best way to handle one justified exception?
Disable the whole category
A narrow suppression with a comment explaining why
Downgrade PMD
Where should a genuine PMD bug be reported?
The JVM bug tracker
The PMD GitHub issue tracker with a minimal reproducer
A Maven plugin POM

41. Why might PMD miss a violation you expected?

When a violation is missing, check the cheap explanations first:

  • The rule is not in the ruleset, or it was excluded from a category reference.
  • The file is filtered out by an exclude-pattern, a Maven exclude or a Gradle exclude.
  • The violation is hidden by a NOPMD comment, an annotation or violationSuppressXPath.
  • --minimum-priority removed rules below your threshold.
  • The file failed to parse, so it was reported as a processing error and skipped.
  • A type-aware rule could not resolve a class because the auxiliary classpath is incomplete.
  • The rule works on patterns that PMD sees largely file by file, so bugs that need whole-program data flow are out of reach.

To debug, paste the snippet into the Rule Designer, run only that rule on a single file, and add --debug to see what PMD loads. If the rule really misses a clear case, open an issue with the sample.

Take quiz
Which is a common cause of a missed violation?
PMD ignores public classes
The rule is excluded or filtered by minimum priority
PMD only scans files named Main
What limitation keeps PMD from finding bugs that need whole-program data flow?
It only reads comments
It analyzes largely file by file, using patterns
It needs a debugger attached

42. How do you unit test a custom PMD rule?

PMD provides the pmd-test module with the PmdRuleTst base class. Add the dependency in test scope, create a test class and an XML file with the sample code and expected result.

public class NoFinalizeRuleTest extends PmdRuleTst {
    // test cases are loaded from xml/NoFinalizeRule.xml
}

<?xml version="1.0" encoding="UTF-8"?>
<test-data xmlns="http://pmd.sourceforge.net/rule-tests"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://pmd.sourceforge.net/rule-tests https://pmd.sourceforge.io/rule-tests_1_0_0.xsd">
  <test-code>
    <description>finalize method is flagged</description>
    <expected-problems>1</expected-problems>
    <code><![CDATA[
public class A {
    @Override
    protected void finalize() { }
}
    ]]></code>
  </test-code>
  <test-code>
    <description>normal method is not flagged</description>
    <expected-problems>0</expected-problems>
    <code><![CDATA[
public class B {
    void close() { }
}
    ]]></code>
  </test-code>
</test-data>

Always include a negative case. A rule that flags everything would still pass a test that only checks for violations.

Take quiz
What does expected-problems define?
The priority of the rule
How many files PMD scans
The maximum runtime of the test
How many violations the sample code must produce
Which base class do PMD rule tests extend?
JUnitRuleBase
PmdSurefire
PmdRuleTst

43. How do you use violationSuppressXPath in a ruleset?

violationSuppressXPath is a rule property that suppresses a violation when its XPath matches. The query is evaluated with the violating node as the context, so you usually look upwards to its ancestors.

A common use is letting test classes use System.out:

<rule ref="category/java/bestpractices.xml/SystemPrintln">
  <properties>
    <property name="violationSuppressXPath"
              value="./ancestor::ClassDeclaration[ends-with(@SimpleName, 'Test')]"/>
  </properties>
</rule>

This is better than scattering suppression comments when a whole pattern of code is acceptable. For simple text matches, violationSuppressRegex matches against the violation message instead.

Keep these queries short and documented, because a mistaken XPath can silently hide real violations.

Take quiz
What is violationSuppressXPath evaluated against?
The node where the violation was reported
The whole file text
The Git diff
Which property suppresses violations by matching the message?
messageIgnoreList
violationSuppressRegex
suppressByText

44. How do you troubleshoot PMD parse errors?

When PMD cannot parse a file it reports a processing error, skips the file and carries on. In PMD 7 the exit code is 5 if only recoverable errors occurred. Work through these causes:

  1. Language version too low. Records, sealed classes or text blocks fail if the version is older than the syntax. Set it with --use-version java-17 or the plugin's target version.
  2. Encoding mismatch. Set --encoding UTF-8 if the files use it.
  3. Not real source. Template or generated files with placeholders are not valid code, so exclude them.
  4. Old PMD. Newer syntax needs a newer PMD, so upgrade if the feature is listed in the release notes.
  5. Genuine bug. Reproduce the snippet in the Designer and report it.

The processing errors section of the XML or HTML report names the failing files. Fix those first, because a skipped file also skips all of its rule checks.

Take quiz
What is a common cause of a parse error on records?
Too many rules enabled
A language version lower than the syntax used
A missing Maven repository
Which option changes the file encoding PMD uses?
--encoding
--charm
--unicode-mode

45. How does PMD work with Salesforce Apex?

PMD is the standard static analysis engine for Apex, and Salesforce Code Analyzer bundles it. Apex rules sit in the same categories as Java rules and many target platform behavior such as governor limits and security.

Rule Category What it checks
AvoidSoqlInLoops Performance SOQL queries inside loops that risk governor limits
AvoidDmlStatementsInLoops Performance DML statements inside loops
ApexCRUDViolation Security Queries or DML without CRUD permission checks
ApexSharingViolations Security Classes missing a sharing declaration
ApexUnitTestClassShouldHaveAsserts Best Practices Tests without assertions

pmd check -d force-app -R category/apex/performance.xml,category/apex/security.xml -f text

Teams add the check to the CI pipeline of their Salesforce project so these problems are caught before deployment.

Take quiz
Which Apex rule targets governor-limit risk from queries inside loops?
AvoidSoqlInLoops
ApexDoc
ClassNamingConventions
FieldDeclarationsShouldBeAtStart
Which Salesforce tool bundles the PMD engine?
Salesforce Code Analyzer
Data Loader
Flow Builder

46. How does PMD fit alongside SonarQube?

They overlap but play different roles. SonarQube is a platform with its own rule engines, dashboards, quality gates and new-code tracking. PMD is a rule engine you run in the build, with rules you can write yourself.

Teams combine them in two ways. They run PMD in the build for its custom rules or Apex support, and import the XML report into SonarQube as external issues, for example through the sonar.java.pmd.reportPaths property of the Java analyzer. SonarQube then shows PMD findings next to its own and applies the quality gate.

Need Better fit
Custom house rules with XPath PMD
Apex or PL/SQL checks PMD
Quality gate on new code and history SonarQube
Fast feedback in a local build PMD

Take quiz
How can PMD results appear in SonarQube?
By replacing the SonarQube database
By importing the PMD XML report as external issues
By copying the PMD jar into SonarQube logs
Which tool provides quality gates and new-code tracking?
SonarQube
The PMD Designer
CPD

47. What is the difference between pmd:pmd and pmd:check in Maven?

Goal Purpose Fails the build?
pmd:pmd Runs PMD and writes the report, such as target/pmd.xml No
pmd:check Reads the results and fails according to failurePriority Yes
pmd:cpd Runs CPD and writes the duplication report No
pmd:cpd-check Fails the build if duplications are found Yes

pmd:check forks pmd:pmd first, so you do not run both. Use pmd:pmd alone when you only want a report, for example in mvn site through the reporting section.

Set printFailingErrors to true on check so the violations show in the console instead of only in the report file.

Take quiz
What does pmd:pmd alone do when violations exist?
Writes the report but does not fail the build
Deletes offending files
Always fails with exit code 4
Which goal is the CPD counterpart of pmd:check?
cpd:check
pmd:dup-fail
pmd:cpd-check

48. How does the PMD rule chain improve performance?

Without optimization, every Java rule walks the whole AST on its own. With hundreds of rules that means hundreds of traversals per file.

The rule chain avoids this. A rule declares the node types it cares about, for example method declarations. PMD walks the tree once and hands each node only to the rules subscribed to that type.

flowchart LR
A[AST] --> B["Single traversal"]
B --> C{Node type}
C -- MethodDeclaration --> D["Rules subscribed to methods"]
C -- CatchClause --> E["Rules subscribed to catch clauses"]

In PMD 7, Java rules extend AbstractJavaRulechainRule and pass their node types to super(...). XPath rules are optimized automatically when the query starts with a node name, such as //MethodDeclaration. So writing a specific XPath start is both clearer and faster than a generic one.

Take quiz
What does the rule chain optimize?
It compiles XPath to bytecode
It walks the AST once and dispatches nodes to subscribed rules
It stops all rules at the first violation
How does a rule benefit from the rule chain?
It declares the node types it wants to visit
It runs in a separate JVM
It scans only the first line of each file

49. How do you choose which PMD rules your team should enable?

Pick rules by the value they bring, not by how many there are. A practical process looks like this:

  1. Start from the quickstart ruleset as a baseline.
  2. Read each category and keep rules that match real problems in your codebase, usually error prone and best practices first.
  3. Run the candidate ruleset on the repository and count violations per rule. A rule with thousands of hits and no one willing to fix them is noise.
  4. Drop code style rules that your formatter or Checkstyle already covers.
  5. Agree on priorities with the team and gate the build on the top ones.
  6. Store the ruleset in version control and revisit it when upgrading PMD.

A short list that everyone trusts is more effective than a long one that everyone suppresses.

Take quiz
What is a good way to decide whether a rule is worth enabling?
Enable rules alphabetically
Enable it if its name sounds serious
Trial-run it and review the signal-to-noise ratio
Which category often overlaps with a formatter or Checkstyle?
Multithreading
Code Style
Security

50. Why does PMD flag a GodClass and how do you fix it?

A god class knows and does too much. PMD's GodClass rule in the design category uses three metrics and reports a class only when all three are bad together:

  • WMC (Weighted Method Count): the class is very complex, with a value of 47 or more.
  • ATFD (Access To Foreign Data): it uses data of other classes heavily, with more than 5 accesses.
  • TCC (Tight Class Cohesion): its methods share few fields, with a value below one third.

Such a class is hard to test and risky to change, because unrelated features live together.

To fix it, look at which groups of methods use which fields and split the class along those lines. Move methods to the class whose data they use, extract services for separate responsibilities, and keep each new class focused on one job. Do it in small steps backed by tests, and re-run PMD to confirm the metrics drop.

Take quiz
Which metric measures how much a class uses data from other classes?
TCC
ATFD
WMC
What is the typical fix for a GodClass?
Make all methods static
Add more methods to it
Split it into classes with single responsibilities
«
»

Comments & Discussions