The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION VII- Programming Flow Instructions

Step 24: Straight Line and Branch Programming



There are 2 kinds of programming, based on the path the code travels:

In JAVA the code Instructions used in coding are similar to C, or C++.


Straight Line Programming

Straight line Programming is when there is no decision making in our code. There is no branch in the path. It is just a straight path from beginning to end. As an example of Straight-line Programming we can think about a program that the only task performed are assignment, and mathematical manipulations.

Example of Straight Line code:

class Exercise
{ public static void main(String[] arg)
{ int a = 4;
int b = 5;
System.out.println(a*b);
}
}


Branch Programming

Branch Programming is when decision making is implemented in our code. The code may generate one or many branches. In JAVA, decision making or branching can be implemented by the existing control flow Instructions.

The Programming Flow Instructions that we wil be seeing in next Steps are categorized into the following groups:

  • Decision and Cases (if / else, switch)


  • Iteration or Loops (for, while, do while)


  • Processor Control (break, continue)
These Instructions ought to be written in a method where they will be implemented. Or they can be enclosed between curly braces. We are showing some Examples where these Instructions are written inside the 'main' method. Obviously they can be written in any method.

Click here to go to the JAVA Mini-Course page

The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION VII- Programming Flow Instructions

Step 25: Decisions and Cases


Decisions and Cases (if / else, switch)


The 'if' Statement

A decision can be made by using the 'if' statement.

The 'if' statement is followed by a set of parenthesis. In that set of parenthesis a boolean expression is evaluated. If that expression evaluates to true, then the 'if' construct is implemented; otherwise it's not. It is important to emphasize that the expression contained withint that set of parenthesis has to evaluate to a boolean.

For instance, we can have a relational operator to compare variables, and determine whether a true or false results. A boolean expression can be comprised of non-boolean variables, for example: if (a > b), here a > b is evaluated and it will result in a true or false. We can also have a boolean variables inside the parentheses, for example: if (flag), here flag is a boolean variable, and it will be determined whether is true or false. Notice that we cannot have a non-boolean variable by itself inside the parentheses, for example: if (year), where year is an 'int' is not allowed. The compiler will yield an error.

When using the ''if' construct, it is not mandatory to use the ''else'. See 'else' statement below.

The ''if' construct is encased within curly braces. However, if there is only one line of code to be implemented then the curly braces are optional. This rule also applies to the 'else', 'while', 'do while', and 'for' statement.

(In the example below, we use curly braces for the ''if' construct. However, in that case that is optional as there is only one line of code within that construct.)

Example:

class Exercise
{ public static void main(String[] arg)
{ int A = 6;
int B = 5;
if (A > B)
{ System.out.println("A is greater than B"); }
}
}



The 'else' Statement

The ''else' statement can only be used if we have a counterpart ''if' statement, but it's not mandatory. It is used as a way to capture the default from the ''if' statement. It does not evaluate, as the evaluation is done by the 'if' statement.

The 'else' construct is encased within curly braces. However, if there is only one line of code to be implemented then the curly braces are optional. This rule also applied to the 'if', 'while', 'do while', and 'for' statements.

See Example below:

class Exercise
{ public static void main(String[] arg)
{ int A = 6;
int B = 5;
if (A > B)
{ System.out.println("A is greater than B"); }
else
{ System.out.println("A is less or equal to B"); }
}
}

Sometimes when using more than one if / else construct, it is convenient to indent properly the code, so that each 'else' can be identified to which 'if' it belongs to.

When we have many if / else constructs, an easy way of expressing them is by the use of 'else' immediately followed by 'if'.

See Example below:

class Exercise
{ public static void main(String[] arg)
{ int A = 6;
int B = 5;
if (A > B)
{ System.out.println("A is greater than B"); }
else if (A < B)
{ System.out.println("A is less than B"); }
else
{ System.out.println("A is equal to B"); }
}
}



The 'switch' Construct

The 'switch' Instruction is used to evaluate cases. It evaluates short, int, long and char. Depending on the result of the evaluation the program continues to the appropriate case statement.

The 'switch' construct can also uses a 'defaut' case which is usually placed by the end, to capture any unwanted or default values.

A 'case' uses a constant or literal as its field. That constant or literal is of the short, int, long or char type.

The example below illustrates the use and syntax of the 'switch' construct. Notice that the switch construct always contains the curly braces to embed the case statements.

class Exercise
{ public static void main(String[] arg)
{ int a = 6;
switch(a) // It evaluates 'a' and program control goes to case 6. { case 1: System.out.println("Case 1"); case 0: System.out.println("Case 0"); case 3: System.out.println("Case 3"); case 2: System.out.println("Case 2"); case 6: System.out.println("This is the case selected.");
// After above statement under case 6 is implemented, then the
// program continues with case 5, case 9, and then the default below.
case 5: System.out.println("Case 5"); case 9: System.out.println("Case 9"); default: System.out.println("No values selected");
}
}
}

In above example, notice that we are using literals (numbers) for each case, and also notice that cases do not need to follow any particular order: in the example, case 3 is before case 2, and after case 0.

Also, after the program control goes to Case 6 above, it continues to case 5, 9 and the default. If you only want to implement only one case, then the Processor Control instruction 'break' has to be included in that case. (The 'break' instruction will be discussed under Processor Control Instructions.)

See Example using 'break':

class Exercise
{ public static void main(String[] arg)
{ int a = 6;
switch(a) // It evaluates 'a' and program continues to case 6.
{ case 1: System.out.println("Case 1");
break;
case 0: System.out.println("Case 0");
break;
case 3: System.out.println("Case 3");
break;
case 2: System.out.println("Case 2");
break;
case 6: System.out.println("This is the case selected.");
break;
// Now, after the Case 6 is implemented, by virtue of the 'break' statement,
// the control goes out of the switch construct.
case 5: System.out.println("Case 5");
break;
case 9: System.out.println("Case 9");
break;
default: System.out.println("No values selected");
break;
}
}
}

In JAVA the 'break' instruction is also used to get out of any iteration (for, while, do while loops).

Click here to go to the JAVA Mini-Course page


The BASE for JAVA LEARNING

by PRO FE S S OR


SECTION VII- Programming Flow Instructions

Iteration

ITERATION

In JAVA iteration can be accomplished by three constructs:
  • for
  • while
  • do while

  • The 'for' loop

    The 'for' loop utilizes 3 fields for controlling any iteration. It's the most powerful of all the iteration constructs in JAVA, as the programmer has more options.

    Each of the fields are separated by a semi-colon.

  • The first field is used for variable initialization.
  • The second field is used to evaluate whether it's the end of the loop or not.
  • The third field is used for manipulating variables.
  • Example of a for loop construct with 1st field: int index=0 ; 2nd field: index<10 ; 3rd field: i++ for(int index=0; index <10 ; index++)
    {System.out.println(index); }
    In the example above, index starst at zero, the program flow remains in the loop as long as index is less than 10, and every time the loop is traversed the index is incremented by one. Numbers 0 through 9 are displayed as the loop is traversed 10 times.

    Notice that within the for construct, the index was declared as an 'int'. That declaration could have been done outside the loop. If index is declared outside the loop its value reamins within the scope after the loop is implemented. If it's declared within the loop (as in the example above) then its value is only within the scope of the for loop.

    See Example below: class Exercise
    { public static void main(String[] arg)
    { int index;
    for (index=10; index>2; index--)
    { System.out.println(index); // displays from 10 down to 3 }
    System.out.println(index); // displays 2, the value from the last loop iteration

    // Notice that if the index were declared inside the for loop, the statement above
    // (which is outside the for loop) would make the program non-compilable as index
    // would then be outside scope.
    }
    }

    Let's have another example, this time using more than one variable (2 indeces) to illustrate the power of for loops. Each variable used are of different data type.
    class Exercise
    { public static void main(String[] arg)
    { int index;
    char charIndex;
    for (index=1, charIndex='A' ; index<=26; index++, charIndex++)
    { System.out.print(index + " "); // displays numbers 1 through 26
    System.out.println(charIndex); // displays the English Alphabet letters
    }
    }
    }


    The 'while' loop

    The 'while' loop evaluates a condition to decide whether or not to continue the iteration.

    It's considered an entry condition iteration, as the evaluation occurs before entering the loop. If the condition is met, it goes through the loop, otherwise it goes out of the loop.

    Example of a while loop: class Exercise
    { public static void main(String[] arg)
    { int index= 0;
    while (index<10)
    { index+= 2; // index is incremented by 2
    System.out.println(index); // displays 2, 4, 6, 8, and 10

    // If the display statement is placed before the increment statement,
    // then, it would have displayed 0, 2, 4, 6, and 8 instead.
    }
    }
    }


    The 'do while' loop

    The 'do while' loop as the 'while' loop evaluates a condition to decide whether or not to continue the iteration.

    However, it's an exit condition iteration, as the evaluation occurs after the loop. By virtue of this, the 'do while' loop is always implemented at least one time.

    Example of a 'do while' loop: class Exercise
    { public static void main(String[] arg)
    { int index= 0;
    do
    { index+= 2; // index is incremented by 2
    System.out.println(index); // displays 2, 4, 6, 8, and 10
    }
    while (index>0 && index<10); // Notice the semicolon at the end of this statement.
    }
    }

    In above example if we would have used 'while' loop instead of the 'do while' loop, the iteration would have never been exercised, as one of the conditions "index>0" would never have been met, at the entry point of the loop.


    Click here to go to the JAVA Mini-Course page



    The BASE for JAVA LEARNING

    by PRO FE S S OR


    SECTION VII- Programming Flow Instructions

    Processor Control Instructions: break and continue


    There are two Processor Control Instructions in JAVA: break and continue.


    The 'break' Instruction

    The 'break' instruction is used to exit any loop construct, or the switch construct.

    When we discussed the 'switch' construct in a previous Step, we saw that 'break' was used to exit the construct from within any case.

    In general, the 'break' instruction is implemented when the programmer wants to exit the loop for a particular condition.

    See Example below:

    class Exercise
    { public static void main(String[] arg)
    { int number=0;
    boolean flag = true;
    while (flag)
    { number++;
    if (number==10) break; System.out.println(number); // numbers 1 through 9 are displayed.
    }
    }
    }
    The program flow in above example by viretue of the 'break' instruction, exits the while loop when number is equal to 10.


    The 'continue' Instruction

    The 'continue' Instruction is used to escape one iteration of the loop.

    See Example below:

    class Exercise
    { public static void main(String[] arg)
    { int number=0;
    boolean flag = true;
    while (flag)
    { number++;
    if (number==5) continue; if (number==10) break; System.out.println(number); // displays No.s 1 through 4 and 6 through 9.
    }
    }
    }
    The program flow in above example by virtue of the 'continue' instruction, skips the iteration for number 5, and later exists the loop when number is equal to 10.


    Labels

    In JAVA, there is no 'goto' instruction. As programmers have learned over the years, the 'goto' statement can produce unstructured and inefficient code. Therefore, as JAVA was designed it was decided to eliminate the 'goto' Instruction. However, it's interesting to notice that even though the 'goto' instruction is not implemented, it cannot be used as an identifier, as JAVA would interpret it as a keyword.

    In JAVA we can use Labels. They are tags followed by a colon, and they are used for naming loops.

    They are used in conjunction with the 'break' and 'continue' instructions. The Labels are conveniently employed in case of nested loops. When placing labels, make certain they are written right at the position just before the loop starts.

    See Example below:
    class Exercise
    { public static void main(String[] arg)
    { int j=0, k=0;
    boolean flag = true;
    outerLoop: // label for this Outer Loop
    while (flag)
    { int i;
    innerLoop: // label for this Inner Loop
    for (i=1; i<10; i++)
    { if (j>39)
    { break outerLoop; }
    do
    { if (i==5) continue innerLoop; j++;
    k++;
    System.out.println(i + " " + j + " " + k);
    // i displays 1 through 9 five times each number
    // j displays 1 through 40 consecutively
    // k displays 1 through 5 repetitively
    }
    while (k<5);
    k=0;
    }
    }
    }
    }


    Click here to go to the JAVA Mini-Course page