O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A String index is coerced to an int for arrays and Lists

The EL for accessing an array is the same as the EL for accessing a List.

Remember folks, this is NOT Java. In EL, the [ ] operator is NOT the array access operator. No, it’s just called the [ ] operator. (We swear, look it up in the spec—it has no name! Just the symbol [ ]. Like Prince, kind of.) If it DID have a name, it would be the array/List/Map/bean Property access operator.

In a Servlet

java.util.ArrayList favoriteFood = new java.util.ArrayList();
favoriteFood.add("chai ice cream");
favoriteFood.add("fajitas");
favoriteFood.add("thai pizza");
favoriteFood.add("anything in dark chocolate");
request.setAttribute("favoriteFood", favoriteFood);

In a JSP

image with no caption
image with no caption
image with no caption

If the thing to the left of the bracket is an array or a List, and the index is a String literal, the index is coerced to an int.

This would NOT work: ${favoriteFood["one"]}

Because “one” can’t be turned into an int. You’ll get an error if the index can’t be coerced.

image with no caption
image with no caption

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required