HomeJava & J2EE Page 5 - The JSP Files (part 3): Black Light And White Rabbits
Paying The Piper - Java
This week, learn all about the different types of loops supportedby JSP, and also expand your knowledge of the various String objectmethods. Finally, take a quick tour of the JSP Response object inpreparation for learning how JSP handles form data.
You've already seen a few of the String object's capabilities in the first part of this tutorial. But as we progress further, you're going to need to know a little bit more to make full use of its power.
First, there's the indexOf() method, which is used to locate the first occurrence of a character or substring in a larger string. If you ran the following code snippet,
<%
// define variable
String storyName = "The Pied Piper Of Hamlin";
// find index
int i = storyName.indexOf("i");
// print index
out.println("The letter i first occurs at " + i + " in the string " +
storyName);
%>
this is what you would see:
The letter i first occurs at 5 in the string The Pied Piper Of Hamlin
Yes, the first character is treated as index 0, the
second as index 1, and so on. These programmers...
The opposite of this is the lastIndexOf() function, used to identify the last occurrence of a character or substring in a larger string. Take a look:
<%
// define variable
String storyName = "The Pied Piper Of Hamlin";
// find index
int i = storyName.lastIndexOf("Pi");
// print index
out.println("The string Pi last occurs at " + i + " in the string " +
storyName);
%>
And the output is
The string Pi last occurs at 9 in the string The Pied Piper Of Hamlin
In case the character or substring is not located,
the function will return an error code of -1.{mospagebreak title=Screaming Out Loud} Next, the trim() function comes in handy when you need to remove white space from the ends of a string.
<%
// define variable
String whatIWant = " gimme my space ";
// trim!
// returns "gimme my space"
whatIWant.trim();
%>
The toUpperCase() and toLowerCase() methods come in
handy to alter the case of a string.
<%
// define variable
String someString = "don't SCREam, help is oN the WAy!";
// uppercase - returns "DON'T SCREAM, HELP IS ON THE WAY!"
someString.toUpperCase();
// lowercase - returns "don't scream, help is on the way!"
someString.toLowerCase();
%>
The startsWith() and endsWith() functions are used to
verify whether a string starts or ends with a specified character or sequence of characters. The following example should illustrate this clearly.