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

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 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.

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.

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

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.
1 2 3 Page 1
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.