Home > Articles > Programming > Java

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book

2.5 Type Coercion

The EL defines a comprehensive set of coercion rules for various data types. Those rules are summarized in Table 2.3.

Table 2.3 JSTL Type Coercion11

convert to —>

Boolean

Character

Number

String

Boolean

———

ERROR

ERROR

x.toString()

Character

ERROR

———

(short)x

x.toString()

Number

ERROR

(char)x

———

x.toString()

String
(not empty)

Boolean.
valueOf(x)

x.charAt(0)

N.valueOf(x)

———

Other

ERROR

ERROR

ERROR

x.toString()

null

Boolean.false

(char)0

0

""

""

Boolean.false

(char)0

0

""


In the preceding table, types in the left column are converted into the types specified in the table's header. For example, if you specify an action attribute's value as a string and that attribute's type is Character, the EL will convert that string to the first character in the string by invoking the method x.charAt(0), where x represents the string. Likewise, strings are coerced to Boolean values with the static Boolean.valueOf(x), where x represents the string.

Table 2.3 also shows how null values and empty strings are converted into booleans, characters, numbers, and strings. JSTL actions typically avoid throwing exceptions because the coercions shown in Table 2.3 are applied to their attribute values before they receive them.

If you specify a null value or an empty string in an expression, the EL's coercion rules ensure that sensible default values are used instead; for example:

<c:out value='${count + param.increment}'/>

In the preceding code fragment, the expression specified for the value attribute coerces a string (a request parameter value named increment) to an integer which is added to the count scoped variable and sent to the current JspWriter by the <c:out> action.

If the increment request parameter does not exist, param.increment resolves to null. If it exists, but no value was specified for it—perhaps it represents an HTML input element in a form that was left blank—it resolves to an empty string. Either way, as you can see from Table 2.3, the EL coerces the string value of param.increment to 0, and the expression ${count + param.increment} evaluates to the value of the count scoped variable.

In general, JSTL actions avoid throwing exceptions, instead favoring sensible default values like 0 for null and empty strings.

Another thing you don't have to worry about is throwing a null pointer exception if you try to access an identifier that is null; for example, the expression ${userProfile.address.city} resolves to null if userProfile, address or city is null because the EL coerces that value into one of the appropriate values in Table 2.3.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus