Monday, 5 September 2011

Java: Some Other Control Statements

    I'll probably start updating daily, at least for a while, while I have the time to do so.

    Remember our control statements? If and while? Well, turns out, there's some more. Namely the For and Switch statements.

For Loops
    These are used mostly for counted iteration, which is when a counter variable controls how many times a loop carries through. Here's an example:


for ( int i = 1; i < 10; i++ ){
    //Loop body here
}


    Here we have the delcaration of the for loop, followed by the initialization of a counter at 1. The loop carries on until the second statement is no longer true, modifying the counter by the 3rd statement each iteration. So, in this case, there will be 9 iterations of the loop.


Switch Statements
    Switch statements offer a way to select one or more statement sequences from among an unlimited number. It's often used when the use of "if" statements becomes too cumbersome, in large amounts. Have an example!

switch ( n ) {
    case 1:
        //Action if n == 1
    case 2:
        //Action is n==2
    ...
    default:
        //action to take if no cases match
        break;
}


    The switch statement starts with the keyword, switch, followed by some expression as a parameter, and then a compound statement to form the body. Inside the body are a series of labels marked with "case",  each of which is followed with an integer value, a colon, and then the statements contained within.

   When a switch is executed, it evaluates the parameter (must be an integer!), then jumps to the case label that contains that value to execute the statements within. You should normally end each of these labelled sets of statements with "break;", which breaks out of the current loop (ie, the switch statement altogether, continuing with the program). If no labels are matched, the default case is used instead.

That's all for now, folks! Comment, Follow and all that jazz.

2 comments:

  1. It seems like these control statements are common amongst different languages - like "if- & then-" and "if- & of-" for example.

    ReplyDelete
  2. They are. A lot of stuff is shared between languages, main differences tending to be syntax, but the base building blocks are more or less the same.

    ReplyDelete