Skip to main content
PreparationZone Logo
PrepZone

Coding Kata: orElse vs orElseGet

Fix the expensive-default bug — the Optional trap paid courses drill repeatedly.

Pass checkpoint below

The trap

Java
public class Example {
    public static void main(String[] args) {
        Optional<User> found = findByEmail(email);

            // BUG: loadDefaultUser() runs even when found is present
            User user = found.orElse(loadDefaultUser());

            // FIX: supplier runs only when empty
            User user = found.orElseGet(this::loadDefaultUser);
    }
}

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Test yourself

Answer these before moving on — recall is what makes it stick.