Code Logo

Handle Nullable Values Safely

Published at13 Jan 2026
Medium 33 views
Like7

You are given one string value that might be usable text, or it might be missing or blank. Your job is to return a safe fallback when the value should not be used directly.

Based on the Java tests, the rule is: if the input is null, an empty string, or only whitespace, return "Guest". Otherwise return the original string unchanged.

For example, "John" should stay "John". But null, "", and " " should all become "Guest".

So this problem is really about handling nullable and blank string input safely, using a default name when the original value is not useful.

Example Input & Output

Example 1
Input
value = "John"
Output
"John"
Explanation

A non-empty name should be returned unchanged.

Example 2
Input
value = null
Output
"Guest"
Explanation

A null value should fall back to the default guest name.

Example 3
Input
value = " "
Output
"Guest"
Explanation

Whitespace-only text should also be treated as missing input.

Algorithm Flow

Recommendation Algorithm Flow for Handle Nullable Values Safely
Recommendation Algorithm Flow for Handle Nullable Values Safely

Solution Approach

This Java exercise is really about safe null handling, and the template strongly hints at using Optional. The important part is not just checking for null. The tests also show that an empty string and a whitespace-only string should be treated as missing input too.

A clean approach is to start with Optional.ofNullable(value). That gives us an Optional that is empty when the input is null and contains the string otherwise. Then we can transform the present value before deciding whether it should still count as usable text.

One practical pattern is:

return Optional.ofNullable(value).map(String::trim).filter(s -> !s.isEmpty()).orElse("Guest");

Here is what each step does:

map(String::trim) removes leading and trailing spaces, so a value like " " becomes an empty string.

filter(s -> !s.isEmpty()) keeps only strings that still contain real content after trimming.

orElse("Guest") supplies the default when the optional is empty because the original value was null or became empty after trimming.

This solution is compact, expressive, and matches the exact behavior required by the tests. It also keeps the null-handling logic in one readable chain instead of scattering manual checks across several if statements.

Best Answers

java - Approach 1
import java.util.Optional;

class Solution {
    public String processValue(String value) {
        Optional<String> opt = Optional.ofNullable(value);
        return opt.filter(v -> !v.isEmpty()).orElse("Guest");
    }
}