Skip to content

[java] Casts to boolean and boolean equality are not folded as constant expressions #7313

Closed

Description

@saryn17

Affects PMD Version: 7.29.0 (also 7.30.0-SNAPSHOT at 4a1d37d)

Description:

getConstValue() returns null and isCompileTimeConstant() returns false for (boolean) true, ON == true and ON != false, where ON is a static final boolean set to true. JLS 15.29 allows casts to primitive types and the equality operators == and != in constant expressions. ConstantFolder folds a cast only to a numeric type or String, and == and != only for numeric and char operands:

if (t.isNumeric()) {
res = numericCoercion(castValue.getValue(), t);
} else if (TypeTestUtil.isExactlyA(String.class, node.getCastType())) {
res = stringCoercion(castValue.getValue());
} else {
return ConstResult.NO_CONST_VALUE;
}

private static @Nullable Boolean eqResult(Object left, Object right) {
if (isConvertibleToNumber(left) && isConvertibleToNumber(right)) {
Pair<Object, Object> promoted = binaryNumericPromotion(left, right);
return promoted.getLeft().equals(promoted.getRight()); // fixme Double.NaN
} else {
return null; // not a constant expr on reference types
}
}

Since #7218, LambdaMirrorImpl uses getConstValue() of a loop condition to decide whether a block lambda body can complete normally. On main, the three lambdas below are not value-compatible, and PMD selects submit(Runnable) where javac selects submit(Callable). PMD 7.29.0 also selects submit(Runnable) for them, because of #7144.

Found while working on #7136.

Code Sample demonstrating the issue:

import java.util.concurrent.ExecutorService;

public class Submit {
    static final boolean ON = true;

    void t(ExecutorService pool) {
        pool.submit(() -> { while ((boolean) true) { } });
        pool.submit(() -> { while (ON == true) { } });
        pool.submit(() -> { while (ON != false) { } });
    }
}

Steps to reproduce:

  1. javac Submit.java, also with --release 8, then javap -c -p Submit. The three calls in Submit.t are submit:(Ljava/util/concurrent/Callable;).
  2. Run PMD on the file with the XPath rule //WhileStatement/*[1][@CompileTimeConstant = false()]. It reports lines 7, 8 and 9.
  3. The XPath rule //MethodCall[pmd-java:matchesSig("java.util.concurrent.ExecutorService#submit(java.lang.Runnable)")] reports lines 7, 8 and 9 too.

Running PMD through: Other (PmdAnalysis API)

Activity

  1. added
    in:type-resolution
    on Nov 14, 2026
  2. added this to the 7.30.0 milestone on Nov 14, 2026
  3. added a commit that references this issue on Nov 14, 2026
    f7b7388
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

    in:type-resolution

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions