Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Predicate.and(): combine conditions with logical AND

Combine two predicates into one reusable condition. The second predicate is evaluated only if the first returns `true`.

Version: Java SE 21

Syntax

default Predicate<T> and(Predicate<? super T> other)

Predicate.and() is a default method of java.util.function.Predicate<T>. The empty parentheses are shorthand in the name: the actual call first.and(other) takes one argument and returns a Predicate<T>, not a boolean. The parameter type Predicate<? super T> accepts a predicate for T or a supertype of T.

Calling and does not run either test. When you call test(value) on the result, first tests the value first. If it returns false, the second test is skipped. If it returns true, other tests the same value and determines the result. This follows the same order as first.test(value) && other.test(value), but and lets you keep the combined condition for reuse.

Calling first.and(null) throws NullPointerException at composition time. That differs from passing null to test, where the behavior depends on the predicates. An exception from either test that runs reaches the caller; if the first test throws, the second does not run.

Examples

import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        Predicate<String> nonNull = text -> text != null;
        Predicate<String> hasAtLeastThreeChars = text -> text.length() >= 3;
        Predicate<String> valid = nonNull.and(hasAtLeastThreeChars);

        System.out.println(valid.test(null));
        System.out.println(valid.test("hi"));
        System.out.println(valid.test("cat"));
    }
}

Result

false
false
true

For `null`, the first predicate returns `false`, so `length()` is never called. For `"hi"` and `"cat"`, the length check runs: `"hi"` is too short, and `"cat"` passes.

Related lessons

  • Java · Lesson 62 · Basic · Version: 2

Sources