HomeJava & J2EE Page 6 - The JSP Files (part 3): Black Light And White Rabbits
You Say Seven, I Say 7 - 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.
// at this stage, someString is still treated as a string
out.println(someString + " plus " + aRandomNumber + " equals " +
(someString+aRandomNumber) + "<p>");
// now convert someString to a number
int someNumber = Integer.parseInt(someString);
// at this stage, someString has been converted to a number, stored in
someNumber
out.println(someNumber + " plus " + aRandomNumber + " equals " +
(someNumber+aRandomNumber));
%>
And here's the output.
97 plus 3 equals 973 97 plus 3 equals 100 [output]
If you'd prefer to do things the other way around, the next example bears careful consideration.
<%
// define variables
int someNumber = 97;
int aRandomNumber = 3;
// at this stage, someNumber is still treated as a number
out.println(someNumber + " plus " + aRandomNumber + " equals " +
(someNumber+aRandomNumber) + "<p>");
// now convert someNumber to a string
String someString = Integer.toString(someNumber);
// at this stage, someNumber has been converted to a string, stored in
someString
out.println(someString + " plus " + aRandomNumber + " equals " +
(someString+aRandomNumber));
%>
And here's the output.
97 plus 3 equals 100
97 plus 3 equals 973
The upshot? parseInt() and toString() are your best
friends when converting between string and numeric data types in JSP.