Jun 30, 2015 11:23 AM PT
Java 101: Foundations

Java 101: Deciding and iterating with Java statements

Use statements to make decisions, iterate, and perform other tasks in your Java programs

Thinkstock

Java applications evaluate expressions in the context of statements, which are standalone islands of code that accomplish various tasks such as declaring a variable, making a decision, or iterating over statements. A statement can be expressed as a simple statement or as a compound statement:

  • A simple statement is a single standalone instruction for performing a task; it must be terminated with a semicolon character (;).
  • A compound statement is a sequence of simple and other compound statements located between open- and close-brace characters ({ and }), which delimit the compound statement's boundaries. Compound statements can be empty, will appear wherever simple statements appear, and are alternatively known as blocks. A compound statement is not terminated with a semicolon.

In this article I introduce you to using statements in your Java programs. You can use statements to declare variables and specify expressions, make decisions, iterate over statements (yes, you can use statements to iterate over statements), break and continue iteration, and do nothing. I'll leave some of the more exotic statements (such as statements for returning values from called methods and for throwing exceptions) for a future Java 101 article.

download
Source code for "Java 101: Deciding and iterating with Java statements." Created by Jeff Friesen for JavaWorld.

Declaring variables and specifying expressions as statements

Earlier in this series I introduced you to the concept of a variable and mentioned that a variable must be declared before it is used. I also mentioned that a variable declaration minimally consists of a type name, optionally followed by a sequence of square-bracket pairs, followed by a name, optionally followed by a sequence of square-bracket pairs, and terminated with a semicolon. Also, a variable may be explicitly initialized during its declaration.

Because a variable declaration is a standalone island of code, it's effectively a statement -- a simple statement to be exact. Here are a few example variable declaration statements:

int age = 25;
float interest_rate;
char[] text = { 'J', 'a', 'v', 'a' };
String name;

Closely related to the variable declaration statement is the assignment statement, which assigns a value (possibly a reference to an array or a reference to an object) to a variable. A few examples appear below:

age = 30;
interest_rate = 4.0F;
age += 10;
text[1] = 'A';
text[2] = 'V';
text[3] = 'A';
name = "John Doe";

An assignment statement is an example of an expression statement, which is an expression that may be used as a statement if it is followed with a semicolon. The following expressions also qualify as expression statements:

  • Preincrement (e.g., ++x;)
  • Predecrement (e.g., --y;)
  • Postincrement (e.g., x++;)
  • Postdecrement (e.g., y--;)
  • Method call (e.g., System.out.println("Hello");)
  • Object creation (e.g., new String("ABC");)

Making decisions

Decision statements let applications choose between multiple paths of execution. For example, if a salesperson sells more than 500 items this month, give the salesperson a bonus. Also, if a student's grade on an algebra test is greater than 85 percent, congratulate the student for doing well; otherwise, recommend that the student study harder for the next test.

Java supports the if, if-else, and switch decision statements.

The if statement

The simplest of Java's decision statements is the if statement, which evaluates a Boolean expression and executes another statement when this expression evaluates to true. The if statement has the following syntax:

if (Boolean expression)
   statement

The if statement starts with reserved word if and continues with a parenthesized Boolean expression, which is followed by the statement to execute when the Boolean expression evaluates to true.

The following example demonstrates the if statement. When the age variable contains a value of 55 or greater, if executes System.out.println(...); to output the message:

if (age >= 55)
   System.out.println("You are or were eligible for early retirement.");

Many people prefer to wrap any simple statement that follows the if statement in braces, effectively converting it to an equivalent compound statement:

if (age >= 55)
{
   System.out.println("You are or were eligible for early retirement.");
}

Although the braces clarify what is being executed by the if statement, I believe that the indentation provides this clarity, and that the braces are unnecessary. You might prefer to specify the braces, however.

The if-else statement

The if-else statement evaluates a Boolean expression, executes one statement when this expression evaluates to true, and executes another statement when it evaluates to false. Here's the syntax for the if-else statement:

if (Boolean expression)
   statement1
else
   statement2

The if-else statement is similar to the if statement, but also includes reserved word else followed by a statement to execute when the Boolean expression is false.

The following example demonstrates an if-else statement that tells someone who is less than 55 years old how many years are left until early retirement:

if (age >= 55)
   System.out.println("You are or were eligible for early retirement.");
else
   System.out.println("You have " + (55 - age) + " years to go until early retirement.");

Chaining if-else statements

Java lets you chain multiple if-else statements together for situations where you need to choose one of multiple statements to execute. The resulting syntax appears below:

if (Boolean expression1)
   statement1
else
if (Boolean expression2)
   statement2
else
   ...
else
   statementN

The chaining works by executing a subsequent if-else statement whenever the current if statement's Boolean expression evaluates to false. The following example provides a demonstration of this chaining behavior:

if (temperature < 0.0)
   System.out.println("freezing");
else
if (temperature > 100.0)
   System.out.println("boiling");
else
   System.out.println("normal");

The first if-else statement determines if temperature's value is negative. If so, it executes System.out.println("freezing");. If not, it executes a second if-else.

The second if-else determines if temperature's value is greater than 100. If so, it executes System.out.println("boiling");. Otherwise, it executes System.out.println("normal");.

The dangling-else problem

When if and if-else are used together, and the source code isn't properly indented, it can be difficult to determine which if associates with the else. The following example demonstrates this problem:

int x = 0;
int y = 2;
if (x > 0)
   if (y > 0)
      System.out.println("x > 0 and y > 0");
else
   System.out.println("x <= 0");

In this example, you probably expect to see x <= 0 output. But that will never happen, instead nothing will output. The else matches up to its nearest if, which is if (y > 0). Once this example is reformatted, you can more clearly see what is happening:

int x = 0;
int y = 2;
if (x > 0)
   if (y > 0)
      System.out.println("x > 0 and y > 0");
   else
      System.out.println("x <= 0");

As you can see, an if (y > 0) ... else ... if-else statement follows the if (x > 0) statement. To create the intent of the previous example, you need to introduce brace characters around if (y > 0) and its subsequent statement. Essentially, a block will follow if (x > 0):

int x = 0;
int y = 2;
if (x > 0)
{
   if (y > 0)
      System.out.println("x > 0 and y > 0");
}
else
   System.out.println("x <= 0");

Because x > 0 evaluates to false, System.out.println("x <= 0"); executes. The else reserved word clearly matches up to if (x > 0).

The switch statement

The switch statement lets you choose from among several execution paths more efficiently than by using equivalent chained if-else statements. It has the following syntax:

switch (selector expression)
{
   case value1: statement1 [break;]
   case value2: statement2 [break;]
   ...
   case valueN: statementN [break;]
   [default: statement]
}

The switch statement begins with reserved word switch and continues with a selector expression that selects one of the subsequent cases or the default case to execute. The selector expression evaluates to an integer, a character, or a string.

Each case identifies a statement to execute. The case begins with the reserved word case and a value that labels the case. Following a colon (:) character is the statement to execute. The statement can be optionally followed by break;, to transfer execution to the first statement after switch. If none of the case labels matches the selector expression's value, the optional default case, which begins with reserved word default, will execute.

The following example demonstrates a switch statement that determines if an integer value is even or odd (by using the remainder operator) and then outputs an appropriate message via the case whose label matches the remainder:

int i = 27;
switch (i % 2)
{
   case 0: System.out.println("even");
           break;

   case 1: System.out.println("odd");
}

This example outputs odd because i % 2 yields 1, which matches the second case label. If I omitted break;, and if the number was even, even followed by odd would output because execution would drop through to the second case.

Sometimes, it's desirable to have execution drop through to the next case. For example, suppose you want to execute common code in response to the user specifying an uppercase or lowercase command-line option letter:

switch (args[i])
{
   case "-v":
   case "-V": System.out.println("Version 1.0");
              break;

   // ...

   default  : System.out.println("unknown option");
}

Imagine that a for statement (discussed shortly) is iterating over each of the arguments in the array of command-line arguments passed to an application's main() method. If the argument is -v (dash and lowercase v) or -V (dash and uppercase V), the application's version number is output. When -v is specified, it's necessary to have execution drop through to the following case, which outputs the version number when -V is specified.

The default case is executed whenever the string referenced by args[i] doesn't match any of the case labels. In other words, the user has specified an unknown option.

Iterating over statements

Iteration statements (also known as loop statements) repeatedly execute other statements for a specific number of iterations (loops) or indefinitely until some terminating condition arises. For example, as previously mentioned, you might want to iterate over all of the String objects in the array of command-line arguments passed to a main() method. Java supports the for, while, and do-while iteration statements.

The for statement

The for statement executes another statement a specific number of times or indefinitely. It is essentially a compact form of the while statement (discussed later) and has the following syntax:

for ([initialize]; [test]; [update])
   statement

This syntax shows that a for statement begins with the reserved word for and continues with a parentheses-delimited and semicolon-separated sequence of three sections:

  • initialize: A comma-separated list of variable declarations or assignments. These variables, which are known as iteration variables or loop variables, are used to index arrays, take part in calculations, or perform other tasks.
  • test: A Boolean expression that determines how long the loop executes. Execution continues for as long as this expression remains true.
  • update: A comma-separated list of expressions that typically modify the loop variables.

Following the for statement is a statement to execute repeatedly.

Each of the three sections is optional. As a result, for can be shrunk down to for (; ;). Because there is no stopping condition, the resulting loop is known as an infinite loop.

The following example uses the for statement to iterate over all elements in an array named args, outputting the value of each array element:

for (int i = 0; i < args.length; i++)
   System.out.println(args[i]);

This example works as follows:

  1. Declare variable i and initialize it to 0.
  2. Evaluate i < args.length. If i equals args.length, terminate the loop.
  3. Execute System.out.println(args[i]);.
  4. Execute i++.
  5. Continue with Step 2.

Variable i is visible to the for statement's test and update sections, and to statement. However, it isn't visible to subsequent statements. If you want subsequent statements to see i's final value, declare i before for, as follows:

int i;
for (i = 0; i < args.length; i++)
   System.out.println(args[i]);

The variable that controls the loop can be a different primitive type, such as Boolean, character, or double precision floating-point. Here are three examples:

for (boolean b = false; b != true; b = !b)
   System.out.println(b); // This statement executes once.

for (char c = 'A'; c <= 'F'; c++)
   System.out.println(c);

for (double d = 0.0; d < 1.0; d += 0.1)
   System.out.println(d);

Finally, as previously mentioned, the initialize section can declare multiple variables. The following example declares two variables, incrementing one variable and decrementing the other variable throughout the loop:

for (int i = 0, j = 5; i <= 5; i++, j--)
   System.out.println(i + j);

The output consists of six lines of 5.

The while statement

The while statement repeatedly executes another statement while its controlling Boolean expression keeps evaluating to true. This statement has the following syntax:

while (Boolean expression)
   statement

This syntax shows that a while statement begins with the reserved word while and continues with a parenthesized Boolean expression. This statement is followed by another statement to execute repeatedly.

The following example demonstrates the while statement:

int i = 0;
while (i < args.length)
{
   System.out.println(args[i]);
   i++;
}

This example works as follows:

  1. Declare variable i and initialize it to 0.
  2. Evaluate i < args.length. If i equals args.length, terminate the loop.
  3. Execute System.out.println(args[i]);.
  4. Execute i++.
  5. Continue with Step 2.

This example is the while equivalent of the previous for example. You could compact the example to repeatedly execute a simple statement instead of a compound statement, as follows:

int i = 0;
while (i < args.length)
   System.out.println(args[i++]);

In this compacted example, I've changed the postincrement statement to an expression that's passed to the array index operator. Although the code is more compact, you might prefer the previous example for clarity.

The do-while statement

The do-while statement repeatedly executes a statement while its controlling Boolean expression, which is evaluated after the statement is executed, evaluates to true. This statement has the following syntax:

do
   statement
while (Boolean expression); // The semicolon terminator is mandatory.

This syntax shows that a do-while statement begins with reserved word do, continues with a statement to execute repeatedly, and ends with reserved word while, followed by a parenthesized Boolean expression.

The following example demonstrates the do-while statement:

int ch;
do
{
   System.out.println("Press x to continue.");
   ch = System.in.read();
}
while (ch != 'x');

This example works as follows:

  1. Declare int variable ch to store a character's numeric code.
  2. Prompt the user to press the x key to continue.
  3. Read a key code from the keyboard via System.in.read(), which is a companion of System.out.println(). Because this method returns the key's code as an int, assign this value to ch.
  4. Compare ch's value with 'x'. Note that 'x' is widened from char to int before the comparison. Terminate the loop when this expression evaluates to false (ch equals 'x'). Otherwise, continue with Step 2.

The difference between while and do-while is that while executes its statement zero or more times, whereas do-while executes its statement one or more times. You will choose either statement based on this property. For example, it's appropriate to use while to iterate over the args array because this array might have zero length and you don't want to access the array in this case (and raise an out-of-bounds exception, which is discussed in a future article). In contrast, you would access the array at least once with do-while (and raise an out-of-bounds exception). It's appropriate to use do-while to prompt the user to enter a key and read the response because these tasks must happen at least once.

Breaking out of and continuing iteration

You previously saw the break statement in the context of a switch statement, for breaking out of a switch statement once a case has executed. However, this statement also can be used in an iteration statement context, which I discuss in this section. I also discuss the continue statement, which can be used in an iteration statement context only. You will explore the unlabeled and labeled versions of these statements.

The unlabeled break and labeled break statements

The unlabeled break statement terminates a switch, for, while, or do-while statement by transferring execution to the first statement following this statement. It has the following syntax:

break;

The following example demonstrates the unlabeled break statement in an iteration statement context:

for (; ;)
{
   System.out.println("Press x to continue.");
   int ch = System.in.read();
   if (ch == 'x')
      break;
}

This example introduces a for-based infinite loop that repeatedly prompts the user to press the x key and reads this key until it equals 'x'. An if statement performs the comparison, executing break; to terminate the loop when the x key is pressed.

The labeled break statement terminates a containing and labeled switch, for, while, or do-while statement by transferring execution to the first statement following the containing statement. It has the following syntax:

break label;

This syntax consists of reserved word break followed by a non-reserved word identifier to serve as a label, followed by a semicolon. The label must be prefixed to a previous switch or iteration statement and must be followed by a colon.

The following example demonstrates the labeled break statement in an iteration statement context:

outer:
while (true)
{
   System.out.println("Guess number between 0 and 9.");
   while (true)
   {
      System.out.println("Press n for new game or q to quit.");
      int ch = System.in.read();
      if (ch == 'n')
         break;
      if (ch == 'q')
         break outer;
   }
}

This example presents a pair of nested infinite while loops that describe part of a number-guessing game. The outer loop is a stub for playing the game, whereas the inner loop prompts the user to play a new game or quit the game.

If the user presses the n key, the unlabeled break statement is executed to terminate the inner loop so that a new game can be played. If q is pressed, break outer; is executed to quit the outer loop, which is assigned an outer: label.

The unlabeled continue and labeled continue statements

The unlabeled continue statement skips the remainder of the current iteration and tells the iteration statement to advance to the next iteration. It has the following syntax:

continue;

Here's an example usage of the unlabeled continue statement:

for (int i = -2; i <= 2; i++)
   if (i == 0)
      continue;
   else
      System.out.println(10 / i);

This example's for statement iterates from -2 to 2, repeatedly executing an if-else statement and then incrementing i by 1 after each iteration.

To prevent a divide-by-zero exception when i contains 0, if tests i for 0. If this is the case, it executes continue;, which causes for to increment i and then evaluate i <= 2. Otherwise, 10 / i is evaluated and the result is output.

The labeled continue statement skips the remaining iterations of one or more nested iteration statements and transfers execution to the labeled iteration statement. It has the following syntax:

continue label;

This syntax consists of reserved word continue followed by a non-reserved word identifier to serve as a label, followed by a semicolon. The label must be prefixed to a previous iteration statement and must be followed by a colon.

Here's an example using the labeled continue statement:

outer:
for (int i = -2; i <= 2; i++)
   for (int j = -2; j <= 2; j++)
      if (i == 0)
         continue outer;
      else
      if (j == 0)
         continue;
      else
         System.out.println(10 / i * j);

This example presents a pair of nested for loops, with each loop variable ranging from -2 through 2. The idea is to divide 10 by the product of the loop variable values. However, division by zero will occur when either variable contains 0.

To prevent division by zero, a chained if-else statement is used to test i's and j's values for 0. If i's value is 0, continue outer; is used to terminate the inner loop and advance the outer loop (with label outer:) past 0. If j's value is 0, continue; is used to quit the current inner loop iteration and advance the inner loop past 0. If neither situation arises, the calculation is performed and its result is output.

Doing nothing

There is one final statement to consider, which is the empty statement, a statement consisting solely of the semicolon character. This statement accomplishes nothing, and yet it is useful. Consider the following example:

for (int ch; (ch = System.in.read()) != -1; System.out.print((char) ch));

This example copies the contents of the standard input stream, read via calls to System.in.read(), to the standard output stream, written via calls to System.out.print(), a companion to System.out.println() that doesn't output a line separator. It works best when the standard input stream is redirected from the keyboard to a text file.

When redirected to a file, System.in.read() returns -1 when there is no more input. When not redirected, System.in.read() obtains its input from the keyboard and never returns -1. Instead, when there are no more key codes to return, System.in.read() returns a line separator character -- two calls are needed on Windows to return its \r\n characters, one call is needed on Unix\Linux to return its \n character, and one call is needed on older versions of Mac OS to return its \r character. For more information, check out Newline.

As you can see, all of the work is performed in the for statement's initialize and test sections. The final semicolon refers to the empty statement, which is executed repeatedly.

Be careful with the empty statement because it can be the source of hard-to-find bugs. For example, you might expect the following for statement to output 10 instances of the word Hello:

for (int i = 0; i < 10; i++);
   System.out.println("Hello");

Instead, you will only observe a single instance of this word, because of the empty statement after the for statement's closing parenthesis. for executes the empty statement 10 times, after which the method call is executed once.

Writing interesting applications

Now that you've explored all of Java's fundamental language features, you're ready to start creating interesting applications. For example, consider a guess-the-number game that randomly selects an integer ranging from 0 through 9 and asks you to guess this number. If you guess too high or too low, the game will tell you. It will also tell you when you guess correctly, and will ask you if you want to play again.

Before I present the game application's source code, I need to introduce you to two features in this source code that you haven't yet encountered:

  • I use System.in.read() to return either the code of a pressed key (when standard input is not redirected) or an 8-bit value from a file (when standard input is redirected). System.in.read() is capable of throwing an exception, so I had to append "throws Exception" to the main() method header, as in public static void main(String[] args) throws Exception. This prevents the compiler from reporting an error.
  • To obtain a random integer, I need to invoke the random() method member of the standard class library's Math class. random() returns a floating-point value ranging from 0.0 to almost 1.0. An expression converts this number to a more useful integer.

Listing 1 presents the source code to the Guess application.

Listing 1. Guess.java

class Guess
{
   public static void main(String[] args) throws Exception
   {
      outer:
      while (true)
      {
         System.out.println("I'm thinking of a number between 0 and 9.");
         int number = (int) (Math.random() * 10);
         while (true)
         {
            int guessNumber;
            while (true)
            {
               System.out.println("Enter your guess number between 0 and 9.");
               guessNumber = System.in.read();
               while (System.in.read() != '\n');
               if (guessNumber >= '0' && guessNumber <= '9')
               {
                  guessNumber -= '0';
                  break;
               }
            }
            if (guessNumber < number)
               System.out.println("Your guess is too low.");
            else
            if (guessNumber > number)
               System.out.println("Your guess is too high.");
            else
            {
               System.out.println("Congratulations! You guessed correctly.");
               while (true)
               {
                  System.out.println("Press n for new game or q to quit.");
                  int ch = System.in.read();
                  while (System.in.read() != '\n');
                  if (ch == 'n')
                     continue outer;
                  if (ch == 'q')
                     break outer;
               }
            }
         }
      }
   }
}

Guess demonstrates several statements and other fundamental features presented in previous articles. The main() method presents a while statement that generates a new number and gives you a chance to guess it. Expression (int) (Math.random() * 10) multiplies random()'s return value by 10 to change the range to 0.0 to almost 10.0, and converts the result to an integer ranging from 0 through 9.

After generating the number, main() executes an inner while statement to handle all of the guesswork. It repeatedly prompts for a guess, converts the pressed key's Unicode character value to a binary integer value from 0 through 9, and determines whether the user has guessed correctly or not. A suitable message is output. Users who guess correctly are given the chance to play a new game by pressing n, or to quit the application by pressing q.

An interesting part of the source code is while (System.in.read() != '\n');. I use this statement to flush the line separator character(s) (e.g., \r\n on Windows) from the operating system's keyboard buffer. If I don't do this, you'll see multiple prompts because each separator character will be interpreted as an attempt to enter a value from 0 through 9 (or n or q). If you are running Java on an older version of Mac OS, you'll probably have to replace \n with \r, which is the Mac's line separator. No changes are necessary when running on Linux or Unix, whose line separator is \n. (You can make the code portable by working with the standard class library's System class, which offers access to the line.separator property. I'll leave this task as a future exercise for when you're more comfortable with Java's classes and methods.)

Compile Listing 1 as follows:

javac Guess.java

Then run the application:

java Guess

Below is the output from a sample run:

I'm thinking of a number between 0 and 9.
Enter your guess number between 0 and 9.
5
Your guess is too high.
Enter your guess number between 0 and 9.
2
Your guess is too low.
Enter your guess number between 0 and 9.
3
Your guess is too low.
Enter your guess number between 0 and 9.
4
Congratulations! You guessed correctly.
Press n for new game or q to quit.
q

In conclusion

Statements are the workhorses of a Java application. Mastering them along with the other fundamental language features will help you develop a solid foundation on which to build your knowledge of more advanced language features. We'll begin this expansion in the next article, where I will introduce you to Java classes and objects.