Saturday, August 16, 2014

Java Control Statements

Control flow statements are divided into 3-categories.:
  • Decision making
  • Loop statements
  • Jump statements
Decision- making
It is used when programmer wants to control the order in which the statements  will be executed.
if-else statement
if(condition)
   {
     action1;
   }else
   {
     action2;
   } 
  • condition - It return true or false;
  • action1 - It is statement executed when if returns true.
  • else - It is optional keyword that specifies  statement will executed when if condition return false.
  • action2 - It is statement executed when if returns false.
Switch Case Statement
It is an alternative for if-else if statement.If the programmer has to make a number of decisions and all the decision depends on the value of same variable, then switch-case is used.
switch (expression <x>)
{
  case condition1:
    statement1;
    break;
  case condition2:
    statement2;
    break;
  case condition3:
    statement3;
    break;
  ...
  case condtionN:
    statementN;
    break;
  default:
    default statement;
}
  • expression <x>- It is variable containing the value to be evaluated.
  • condition<x> : are conditions which should match to expression for that case to execute.
  • statement<x> : statement executed in case of the condition is matched.
  • break : It is used to terminate the switch case, once the expression is executed.
  • default: It is executed when all the case  statement evaluate to false.
Loop Statement
Loop statement are used in iterations. For example do certain things for n number of times or till some condition is satisfied.
while loop
It executes the steps mentioned in the loop only if the condition is true.
while (condition)
  {
    <statement>;
    ...
  }
  • condition - It is  a Boolean expression that return a true or a false  value.
  • statement - These execute if the condition is true.
do-while loop
This loop executes at least once,even the condition is false.
do{
   action statement;
   ...
  }while(condition);
for loop
for(<initialization>;<condition>;<increment/decrement>)
  {
    <statement>;
  }
  • initialization - Set the value of counter.
  • condition - Returns true/false. If true the loop continues else the loop is terminated.
  • increment/decrement - modifies the counter value.
Jump Statements
  • break - breaks the loop whenever it is called.
  • continue- Aborts current iteration of loop and goes to the next iteration.

No comments:

Post a Comment