Skip to content

[java] getConstValue() returns null for constant expressions referencing final local variables #7060

Closed

Description

@aoto-tech

Affects PMD Version:

7.28.0-SNAPSHOT. Reproduced against the current main constant-folding implementation at 97c5369cf9b1b954ffd3a31191d82b9efaa95193.

Description:

ASTExpression#getConstValue() returns null for a constant expression referencing a final local variable, although PMD successfully computes its value.

While working on #7059, which addresses #7015, I added a check for default-initialized byte arrays with a positive constant length. The implementation uses getConstFoldingResult().getValue() to obtain the array length.

During review, it was suggested that getConstValue() would be sufficient. I tried that change, but a regression test using final int size = 8; and new byte[size * 2] stopped reporting the expected violation. Investigating the difference showed that PMD evaluates size * 2 to 16, but classifies it as not being a compile-time constant.

Tracing this classification led to #5595, which distinguishes static final fields from final local variables. I am reporting this separately because it concerns the shared Java constant-folding API. #7059 currently retains getConstFoldingResult().getValue().

Exception Stacktrace:

None; the API returns an unexpected result without throwing an exception.

Code Sample demonstrating the issue:

class Example {
    void example() {
        final int size = 8;
        byte[] array = new byte[size * 2];
    }
}

For the length expression size * 2:

getConstFoldingResult().getValue()              = 16
getConstFoldingResult().isCompileTimeConstant() = false
getConstValue()                                = null

Expected behavior:

The expression should be classified as a compile-time constant, and getConstValue() should return 16.

JLS §4.12.4 defines a constant variable as a final variable of primitive type or type String, initialized with a constant expression; it does not require static. JLS §15.29 permits simple names referring to constant variables in constant expressions.

As a compiler control, this compiles successfully with javac 21. The resulting switch bytecode contains the key 16:

class JavacConstantControl {
    static int check(int input) {
        final int size = 8;
        switch (input) {
        case size * 2:
            return 1;
        default:
            return 0;
        }
    }
}

Steps to reproduce:

In a built PMD checkout, run the following probe with pmd-java/target/classes, pmd-java/target/test-classes, and its test dependencies on the classpath. It uses PMD's existing JavaParsingHelper.DEFAULT to parse and process the source.

import net.sourceforge.pmd.lang.java.JavaParsingHelper;
import net.sourceforge.pmd.lang.java.ast.ASTArrayDimExpr;
import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;

public class ConstantProbe {
    public static void main(String[] args) {
        String[] sources = {
            "class X { void f() { byte[] a = new byte[8 * 2]; } }",
            "class X { void f() { final int size = 8; byte[] a = new byte[size * 2]; } }",
            "class X { static final int size = 8; void f() { byte[] a = new byte[size * 2]; } }",
            "class X { void f() { int size = 8; byte[] a = new byte[size * 2]; } }"
        };
        String[] labels = {"literal", "final local", "static final field", "non-final local"};
        for (int i = 0; i < sources.length; i++) {
            ASTCompilationUnit root = JavaParsingHelper.DEFAULT.parse(sources[i]);
            ASTExpression expr = root.descendants(ASTArrayDimExpr.class).first().getLengthExpression();
            System.out.printf("%s: folded=%s, isCompileTimeConstant=%s, getConstValue=%s%n",
                labels[i], expr.getConstFoldingResult().getValue(),
                expr.isCompileTimeConstant(), expr.getConstValue());
        }
    }
}

For example, after saving this as ConstantProbe.java in the repository root, the following PowerShell commands compile and run it against the built module:

.\mvnw.cmd -B -pl pmd-java dependency:build-classpath "-Dmdep.outputFile=target/constant-probe-classpath.txt" "-DincludeScope=test"
$probeClasspath = "pmd-java/target/classes;pmd-java/target/test-classes;" + (Get-Content pmd-java/target/constant-probe-classpath.txt -Raw).Trim()
javac -proc:none -cp $probeClasspath ConstantProbe.java
java -cp ".;$probeClasspath" ConstantProbe

Observed output:

literal: folded=16, isCompileTimeConstant=true, getConstValue=16
final local: folded=16, isCompileTimeConstant=false, getConstValue=null
static final field: folded=16, isCompileTimeConstant=true, getConstValue=16
non-final local: folded=null, isCompileTimeConstant=false, getConstValue=null

Running PMD through: Other — direct Java AST API probe using the built pmd-java module and its test helper, on Windows with JDK 21.

Investigation:

In ConstantFolder.visit(ASTVariableAccess, ...), the initializer's value is resolved, but the result is classified as a compile-time constant only when the variable is a static field:

boolean isCompileTimeConstant = symbol instanceof JFieldSymbol
    && ((JFieldSymbol) symbol).isStatic();

The distinction described in #5595 appears inconsistent with the JLS definition above. The existing ConstValuesKotlinTest case named Test non CT constants are still resolved also expects an expression involving final local and non-static final variables to be classified as non-constant.

Proposed fix:

Update the variable-reference classification to follow the JLS definition: the variable must be final, have primitive or String type, and be initialized at its declaration with a constant expression. Qualifying final local variables and non-static final fields should be included. Removing isStatic() alone is insufficient; the variable's type and the initializer's compile-time constant status also need to be checked.

Update the existing test expectations and add coverage for qualifying variables, along with negative cases such as non-final variables, boxed types, and variables initialized by method calls. The fix should preserve the distinction between having a foldable value and being a JLS constant expression.

This would allow getConstValue() to return 16 for the example above. The array-length check in #7059 could then use that API for this case.

Activity

  1. added
    a:bug
    on Sep 11, 2026
  2. aoto-tech commented on Sep 11, 2026

    @aoto-tech
    ContributorAuthor

    another bugs test stopping now...

  3. added this to the 7.29.0 milestone on Sep 27, 2026
  4. added
    in:type-resolution
    on Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:bugin:type-resolution

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions