mercredi 21 mars 2018

Strange if-else conditional behaviour

I have a simple static method as shown below.

/**
 * Get a text or its default.
 * <p>
 * Optionally you can treat a text containing the null literal string as a null text reference
 * by setting removeNullLiterals to true.
 * For example the text "null" will be considered as empty if removeNullLiterals is set to true.
 *
 * @param text               The text to get
 * @param defaultText        The default text that would be returned if text is null.
 * @param removeNullLiterals Remove null literals from text
 * @return
 */
public static String getText(String text, String defaultText, boolean removeNullLiterals) {
    String finalText = "";

    if (text != null) {
        finalText = text.trim();
    }

    if (removeNullLiterals) {
        finalText = finalText.replace("null", "");
    }

    if (finalText.isEmpty()) {
        return defaultText;
    } else {
        return finalText;
    }
}

I'm seeing a very weird behaviour where even if finalText.isEmpty() evaluates to true, the else block gets executed. Can anyone help me out?

Aucun commentaire:

Enregistrer un commentaire