Friday, January 15, 2016

Topic 9: Statements in Java

  • Java’s control statements can be put into the following categories: selection, iteration, jump. 

  • Selection statements allow program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Java supports two selection statements: if and switch

    • The general form of the if statement: 

    if (condition) statement1;

    else statement2;

    Most often, the expression used to control the if will involve the relational operators. However, it is possible to control the if using a single boolean variable, as shown in this code fragment:

    boolean dataAvailable;

    if (dataAvailable) statements;

    • The switch statement often provides a better alternative to a large series of if-else-if statements. Here is the general form of a switch statement:

switch (expression)

{

case value1: // statement sequence

break;

case value2: // statement sequence

break;

....

case valueN: // statement sequence

break;

default: // default statement sequence

} 

The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. An enumeration value can also be used to control a switch statement. Each case value must be a unique literal and not a variable.

The switch statement works like this:

  • The value of the expression is compared with each of the literal values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constants match the value of the expression, then the default statement is executed. 

  • Default statement is optional. 

  • If no case matches and no default is present, then no further action is taken. 

  • When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. The break statement is optional. If it is omitted, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them. For example, consider the following snippet:

switch (month) { 

case 12: case 1: case 2: season = "Winter"; break; 

case 3: case 4: case 5: season = "Spring"; break; 

case 6: case 7: case 8: season = "Summer"; break; 

case 9: case 10: case 11: season = "Autumn"; break; 

default: season = "Invalid Month"; }

  • The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression.  

  • A switch statement is usually more efficient than a set of nested ifs. When it compiles a switch statement, the Java compiler will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression.

  • Iteration statements enable program execution to repeat one or more statements. Java’s iteration statements are for, while, and do-while.

    • The while loop repeats a statement or block while its controlling expression is true. Here is its general form:

    while(condition) {
    // body of loop
    }

    • The condition can be any Boolean expression. 

    • The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop.

    • The curly braces are unnecessary if only a single statement is being repeated.

    • Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute even once if the condition is false to begin with.

    Important note: The body of the while (or any other of Java’s loops) can be empty. This is because a null statement (one that consists only of a semicolon) is syntactically valid in Java. For ex, while(++i < --j) ; // no body in this loop 

    • Unlike while loop, the do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is:

    do {
    // body of loop
    } while (condition);

    • Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. 

    • As with all of Java’s loops, condition must be a Boolean expression.

    • The do-while loop is especially useful when you process a menu selection. 

    • Beginning with JDK 5, there are two forms of the for loop - traditional “for” and “for-each”. Here is the general form of the traditional for statement:

    for(initialization; condition; iteration) { 

    // body

    }

    • The variable that controls a for loop is only needed for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for. For ex, for(int n=10; n>0; n--). The scope of that variable ends when the for statement does.

    • To allow two or more variables to control a for loop, Java permits us to include multiple statements in both the initialization and iteration portions of the for. Each statement is separated from the next by a comma.

    int a, b;

    for(a=1, b=4; a<b; a++, b--)// In Java, the comma is a separator.

    • We can create an infinite loop (a loop that never terminates) if we leave all three parts of the for empty. For example: for( ; ; ) { }

    • Beginning with JDK 5, the For-Each(or enhanced for loop) style loop of for is designed to cycle through a collection of objects, such as an array, in strictly sequential fashion, from start to finish. The advantage of this approach is that no new keyword is required, and no preexisting code is broken. The general form of the for-each:

for(type itr-var : collection) statement-block 

itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end. 

type must be the same as (or compatible with) the elements stored in the collection. 

With each iteration of the loop, the next element in the collection is retrieved and stored in itr-var. The loop repeats until all elements in the collection have been obtained.

For ex,

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int sum = 0;

for(int x: nums) sum += x; 

With each pass through the loop, x is automatically given a value equal to the next element in nums. Thus, on the first iteration, x contains 1; on the second iteration, x contains 2; and so on. Not only is the syntax streamlined, but it also prevents boundary errors (index overflow, underflow errors). 

  • It is possible to terminate the loop early by using a break statement. 

  • The iteration variable is “read-only”. For ex:

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x : nums)
{
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for(int x : nums)

System.out.print(x + " ");

The first for loop increases the value of the iteration variable by a factor of 10. However, this assignment has no effect on the underlying array nums.

  • The enhanced version of the for also works on multidimensional arrays. In Java, multidimensional arrays consist of arrays of arrays. When iterating over a multidimensional array, each iteration obtains the next array. Therefore, the iteration variable in the for loop must be compatible with the type of array being obtained. For example, in the case of a two-dimensional array, the iteration variable must be a reference to a one-dimensional array. In general, when using the for-each for to iterate over an array of N dimensions, the objects obtained will be arrays of N–1 dimensions. For ex,

int nums[][] = new int[3][5];

for(int x[] : nums)

for(int y : x)

System.out.println("Value is: " + y);

  • Jump statements allow our program to execute in a nonlinear fashion. Java supports three jump statements: break, continue, and return. These statements transfer control to another part of the program.

    • In Java, the break statement has three uses: 

      • In a switch statement. 

      • To exit a loop. 

      • As a “civilized” form of goto.

    Few points to remember: 

    • Inside a set of nested loops, the break can only break out of the innermost loop. 

    • The break that terminates a switch statement affects only that switch statement and not any enclosing loops.

    • Java does not have a goto statement. Goto can be useful when exiting from a deeply nested set of loops. Java implements goto by using version of break statement. The general form of the labeled break statement is shown here: 

    break label;

    label is any valid Java identifier that identifies a stand-alone block of code or a block that is the target of another statement. To name a block, put a label at the start of it followed by a colon. Once we label a block, we can use this label as the target of a break statement. Doing so causes execution to resume at the end of the labeled block. For ex, 

    boolean t = true;
    first:
    {
    second:
    {
    third:
    {
    System.out.println("Before the break.");
    if(t) break second; // break out of second block
    System.out.println("This won't execute");
    }
    System.out.println("This won't execute");
    }
    System.out.println("This will execute.");
    }

    • Labeled break statement is used mostly to exit from nested loops. For ex, in the following code fragment, the outer loop executes only once:

    outer: for(int i=0; i<3; i++) 
    {
    for(int j=0; j<100; j++)
    if(j == 10)
    break outer; // exit both loops
    }

    • We cannot break to any label which is not defined for an enclosing block. For ex, following code fragment will lead to compilation error:

    one: for(int i=0; i<3; i++)
    {
    System.out.print("Pass " + i + ": ");
    }
    for(int j=0; j<100; j++)
    if(j == 10) break one; // WRONG - break is not defined inside enclosing block

    • To force an early iteration of a loop, we use continue statement. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression controlling the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed. For ex, the following code fragment only prints the odd nos:

    for(int i=0; i<10; i++)
    {
    if (i%2 == 0)
    continue;
    System.out.println("Odd nos " + i + " is printed.");
    }

    Continue may specify a label to describe which enclosing loop to continue. For ex:

    outer: for (int i=0; i<10; i++)
    {
    for(int j=0; j<10; j++)
    if(j > i)
    continue outer;
    }

    • The return statement is used to explicitly return from a method. It causes program control to transfer back to the caller of the method. 

 

Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment