Java Platform, Enterprise Edition (Java EE) 8 The Java EE Tutorial

## Validating Null and Empty Strings

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all.

An empty string is represented as `""`. It is a character sequence of zero characters. A null string is represented by `null`. It can be described as the absence of a string instance.

Managed bean elements represented as a JavaServer Faces text component such as `inputText` are initialized with the value of the empty string by the JavaServer Faces implementation. Validating these strings can be an issue when user input for such fields is not required. Consider the following example, in which the string `testString` is a bean variable that will be set using input entered by the user. In this case, the user input for the field is not required.

    if (testString==null) {
        doSomething();
    } else {
        doAnotherThing();
    }

By default, the `doAnotherThing` method is called even when the user enters no data, because the `testString` element has been initialized with the value of an empty string.

In order for the Bean Validation model to work as intended, you must set the context parameter `javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL` to `true` in the web deployment descriptor file, `web.xml`:

    <context-param>
        <param-name>
            javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL
        </param-name>
        <param-value>true</param-value>
    </context-param>

This parameter enables the JavaServer Faces implementation to treat empty strings as null.

Suppose, on the other hand, that you have a `@NotNull` constraint on an element, meaning that input is required. In this case, an empty string will pass this validation constraint. However, if you set the context parameter `javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL` to `true`, the value of the managed bean attribute is passed to the Bean Validation runtime as a null value, causing the `@NotNull` constraint to fail.

Copyright © 2017, Oracle and/or its affiliates. All rights reserved.