The JSP Files (part 4): The Red Pill - What's For Dessert?
(Page 6 of 9 )
Thus far, the variables you've used contain only a single value - for example,
int i = 0
However, array variables are a different kettle of fish altogether. An array variable can best be thought of as a "container" variable, which can contain one or more values. For example,
String[] desserts = {"chocolate mousse", "tiramisu", "apple pie",
"chocolate fudge cake"};
Here, "desserts" is an array variable, which contains the values "chocolate mousse", "tiramisu", "apple pie", and "chocolate fudge cake".
Array variables are particularly useful for grouping related values together - names, dates, phone numbers of ex-girlfriends et al.
The various elements of the array are accessed via an index number, with the first element starting at zero. So, to access the element
"chocolate mousse"
you would use the notation
desserts[0]
while
"chocolate fudge cake"
would be
desserts[3]
- essentially, the array variable name followed by the index number enclosed within square braces. Geeks refer to this as "zero-based indexing".
Defining an array variable in JSP is somewhat convoluted, as compared to languages like PHP and Perl; you need to first declare the variable and its type, and then actually create the array.
<%
// declare type of arrayString[] desserts;// initialize array// the number indicates the number of elements the array will holddesserts = new String[4];// assign values to array elementsdesserts[0] = "chocolate mousse";desserts[1] = "tiramisu";desserts[2] = "apple pie";desserts[3] = "chocolate fudge cake";%>
Or you can use the simpler version:
<%
String[] desserts = {"chocolate mousse", "tiramisu", "apple pie","chocolate fudge cake"};%>
Note that if you try to add more elements than the number specified when creating the array, JSP will barf with a series of strange error message.
Next: A Chocolate Addiction >>
More Java Articles
More By Vikram Vaswani, (c) Melonfire