Java
  Home arrow Java arrow Page 4 - Making Decisions, Decisions
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Making Decisions, Decisions
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 3
    2005-05-05

    Table of Contents:
  • Making Decisions, Decisions
  • Creating Multidimensional Arrays
  • Comparing Data Values
  • Making Decisions
  • Understanding Variable Scope in Statement Blocks
  • How It Works
  • Understanding the Conditional Operator
  • Trying It Out: Working with the choose...when...when Construct
  • Understanding Loops and Iteration
  • Introducing Branching Statements
  • Trying It Out: Using Arrays

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

    More Java Articles
    More By Apress Publishing


     

    Buy this book now. This article was excerpted from Beginning JSP 2: From Novice to Professional by Peter den Haan et. al. (Apress, 2004; ISBN: 1590593391). Check it out at your favorite bookstore. Buy this book now.

    JAVA ARTICLES

    - 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 ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek