HomeJava & J2EE Page 3 - The JSP Files (part 2): Attack Of The Killer Fortune Cookies
Do It Or Else... - Java
The second part of our introductory JSP tutorial discussesarithmetic, logical and comparison operators, together with simple examplesand illustrations. You'll also learn the basics of JSP's numerousconditional expressions, including the "if", "if-else" and "switch"statements, and find out a little more about the String object.
In addition to the "if" statement, JSP also offers the "if-else" statement, which allows you to execute different blocks of code depending on whether the expression is evaluated as true or false.
The structure of an "if-else" statement looks like this:
if (condition)
{
do this!
}
else
{
do this!
}
In this case, if the conditional expression evaluates as
false, all statements within the curly braces of the "else" block will be executed. Modifying the example above, we have
<%!
// declare temperature variable
int temp = 50;
%>
<%
// check temperature and display output
if (temp > 30)
{
out.println("Man, it's hot out there!");
}
else
{
out.println("Well, at least it isn't as hot as it could be!");
}
%>
In this case, if the first past of the construct fails
(temperature is *not* greater than 30), control is transferred to the second part - the "else" statement - and the code within the "else" block is executed instead. You can test both possibilities by adjusting the value of the "temp" variable, and viewing the resulting output in your browser.