Home arrow Java arrow Page 4 - Making Decisions, Decisions
JAVA

Making Decisions, Decisions


Most JavaServer Pages will need to perform one of several actions according to some condition. This is managed in the code through control statements, which come in three flavors: conditional, iterative, and branching. This article will explain the syntax Java provides for these statements, how and when to use arrays, and more. It is taken from chapter five of Beginning JSP 2 From Novice to Professional, written by Peter den Haan et. al. (Apress, 2004; ISBN: 1590593391).

Author Info:
By: Apress Publishing
Rating: 4 stars4 stars4 stars4 stars4 stars / 11
May 05, 2005
TABLE OF CONTENTS:
  1. · Making Decisions, Decisions
  2. · Creating Multidimensional Arrays
  3. · Comparing Data Values
  4. · Making Decisions
  5. · Understanding Variable Scope in Statement Blocks
  6. · How It Works
  7. · Understanding the Conditional Operator
  8. · Trying It Out: Working with the choose...when...when Construct
  9. · Understanding Loops and Iteration
  10. · Introducing Branching Statements
  11. · Trying It Out: Using Arrays

print this article
SEARCH DEVARTICLES

Making Decisions, Decisions - Making Decisions
(Page 4 of 11 )

The things youíve learned thus faróhow to compare values and how to use Boolean logic to create more complex expressions (or ďdecisionsĒ)óare the basic tools for controlling the flow of a program. There are many situations where such expressions are useful, and youíll find few programming problems that donít require them at one point or another.

Most often, such expressions are combined with control statements, which are statements that control the flow of program execution. There are three basic kinds of control statement:

  • Conditional statements: Here the statement is evaluated, and the code block executed depends upon the value returned by the statement.

  • Iterative statements: The same block of code is executed again and again (iterated).

  • Branching statements: The statement moves execution to a particular point within the code.

The following sections examine each of these in turn.

Introducing Conditional Statements

While writing programs you continually come across situations where you need to evaluate a condition and proceed according to the result. Java has two main types of conditional statement:

  • The if statement (and its variations)

  • The switch statement

The main difference between the two is that an if statement requires an expression that results in either true or false, and switch allows one of many blocks of code to be executed, depending on the outcome of the expression.

Using the if Statement

The following is an example of an if statement:

if ( itemQuantity > 0 )
{
  System.out.println("The Quantity is greater than 0");
  System.out.println("No. of items : " + itemQuantity);
}

In English, what this basically means is this: If the value of itemQuantity is greater than zero, then display the following:

The Quantity is greater than 0

No. of items :

followed by the value of itemQuantity.

Note that this if statement follows the general form of if statements:

if (expression)
{
  Statement Block
}

You may recognize the correspondence with the JSTL <if> tag that youíve already used in earlier chaptersí examples:

<c:if test="expression">
 
Statement Block
</c:if>

The expression is evaluated first, and if it evaluates to true, the statement block (which consists of one or more Java statements) is executed. In a JSP page the statement block could consist of other tags (HTML or JSP tags) or even plain text.

Be aware that here you see the syntax using a statement block, as denoted by enclosing curly braces. Java doesnít require that statement blocks be used, and if only a single line is to be executed if the expression evaluates to true, the braces can be omitted, as follows:

if (itemQuantity > 0)
  System.out.println("The Quantity is greater than 0");

This practice is frowned upon because mistakes can be made unwittingly. For example, the author doesnít always maintain the code (they may have left the company, or it may not be their job). So, if the previous code were given to somebody else, that person may want to exit the program if the quantity is greater than zero:

if (itemQuantity > 0)
  System.out.println("The Quantity is greater than 0");
  System.exit(1);                                           

However, the previous code will actually exit the program no matter what value is stored in itemQuantity. Braces are much safer:

if (itemQuantity > 0) {
  System.out.println("The Quantity is greater than 0");
 
System.exit(1);
}

This applies to all other Java constructs, as well as if, with the exception of do...while loops. Note that this doesnít apply to the JSTL. The JSTLís <if> tag, for instance, always requires a closing tag:

<c:if test="expression">Statement Block</c:if>

This requirement is the same as numerous HTML tags, which also require a closing tag, such as the table (<table></table>), heading (<h1></h1>), and font (<font></font>) tags. Although most Web browsers are lenient about this rule, JSP tags arenít: You must supply the closing tag.

Understanding the if...else Statement

Youíll often find the if statement used in conjunction with else, which allows you to specify code that should be executed when the expression doesnít evaluate to true:

if (expression)
{
  Statement Block 1
}
else
{
  Statement Block 2
}

As before, the expression is evaluated first and if it results in true, then the first statement block is executed. If the expression isnít true, then the second statement block is executed instead.

The following is an example of the if...else statement that evaluates whether you have four or more items to ship. If this is the case, the customer incurs no shipping costs. If you have fewer than four items, you find the shipping cost by multiplying the number of items to ship by the cost of shipping an item:

if (itemQuantity >= 4)
{
 
shippingCost = 0.0;
}
else
{
  shippingCost = basicShippingCost * itemQuantity;
}

So for orders of four or more items, the shippingCost variable will be set to zero. For fewer items than that, the cost will depend on the value of basicShippingCost and the total number of items ordered.

Understanding the if...else if Statement

Many situations are a little more involved, and you donít simply want to execute one of two options depending on whether a single condition is true or false. For instance, the online store might offer several levels of discount to customers, depending on how much they spend. There might be no discount for purchases less than $100, but between $100 and $500 the customer gets 10 percent off and greater than $500 they get 15 percent off.

You can quite easily code such behavior in Java by simply placing further if statements for each else keyword, as follows:

if (expression1)
{
  Statement Block 1
}
else if (expression2)
{
Statement Block 2
}
.
.
More else if Blocks !
.
.

Here, the only statement block that will be evaluated will be the first one where the associated expression evaluates to true (and all previous expressions have come up as false).

Consider the following code snippet, where you test the value of the integer variable n against several possible values. You first check to see if it is less than zero (negative), then check if itís equal to zero, and finally check if itís greater than zero (positive):

int n = 10;
if (n < 0 )
{
  System.out.println("n is negative");
}
else if (n == 0)
{
  System.out.println("n is zero");
}
else if (n > 0)
{
  System.out.println("n is positive");
}

Because n is set to 10 at the start of the code snippet, the output will be that n is positive. This is a simple example, but it illustrates the flow of execution well enough for these purposes.


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials