Home arrow Java arrow 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
(Page 1 of 11 )

ONLY THE MOST simplistic JavaServer Pages (JSP) page can get away without needing to perform one of several actions according to some condition. These conditions control the flow that your code follows as it executes, and they do so through control statements. Such statements evaluate an expression to determine the condition and direct the flow of execution accordingly.

The kinds of program flow control you’ll meet in this chapter are as follows:

  • Conditional statements: Evaluating a condition in the program and executing code depending on whether the condition evaluates to “true” or “false”

  • Iterative statements: Repeating (looping through) sections of code

  • Branching statements: Transferring execution of the program to a particular section of the code

This chapter discusses the syntax Java provides for all of these and also presents the flow control constructs of the Java Standard Tag Library (JSTL). You’ll also look at how Java lets you store and manipulate groups of variables of the same type using arrays. In short, the chapter covers the following:

  • How to use arrays and when to use them

  • How to compare values

  • How to easily incorporate logic in your code

  • The if,if...else, and switch statements

  • The while,do...while, and for loops
  • The break, continue, and return statements

In each case you’ll learn about the standard Java techniques, followed by a JSTL example if appropriate.

Introducing Arrays

Before learning about the important control statements, you’ll look at how you can group variables of the same data type into arrays. This will allow you to see how combining control statements with arrays can make your code simpler and easier to manage.

So what exactly is an array? Well, imagine that your program needed a thousand String variables, each one storing a different value as follows:

String name1 = "Richmal";
String name2 = "Tobian";
String name3 = "Rozzle";
.
.
.
String name1000 = "Joey";

Remembering and managing them all would be troublesome to say the least! Also, there would more than likely be many situations where you’d need to perform the same action on every variable. Even something as simple as printing a list of all the names would require you to type the same code for each String:

myPrintMethod(name1);
myPrintMethod(name2);
myPrintMethod(name3);
.
.
.
myPrintMethod(name1000);

To address such situations, array variables allow many instances of a single data type to be grouped together, which greatly simplifies using groups of variables, as you’ll see.

Arrays can contain groups of any of the basic primitive data types, such as int, String, char, and float, and they can also handle other data types such as user-defined objects. You can even have arrays of arrays (of arrays...)! Note, however, that you can’t have an array of mixed data types—every element of an array must be of the same type.

Understanding Array Elements and Index Values

Each variable in an array is known as an element. To be able to reference a particular element within the array, you use its index, which indicates the element’s offset from the start of the array. The fact that array indices start at zero is a source of many programming errors, and you always need to remember that the first element has an index of zero (not one), the second has an index of one, the 15th has an index of 14, and so on.

Creating Arrays

There are three steps when creating an array:

  1. Declare.

  2. Define.

  3. Initialize.

The third step isn’t always required, but the other two are necessary for an array to be usable.

Declaring an Array

You declare an array by specifying the type of array elements followed by a pair of empty square brackets and finally the name of the array, like so:

int[] numbers;

The previous line declares an array of integers called numbers. However, you can place the square brackets after the array name, as in this example, which declares an array of strings called names:

String names[];

Defining an Array

Before you can use an array you’ve declared, you need to define it by stating its size—the number of elements it’ll contain. This step is necessary so that the correct amount of memory can be allocated for it. You use the new keyword to define an array, like so:

numbers = new int[4];
names = new String[1000];

Here, you’ve defined the numbers array as containing four elements and names as containing 1,000.

On definition, each of the elements in an array is set to the default value for that data type. The default value of any primitive data type (except boolean) in an array is zero, the default value for a boolean is false, and the default value for any Object type is null.

Initializing and Resetting Array Values

The final step is to place initial values into your array elements. You can assign values to each of the elements individually, as follows:

numbers[0] = 39;
names[0] = "Chris";

The number between the brackets is the index of the element you want to populate.

You should note that you can reset the values contained by the elements in an array at any time during the array’s lifetime in the same way. So if Chris changed his name to Kurt, you could reset the value of the second element of the names array using this:

names[0] = "Kurt";

Creating an Array the Easy Way

There’s no need to declare and define arrays in individual steps; you can perform all of these steps in a single line of code if you want. For instance, you can create an array of four integers with the values 39, 21, 8, and 93 with this line:

int[] numbers = {39, 21, 8, 93};

Note that Java uses the number of values provided as initialization to set the size of the array.

Finally, the easiest way to create a new array is to initialize it using an existing array. For instance, now that you’ve created the numbers array, you could use it to initialize a new array, moreNumbers:

int[] moreNumbers = numbers;

In this case, Java creates a new integer array, moreNumbers, that has the same number of elements as the numbers array, and each element of moreNumbers will contain the same value as the corresponding element of numbers.

On a JSP page, you could declare an array using this sort of code inside a scriptlet. Generally speaking, however, placing Java code in a JSP page is considered a “breach of contract.” This “unwritten contract” states that JSP pages are for Hypertext Markup Language (HTML) and JSP tags, and Java objects are where code belongs. However, JSP actually provides you with arrays whenever data has been submitted to a page, whether using the GET or POST method (review Chapter 2), and the JSTL expression language provides a handy mechanism for getting these arrays, as you’ve already seen:

${ paramValues.book_id }

This will return a String array of the parameters called book_id that were submitted to the page. If there were only one book_id parameter, it’d be a String array whose size is one.

Now that you know about arrays, you can move on to control statements.


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-2014 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials