Wednesday, November 13, 2013

Flow Controls - Jump Statements

java supports three jump statements : break, continue, and return,These statements transfer control to another part of your program, Each is examined here.

Note: in additional to the jump statements discussed here, java supports one other way by which you can change your program flow of execution, through exception handling,Exception handling provides a structured method by which run-time error can be trapped and handled by your program, it is supported by the keywords try, catch ,throw , throws and finally 

Using break 

in java the break statement has three users, First, as you have seen, it terminates a statement sequence in a switch statement, Second, it can be used to exit a loop, Third it can be used ad a "civilized " form of goto. the last two uses are explained here,

Using break to exit a loop 

By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop, when a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop
class UsingBreak {

    public static void main(String[] args) throws IOException {

       for(int i=0; i<100; i++){
           if (i==10) break;
           System.out.println("i is :"+i);
       }
        System.out.println("loop Complete.");
    }
}
OUTPUT 
i is :0
i is :1
i is :2
i is :3
i is :4
i is :5
i is :6
i is :7
i is :8
i is :9

loop Complete.

As you can see, although the for loop is designed to run form 0 to 99 the break statement causes it to terminated early, when i equals 10
the break statement can be used with any of java's loop, including intentionally infinite loops for example here is the preceding program coded by use of while loop, The output if this is the same as just shown
class UsingBreak {

    public static void main(String[] args) throws IOException {
        int i = 0;
        while (i<100) {
            if (i == 10) break;
            System.out.println("i is :" + i);
            i++;
        }
        System.out.println("loop Complete.");
    }
}
When used inside a set of nested loop, the break statement will only break out of the innermost loop.
class UsingBreak {

    public static void main(String[] args) throws IOException {
        for(int i =0; i<3; i++){
            System.out.print("pass "+i+" : ");
            for(int j=0; j<100; j++){
                if(j==10)break;
                System.out.print(j+" ");
            }
            System.out.println("");
        }
        System.out.println("Loops Complete.");
    }
}
OUTPUT
pass 0 : 0 1 2 3 4 5 6 7 8 9 
pass 1 : 0 1 2 3 4 5 6 7 8 9 
pass 2 : 0 1 2 3 4 5 6 7 8 9 

Loops Complete.

As you can see, the break statement in the inner loop only causes termination of the loop, the outer loop is unaffected,
Here are two other points to remember about break, first more then one break may appear in a loop.
However be careful too many break statements have the tendency to restructure you code, Second the break, that terminates a switch statement affects only the switch statement and not any enclosing loop.

Using continue

Sometime it is useful to force an early iteration of a loop that is, you might to continue running the loop but stop processing the remainder of the code in its body for this particular iteration, this is, in effect, a goto just past the body of the loop, to the loop's end the continue statement performs such an action. In while and do while loops a continue statement causes control to be transferred directly to the conditional expression that controls the loop, in a for loop , control goes first to the iteration portion of the for statement and then to the conditional expression, for statement loops. any intermediate code is by passed, 
Here is an example program that uses continue to cause two numbers to be printed on each line: this code use the % operator to check if i is even, if it is the loop continues without printing a new line .
class UsingContinue {

    public static void main(String[] args) throws IOException {
        for(int i=0; i<10; i++){
            System.out.print(i+" ");
            if(i%2 == 0)continue;
            System.out.println("");
        }
    }
}
OUTPUT
0 1 
2 3 
4 5 
6 7 

8 9 

return 

The return statement is used to explicitly return from a method. That is it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. Although for a full discussion of return, You must until methods are discussed, we present a brief look at return, 
At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed, The following examples illustrates this point. Here return causes execution to return to the java run-time system,Since it is the run time system that calls main method (  public static void main(String[] args) )
class UsingReturn {

    public static void main(String[] args) throws IOException {
        boolean t = true;
        System.out.println("Befor the return ");
        if(t) return;
        System.out.println("this is not executed");
    }
}

Monday, November 11, 2013

Flow Controls - for Loop

General form of the traditional for statement :
for( initialization; condition; iteration ){
               // body
}
if only one statements is being repeated, there is no need for the curly braces.
The for loop operates as follows. when the loop first starts, the initialization portion of the loop is executed.Generally , this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop. it is important to understand that the initialization expression is only executed once, Next condition is evaluated, this must be a boolean expression, it usually tests loop control variable against a target value, if this expression is true , then the body of the loop is executed, if it is false, the loop terminates. next the iteration portion of the loop is executed. this is usually an expression that increments or decrements the loop control variable, the loop then iterates, first evaluation the conditional expression, then executing the body of the loop , and then executing the iteration expression with each pass, this process repeats until the controlling expression is false.
here is a version of the "tick " program that uses a for loop.

Declaring Loop Control variables inside the for loop

class ForLoopTest {

    public static void main(String[] args) throws IOException {
     
        int n;
        for(n=10; n>0; n--){
            System.out.println("tick "+n);
        }
    }
}
Often the variable that controls a for loop is only needed for the purpose 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 example, here is the preceding program re-coded so that the loop control variable n is declared as an int inside the for:
when you declare a variable inside a for loop, there is one important point to remember, the scope of the
class ForLoopTest {

    public static void main(String[] args) throws IOException {
     
        for(int n=10; n>0; n--){
            System.out.println("tick "+n);
        }
    }
}
variable ends when the for statement does, (that is, the scope of the variable is limited to the for loop) Outside the for loop, the variable will cease to exist, if you need to use the loop control variable elsewhere in your program, you will not be able to do it inside the for loop.
when the loop control variable will not be needed elsewhere, most java programmers declare it inside the for.EX : the following program tests for prime numbers Notice that the loop control variable, i is declared inside the for since it is not needed elsewhere,
class ForLoopTest {

    public static void main(String[] args) throws IOException {

        int num;
        boolean isPrime = true;
        num = 14;
        for (int i = 2; i < num / i; i++) {
            if ((num % i) == 0) {
                isPrime = false;
                break;
            }

            if (isPrime) {
                System.out.println("Prime");
            } else {
                System.out.println("Not Prime");
            }
        }
    }
}
The for loop supports a number of variation that increases its power and applicability. The reason it is so flexible is that its three parts, the initialization, the conditional test, and the iteration, do not need to be used for only those purposes, In fact, the three sections of the for can be used for any purpose you desire, Let's look at some examples.
One of the most common variations involves the conditional expression, Specifically , this expression does not need to test the loop control variable against some target value. In fact, the condition controlling the for can be any boolean expression.

class ForLoopTest {

    public static void main(String[] args) throws IOException {

       boolean done = false;
       for(int i = 10; done; i++){
           if(i==5) done =false;
       }
     
    }
}
Here, the for loop continues to run until the boolean variable done is set true, it does not test the value of i.
Here is another interesting for loop variation, either the initialization or the iteration expression or both may be absent, as in this next program.
class ForLoopTest {

    public static void main(String[] args) throws IOException {

        int i;
        boolean done = false;
        i = 0;
        for (; !done;) {
            System.out.println("i is :" + i);
            if (i == 10) {
                done = true;
            }
            i++;
        }
    }
}
Here, the initialization and iteration expressions have been moved out of the for, thus, parts of the for are empty while this is of no value in this simple example indeed, it would be considered quite poor style there can be times when this type of approach makes sense ,
Eg :- if the initial condition is set through a complex expression elsewhere in the program or if the loop control variable changes in a non sequential manner determined by actions that occur within the body of the loop, it may be appropriate to leave these the for empty.
Here us one more for loop variation, You can intentionally create an infinite loop (a loop that never terminates ) if you leave there parts if the for empty.
Eg:
for( ; ; ){
          // body
}

Nested loops 

like all other programming languages, Java allows loops to be nested, that is one loop may be inside another

class ForLoopTest {

    public static void main(String[] args) throws IOException {

        int i,j;
        for(i=0; i<10; i++){
            for (j=i; j<10; j++){
                System.out.print(".");
            }
             System.out.println("");
        }
    }
}
Output
..........
.........
........
.......
......
.....
....
...
..

.


Saturday, November 9, 2013

Flow Controls - do while loop

As you just saw, if the conditional expression controlling a while loop in initially false, then the body of the loop will not be executed all However, sometime it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with, In other words, there are times when you would like to test the termination expression at the end of the loop rather then at the beginning, Fortunately, java has a loop that does that : the do while loop the do while loop always executes its body at least one, because its conditional expression is at the bottom of the loop. its general form is
do {
      // body
}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, here is a reworked version of the "tick " program that demonstrates the do while loop.
class Dowhile{
            public static void main(String args[]){
                          int n = 10;
                          do {
                                       System.out.println("tick "+n);
                                       n--;
                           }while (n > 0);
                       
           }
}
It generates the same output as before. The loop in the above program, while technically correct, can be written efficiently as follows;
do {
           System.out.println("tick "+ n);
}while(--n >0 );
Here, the expression (--n >0) combines the decrements of n and the test for zero into one expression, here is how it works, First, the --n statement executes, decrements n and return the new value of n. this value is then compared with zero,  the loop continues, otherwise it terminates, a menu selection, because you will usually want the body of a menu loop to execute at least once, Consider the following example
class Menu {

    public static void main(String[] args) throws IOException {
        char c;
        do {
            System.out.println("Your name");
            System.out.println("Jone ");
            System.out.println("karina");
            System.out.println("max");
            System.out.println("chose one :");
            c = (char) System.in.read();
        } while (c < '1' || c > '3');
        System.out.println("\n");
        switch (c) {
            case '1':
                System.out.println("My Name is Jone");
                break;
            case '2':
                System.out.println("My Name is Karina ");
                break;
            case '3':
                System.out.println("My name is max");
        }
    }
}

Output 
Your name
Jone
karina
max
chose one :
1

My Name is Jone

In the program, the do while loop is used to verify that the user has entered a valid choice if not, then the user is re prompted. Sine the menu must be displayed  at least once, the do while is the perfect loop to accomplish this
A few other points about this example Notice that characters are read from the keyboard by calling System.in.read(); this is one of java's console input functions, Although java's console I/O methods won't be discussed till the later System.in.read(); is used here to obtain the user;s choice it reads characters form standard input ( returned as integers, which is why the return value was cast to char ) . By default. standard input is line buffered, so you must press ENTER before any characters that you type will be sent to you program.java's console input can be a bit awkward to work with. Further. most real world program and applets will be graphical and window based For these reasons, not much use of console input has been made in this However , is is useful in this context point to consider because System.in.read(); is being used, the program must specify the throw java.io.IOException clause, This line is necessary to handle input errors, it is part Java's exception handling features, which are discussed later.