Overview of java statements chapter-3

Chapter 3
Statements

A computer program is a compilation of instructions called statements. There are many types of statements in Java and some—such as ifwhilefor, and switch—are conditional statements that determine the flow of the program. Even though statements are not features specific to object-oriented programming, they are vital parts of the language fundamentals. This chapter discusses Java statements, starting with an overview and then providing details of each of them. The return statement, which is the statement to exit a method, is discussed in Chapter 4, “Objects and Classes.”
An Overview of Java Statements
In programming, a statement is an instruction to do something. Statements control the sequence of execution of a program. Assigning a value to a variable is an example of a statement.
x = z + 5;
Even a variable declaration is a statement.
long secondsElapsed;
By contrast, an expression is a combination of operators and operands that gets evaluated. For example, z + 5 is an expression.
In Java a statement is terminated with a semicolon and multiple statements can be written on a single line.
x = y + 1; z = y + 2;
However, writing multiple statements on a single line is not recommended as it obscures code readability.
Note
In Java, an empty statement is legal and does nothing:
;
Some expressions can be made statements by terminating them with a semicolon. For example, x++ is an expression. However, this is a statement:
x++;
Statements can be grouped in a block. By definition, a block is a sequence of the following programming elements within braces:
images statements
images local class declarations
images local variable declaration statements
A statement and a statement block can be labeled. Label names follow the same rule as Java identifiers and are terminated with a colon. For example, the following statement is labeledsectionA.
sectionA: x = y + 1;
And, here is an example of labeling a block:
start: {
    // statements
}
The purpose of labeling a statement or a block is so that it can be referenced by the break and continue statements.
The if Statement
The if statement is a conditional branch statement. The syntax of the if statement is either one of these two:
if (booleanExpression) {
    statement(s)
}
if (booleanExpression) {
    statement(s)
} else {
    statement(s)
}
If booleanExpression evaluates to false and there is an else block, the statements in the else block are executed.
For example, in the following if statement, the if block will be executed if x is greater than 4.
if (x > 4) {
    // statements
}
In the following example, the if block will be executed if a is greater than 3. Otherwise, the else block will be executed.
if (a > 3)  {
    // statements
} else {
    // statements
}
Note that the good coding style suggests that statements in a block be indented.
If you are evaluating a boolean in your if statement, it's not necessary to use the == operator like this:
boolean fileExist = ...
if (fileExist == true) {
Instead, you can simply write
if (fileExists) {
By the same token, instead of writing
if (fileExists == false) {
write
if (!fileExists) {
If the expression to be evaluated is too long to be written in a single line, it is recommended that you use two units of indentation for subsequent lines. For example.
if (numberOfLoginAttempts < numberOfMaximumLoginAttempts
        || numberOfMinimumLoginAttempts > y) {
    y++;
}
If there is only one statement in an if or else block, the braces are optional.
if (a > 3)
    a++;
else
    a = 3;
However, this may pose what is called the dangling else problem. Consider the following example:
if (a > 0 || b < 5)
    if (a > 2)
        System.out.println("a > 2");
    else
        System.out.println("a < 2");
The else statement is dangling because it is not clear which if statement the else statement is associated with. An else statement is always associated with the immediately preceding if. Using braces makes your code clearer.
if (a > 0 || b < 5) {
    if (a > 2) {
        System.out.println("a > 2");
    } else {
        System.out.println("a < 2");
    }
}
If there are multiple selections, you can also use if with a series of else statements.
if (booleanExpression1) {
    // statements
} else if (booleanExpression2) {
    // statements
}
...
else {
    // statements
}
For example
if (a == 1) {
    System.out.println("one");
} else if (a == 2) {
    System.out.println("two");
} else if (a == 3) {
    System.out.println("three");
} else {
    System.out.println("invalid");
}
In this case, the else statements that are immediately followed by an if do not use braces. See also the discussion of the switch statement in the section, “The switch Statement” later in this chapter.
The while Statement
In many occasions, you may want to perform an action several times in a row. In other words, you have a block of code that you want executed repeatedly. Intuitively, this can be done by repeating the lines of code.2
java.awt.Toolkit.getDefaultToolkit().beep();
And, to wait for half a second you use these lines of code.
try {
    Thread.currentThread().sleep(500);
} catch (Exception e) {
}
Therefore, to produce three beeps with a 500 milliseconds interval between two beeps, you can simply repeat the same code:
java.awt.Toolkit.getDefaultToolkit().beep();
try {
    Thread.currentThread().sleep(500);
} catch (Exception e) {
}
java.awt.Toolkit.getDefaultToolkit().beep();
try {
    Thread.currentThread().sleep(500);
} catch (Exception e) {
}
java.awt.Toolkit.getDefaultToolkit().beep();
However, there are circumstances where repeating code does not work. Here are some of those:
images The number of repetition is higher than 5, which means the number of lines of code increases five fold. If there is a line that you need to fix in the block, copies of the same line must also be modified.
images If the number of repetitions is not known in advance.
A much cleverer way is to put the repeated code in a loop. This way, you only write the code once but you can instruct Java to execute the code any number of times. One way to create a loop is by using the while statement, which is the topic of discussion of this section. Another way is to use the for statement, which is explained in the next section.
The while statement has the following syntax.
while (booleanExpression) {
    statement(s)
}
Here, statement(s) will be executed as long as booleanExpression evaluates to true. If there is only a single statement inside the braces, you may omit the braces. For clarity, however, you should always use braces even when there is only one statement.
As an example of the while statement, the following code prints integer numbers that are less than three.
int i = 0;
while (i < 3) {
    System.out.println(i);
    i++;
}
Note that the execution of the code in the loop is dependent on the value of i, which is incremented with each iteration until it reaches 3.
To produce three beeps with an interval of 500 milliseconds, use this code:
int j = 0;
while (j < 3) {
    java.awt.Toolkit.getDefaultToolkit().beep();
    try {
    Thread.currentThread().sleep(500);
    } catch (Exception e) {
    }
    j++;
}
Sometimes, you use an expression that always evaluates to true (such as the boolean literal true) but relies on the break statement to escape from the loop.
int k = 0;
while (true) {
    System.out.println(k);
    k++;
    if (k > 2) {
        break;
    }
}
You will learn about the break statement in the section, “The break Statement” later in this chapter.
The do-while Statement
The do-while statement is like the while statement, except that the associated block always gets executed at least once. Its syntax is as follows:
do {
    statement(s)
} while (booleanExpression);
With do-while, you put the statement(s) to be executed after the do keyword. Just like the while statement, you can omit the braces if there is only one statement within them. However, always use braces for the sake of clarity.
For example, here is an example of the do-while statement:
int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 3);
This prints the following to the console:
0
1
2
The following do-while demonstrates that at least the code in the do block will be executed once even though the initial value of j used to test the expression j < 3 evaluates to false.
int j = 4;
do {
    System.out.println(j);
    j++;
} while (j < 3);
This prints the following on the console.
4
The for Statement
The for statement is like the while statement, i.e. you use it to enclose code that needs to be executed multiple times. However, for is more complex than while.
The for statement starts with an initialization, followed by an expression evaluation for each iteration and the execution of a statement block if the expression evaluates to true. An update statement will also be executed after the execution of the statement block for each iteration.
The for statement has following syntax:
for ( init ; booleanExpression ; update ) {
    statement(s)
}
Here, init is an initialization that will be performed before the first iteration, booleanExpression is a boolean expression which will cause the execution of statement(s) if it evaluates to true, and update is a statement that will be executed after the execution of the statement block. initexpression, and update are optional.
The for statement will stop only if one of the following conditions is met:
images booleanEpression evaluates to false
images A break or continue statement is executed
images A runtime error occurs.
It is common to declare a variable and assign a value to it in the initialization part. The variable declared will be visible to the expression and update parts as well as to the statement block.
For example, the following for statement loops five times and each time prints the value of i.
for (int i = 0; i < 3; i++) {
    System.out.println(i);
}
The for statement starts by declaring an int named i and assigning 0 to it:
int i = 0;
It then evaluates the expression i < 3, which evaluates to true since i equals 0. As a result, the statement block is executed, and the value of i is printed. It then performs the update statementi++, which increments i to 1. That concludes the first loop.
The for statement then evaluates the value of i < 3 again. The result is again true because i equals 1. This causes the statement block to be executed and 1 is printed on the console. Afterwards, the update statement i++ is executed, incrementing i to 2. That concludes the second loop.
Next, the expression i < 3 is evaluated and the result is true because i equals 2. This causes the statement block to be run and 2 is printed on the console. Afterwards, the update statement i++ is executed, causing i to be equal to 3. This concludes the second loop.
Next, the expression i < 3 is evaluated again, and the result is false. This stops the for loop.
This is what you see on the console:
0
1
2
Note that the variable i is not visible anywhere else since it is declared within the for loop.
Note also that if the statement block within for only consists of one statement, you can remove the braces, so in this case the above for statement can be rewritten as:
for (int i = 0; i < 3; i++)
    System.out.println(i);
However, using braces even if there is only one statement makes your code clearer.
Here is another example of the for statement.
for (int i = 0; i < 3; i++) {
    if (i % 2 == 0) {
        System.out.println(i);
    }
}
This one loops three times. For each iteration the value of i is tested. If i is even, its value is printed. The result of the for loop is as follows:
0
2
The following for loop is similar to the previous case, but uses i += 2 as the update statement. As a result, it only loops twice, when i equals 0 and when it is 2.
for (int i = 0; i < 3; i += 2) {
    System.out.println(i);
}
The result is
0
2
A statement that decrements a variable is often used too. Consider the following for loop:
for (int i = 3; i > 0; i--) {
    System.out.println(i);
}
which prints:
3
2
1
The initialization part of the for statement is optional. In the following for loop, the variable j is declared outside the loop, so potentially j can be used from other points in the code outside the for statement block.
int j = 0;
for ( ; j < 3; j++) {
    System.out.println(j);
}
// j is visible here
As mentioned previously, the update statement is optional. The following for statement moves the update statement to the end of the statement block. The result is the same.
int k = 0;
for ( ; k < 3; ) {
    System.out.println(k);
    k++;
}
In theory, you can even omit the booleanExpression part. For example, the following for statement does not have one, and the loop is only terminated with the break statement. See the section, “The break Statement” for more information.
int m = 0;
for ( ; ; ) {
    System.out.println(m);
    m++;
    if (m > 4) {
        break;
    }
}
If you compare for and while, you'll see that you can always replace the while statement with for. This is to say that
while (expression) {
    ...
}
can always be written as
be written as
for ( ; expression; ) {
    ...
}
Note
In addition, for can iterate over an array or a collection. See Chapters 5, “Core Classes” and Chapter 11, “The Collections Framework” for the discussions of the enhanced for.
The break Statement
The break statement is used to break from an enclosing dowhilefor, or switch statement. It is a compile error to use break anywhere else.
For example, consider the following code
int i = 0;
while (true) {
    System.out.println(i);
    if (i > 3) {
        break;
    }
}
The result is
0
1
2
3
Note that break breaks the loop without executing the rest of the statements in the block.
Here is another example of break, this time in a for loop.
int m = 0;
for ( ; ; ) {
    System.out.println(m);
    m++;
    if (m > 4) {
        break;
    }
}
The break statement can be followed by a label. The presence of a label will transfer control to the start of the code identified by the label. For example, consider this code.
start:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        if (j == 2) {
            break start;
        }
        System.out.println(i + ":" + j);
    }
}
The use of label start identifies the first for loop. The statement break start; therefore breaks from the first loop. The result of running the preceding code is as follows.
0:0
0:1
Java does not have a goto statement like in C or C++, and labels are meant as a form of goto. However, just as using goto in C/C++ may obscure your code, the use of labels in Java may make your code unstructured. The general advice is to avoid labels if possible and to always use them with caution.
The continue Statement
The continue statement is like break but it only stops the execution of the current iteration and causes control to begin with the next iteration.
For example, the following code prints the number 0 to 9, except 5.
for (int i = 0; i < 10; i++) {
    if (i == 5) {
        continue;
    }
    System.out.println(i);
}
When i is equals to 5, the expression of the if statement evaluates to true and causes the continue statement to be called. As a result, the statement below it that prints the value of i is not executed and control continues with the next loop, i.e. for i equal to 6.
As with breakcontinue may be followed by a label to identify which enclosing loop to continue to. As with labels with break, employ continue label with caution and avoid it if you can.
Here is an example of continue with a label.
start:
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        if (j == 2) {
            continue start;
        }
        System.out.println(i + ":" + j);
    }
}
The result of running this code is as follows:
0:0
0:1
1:0
1:1
2:0
2:1
The switch Statement
An alternative to a series of else if, as discussed in the last part of the section, “The if Statement,” is the switch statement. switch allows you to choose a block of statements to run from a selection of code, based on the return value of an expression. The expression used in the switch statement must return an int, a String, or an enumerated value.
Note
The String class is discussed in Chapter 5, “Core Classes” and enumerated values in Chapter 10, “Enums.”
The syntax of the switch statement is as follows.
switch(expression) {
case value_1 :
    statement(s);
    break;
case value_2 :
    statement(s);
    break;
  .
  .
  .
case value_n :
    statement(s);
    break;
default:
    statement(s);
}
Failure to add a break statement after a case will not generate a compile error but may have more serious consequences because the statements on the next case will be executed.
Here is an example of the switch statement. If the value of i is 1, “One player is playing this game.” is printed. If the value is 2, “Two players are playing this game is printed.” If the value is 3, “Three players are playing this game is printed. For any other value, “You did not enter a valid value.” will be printed.
int i = ...;
switch (i) {
case 1 :
    System.out.println("One player is playing this game.");
    break;
case 2 :
    System.out.println("Two players are playing this game.");
    break;
case 3 :
    System.out.println("Three players are playing this game.");
    break;
default:
    System.out.println("You did not enter a valid value.");
}
For examples of switching on a String or an enumerated value, see Chapter 5, “Core Classes” and Chapter 10, “Enums,” respectively.
Summary
The sequence of execution of a Java program is controlled by statements. In this chapter, you have learned the following Java control statements: ifwhiledo-whileforbreakcontinue, and switch. Understanding how to use these statements is crucial to writing correct programs.
Questions
1.  What is the difference between an expression and a statement?
2.  How do you escape from the following while loop?
while (true) {
    // statements
}
3.  Is there any difference between using the postfix increment operator and the prefix increment operator as the update statement of a for loop?
for (int x = 0; x < length; x++)
for (int x = 0; x < length; ++x)
4.  What will be printed on the console if the code below is executed:
int i = 1;
switch (i) {
case 1 :
    System.out.println("One player is playing this game.");
case 2 :
    System.out.println("Two players are playing this game.");
    break;
default:
    System.out.println("You did not enter a valid value.");
}
Hint: no break after case 1.


2What this line of code and the following lines of code do will become clear after you read Chapter 4.

About Sudhir Kumar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 σχόλια :

Post a Comment