The JSP Files (part 2): Attack Of The Killer Fortune Cookies

Conditional expressions, logical and comparsion operators, and a basket full of fortune cookies. What more could you ask for?

Overdrive

With a little bit of luck, our introductory article on JSP left you so excited that you spent the last few days eagerly practicing variable names and letting your friends know how much smarter you are than them. And this week, we’re going to help you cement your reputation still further, by giving you a crash course in JSP’s conditional statements and loops.

Make sure you’re strapped in tight - this is gonna be one hell of a ride!

Adding It All Up

You’ll remember how, in the first part of this tutorial, we used the + operator to add numbers and strings together. And just as you have the + operator for addition, JSP comes with a bunch of other arithmetic operators designed to simplify the task of performing mathematical operations.

The following example demonstrates the important arithmetic operators available in JSP:

<html>
<head>
</head>
<body>

<%!
// declare variables
int alpha = 25;
int beta = 5;
int sum, difference, product, quotient, remainder;
%>

<%
// perform operations
out.println("The sum of " + alpha + " and " + beta + " is " + (alpha + beta) + "<br>");
out.println("The difference of " + alpha + " and " + beta + " is " + (alpha - beta) + "<br>");
out.println("The product of " + alpha + " and " + beta + " is " + (alpha * beta) + "<br>");
out.println("The quotient after division of " + alpha + " and " + beta + " is " + (alpha / beta) + "<br>");
out.println("The remainder after division of " + alpha + " and " + beta + " is " + (alpha % beta) + "<br>");
%>


</body>
</html>

And here’s the output:

The sum of 25 and 5 is 30
The difference of 25 and 5 is 20
The product of 25 and 5 is 125
The quotient after division of 25 and 5 is 5
The remainder after division of 25 and 5 is 0

As with all other programming languages, division and multiplication take precedence over addition and subtraction, although parentheses can be used to give a particular operation greater precedence. For example,

<%
out.println(10 + 2 * 4);
%>

returns 18, while

<%
out.println((10 + 2) * 4);
%>

returns 48.

In addition to these operators, JSP comes with the very useful auto-increment [++] and auto-decrement [–] operators, which you’ll see a lot of in the next article. The auto-increment operator increments the value of the variable to which it is applied by 1, while the auto-decrement operator does the opposite. Here’s an example:

<%!
int x = 99;
%>

<%
// x = 99
out.println("Before increment, x = " + x + "<br>");
x++;
// x = 100
out.println("After increment, x = " + x);
%>

JSP also comes with a bunch of comparison operators, whose sole raison d’etre is to evaluate expressions and determine if they are true or false. The following table should make this clearer.

Assume x=4 and y=10

Operator What It Means Expression Result
== is equal to x == y False
!= is not equal to x != y True
> is greater than x > y False
< is less than x < y True
>= is greater than or equal to x >= y False
<= is less than or equal to x <= y True

Flavour Of The Month

And just as you can compare numbers, JSP also allows you to compare strings, with a couple of very useful String object methods.

First, the equals() method allows you to check whether the value of a particular string variable matches another. The following example should demonstrate this.

<%
// define variables
String myFavourite = "chocolate";
String yourFavourite = "strawberry";

// compare strings
if (myFavourite.equals(yourFavourite))
{
out.println("A match made in heaven!");
}
else
{
out.println("Naw - try again!");
}
%>

Try changing the values of the variables to match each other, and gasp in awe as the output changes.

In case the equals() method doesn’t appeal to you, JSP offers you a choice in the form of the compareTo() method, which returns a value indicating which of the two strings is greater. Take a look:

<%
// define variables
String alpha = "abcdef";
String beta = "zyxwvu";

// compare strings
out.println(alpha.compareTo(beta));
%>

In this case, if the value of the variable “beta” is greater than that of the variable “alpha”, the compareTo() method will return a negative integer; if it’s the other way around, the comparison will return a positive integer. And if the two strings are identical, the comparison will return 0.

Incidentally, the comparison is based on both the first character of the string, and the number of characters in the string. One string is considered “greater” than another if the numeric value of its first character is greater, or if its length is greater. In the example above, “z” has a greater numeric code than “a”, and so the comparison will return a negative integer. But don’t take our word for it - try it yourself and see!

Turning Up The Heat

Why do you need to know all this? Well, comparison operators come in very useful when building conditional expressions - and conditional expressions come in very useful when adding control routines to your code. Control routines check for the existence of certain conditions, and execute appropriate program code depending on what they find.

The first - and simplest - decision-making routine is the “if” statement, which looks like this:

if (condition)
{
	do this!
}

The “condition” here refers to a conditional expression, which evaluates to either true or false. For example,

if (hard drive crashes)
{
	get down on knees and pray for redemption
}

or, in JSP-lingo.

<%
if (hdd == 0)
{
	pray();
}
%>

If the conditional expression evaluates as true, all statements within the curly braces are executed. If the conditional expression evaluates as false, all statements within the curly braces will be ignored, and the lines of code following the “if” block will be executed.

Here’s a simple program that illustrates the basics of the “if” statement.

<%!
// declare temperature variable
int temp = 50;
%>

<%
// check temperature and display output
if (temp > 30)
{
	out.println("Man, it's hot out there!");
}
%>

In this case, a variable named “temp” has been defined, and initialized to the value 50. Next, an “if” statement has been used to check the value of the “temp” variable and display a message if it’s over 30. Note our usage of the greater-than (>) conditional operator in the conditional expression.

An important point to note - and one which many novice programmers fall foul of - is the difference between the assignment operator [=] and the equality operator [==]. The former is used to assign a value to a variable, while the latter is used to test for equality in a conditional expression.

So

a = 47;

assigns the value 47 to the variable a, while

a == 47

tests whether the value of a is equal to 47.

Do It Or Else…

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.

The “if-else” construct certainly offers a smidgen more flexibility than the basic “if” construct, but still limits you to only two possible courses of action. If your script needs to be capable of handling more than two possibilities, you should reach for the “if-else if-else” construct, which is a happy combination of the two constructs you’ve just been reading about.

if (first condition is true)
{
	do this!
}
else if (second condition is true)
{
	do this!
}
else if (third condition is true)
{
	do this!
}

	... and so on ...

else
{
	do this!
}

Take a look at it in action:

<%!
// declare temperature variable
int temp = 20;
%>

<%
// check temperature and display output
// what happens if temp is less than 25 degrees
if (temp >= 25)
{
	out.println("Man, it's hot out there!");
}
// what happens if temp is between 25 and 10 degrees
else if (temp < 25 && temp > 10)
{
	out.println("Great weather, huh?!");
}
// what happens if temp is less than ten degrees
else if (temp <= 10)
{
	out.println("Man, it's freezing out there!");
}
// this is redundant, included for illustrative purposes
else
{
	out.println("Huh? Somebody screwed up out there!");
}
%>

In this case, depending on the value of the “temp” variable, the appropriate code branch is executed, thereby making it possible to write scripts which allow for multiple possibilities.

One important point to be noted here: control is transferred to successive “if” branches only if the preceding condition(s) turn out to be false. Or, in English, once a specific conditional expression is satisfied, all subsequent conditional expressions are ignored.

Here’s another example, this one using the day of the week to decide which fortune cookie to display. Alter the “day” variable to see a different cookie each time.

<%!
String day = "Monday";
String fortune;
%>
<%
// check day and set fortune
if (day.equals("Monday"))
{
	fortune = "Adam met Eve and turned over a new leaf.";
}
else if (day.equals("Tuesday"))
{
	fortune = "Always go to other people's funerals, otherwise they won't come to yours.";
}
else if (day.equals("Wednesday"))
{
	fortune = "An unbreakable toy is useful for breaking other toys.";
}
else if (day.equals("Thursday"))
{
	fortune = "Be alert - the world needs more lerts.";
}
else if (day.equals("Friday"))
{
	fortune = "Crime doesn't pay, but the hours are good.";
}
else
{
	fortune = "Sorry, closed on the weekend";
}
// print output
out.println(fortune);
%>

Lunch In Milan

If you take a close look at the last-but-one example above, you’ll notice that the conditional expression

(temp < 25 && temp > 10)

is slightly different from the ones you’ve been used to thus far. This is because JSP also allows you to combine multiple conditions into a single expression, with the help of an animal called a “logical operator”.

The following table should make this clearer.

Assume $delta = 12, $gamma = 12 and $omega = 9

Operator What It Means Example Translation Evaluates To
&& AND $delta == $gamma && $delta > $omega delta equals gamma AND delta is greater than omega True
&& AND $delta == $gamma && $delta < $omega delta equals gamma AND delta is less than omega False
|| OR $delta == $gamma || $delta < $omega delta equals gamma OR delta is less than omega True
|| OR $delta > $gamma || $delta < $omega delta is greater than gamma OR delta is less than omega False
! NOT !$delta delta doesn’t exist False

So, instead of something as ugly as this

<%
if (day == "Thursday")
{
	if (time == "12")
	{
		if (place == "Italy")
		{
			lunch = "pasta";
		}
	}
}

%>

you could have something as elegant as this.

<%
if (day == "Thursday" && time == "12" && place == "Italy")
{
   lunch = "pasta";
}
%>

Switching Things Around

Finally, JSP rounds out its conditional expressions with the “switch” statement, which offers an alternative method of transferring control from one program block to another. Here’s what it looks like:

switch (decision-variable)
{
	case first_condition_is true:
		do this!

	case second_condition_is true:
		do this!

	case third_condition_is true:
		do this!

	... and so on...

	default:
		do this by default!
}

The “switch” statement can best be demonstrated by rewriting the previous example using “switch” instead of “if-else if-else”.

<%!
int dayOfWeek = 3;
String fortune;
%>
<%
// the decision variable here is the day chosen by the user
switch (dayOfWeek)
{

	// first case
    case 1:
        fortune = "Adam met Eve and turned over a new leaf.";
        break;

	// second case
    case 2:
        fortune = "Always go to other people's funerals, otherwise they won't come to yours.";
        break;

    case 3:
        fortune = "An unbreakable toy is useful for breaking other toys.";
        break;

    case 4:
        fortune = "Be alert - the world needs more lerts.";
        break;

    case 5:
        fortune = "Crime doesn't pay, but the hours are good.";
        break;

	// if none of them match...
    default:
        fortune = "Sorry, closed on the weekend";
        break;

}
// print output
out.println(fortune);
%>

The first thing you’ll notice is that the “day” variable from the previous example has been converted to a numeric “dayOfWeek” variable - this is because the “switch” construct only works when the decision variable is an integer.

There are also a couple of important keywords here: the “break” keyword is used to break out of the “switch” statement block and move immediately to the lines following it, while the “default” keyword is used to execute a default set of statements when the variable passed to “switch” does not satisfy any of the conditions listed within the block.

And that’s about it. You now know enough about JSP’s conditional statements to begin writing simple programs - so go practice! And come back for the next issue, when we’ll be talking about loops, demonstrating other String object methods, and even taking a quick look at the new Response object.

Note: All examples in this article have been tested on Linux/i586 with Tomcat 3.2 and JServ 1.1. Examples are illustrative only, and are not meant for a production environment. YMMV!

This article was first published on 15 Feb 2001.