Java Control Statement
Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of control flow statements;
- Selection statements: if, if-else and switch.
- Iteration statements: while, do-while and for.
- Transfer statements: break, continue, return, try-catch-finally and assert.
Selection Statements
The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression.
The simple if statement has the following syntax:
if (<conditional expression>)
{
<statement action>;
}
Below is an example that demonstrates conditional execution based on if statement condition.
public class IfStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } }
Output: b > a
The If-else Statement
The if-else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression.
The if-else statement has the following syntax:
if (<conditional expression>)
{
<statement action>;
}
else
{
<statement action>;
}
Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a > b"); } else { System.out.println("b > a"); } } }
Output: b > a
Nesting of if-else Statements
When a series of decisions are involved, we may have to use more than one if-else statement in nested form. The general syntax for nested if else is as follows:
if(<Conditional Statements>)
{
if(<Conditional Statement>)
{
<Statement>;
}
else
{
<Statement>;
}
}
else
{
<Statement>;
}
Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo { public static void main(String[] args) { int a = 10, b = 20, c = 30; if (a > b) { if (a > c) { System.out.println("a is greater"); } } else { if(b > c) { System.out.println("b is greater"); } else { System.out.println("c is greater"); } } } }
Output: c is greater
The Ladder if-else Statements
There is another way of putting if-else together when multi-path decisions are involved. A multipath decision is a chain of its in which the statement associated with each else is an if. It takes the following general form:
if(Condition)
{
<Statement>;
}
else if(Condition)
{
<statement>;
}
else if(Condition)
{
<Statement>;
}
else
{
<Statement>;
}
<Statement x>;
The Conditions are evaluated from top to bottom, as soon as the True condition is found, the Statement associated with it is executed and the control is transferred to the <Statement x>; (Skipping the rest of the Ladder) When all the condition becomes false, then the final else containing the default-statement will be executed.
Example:
class LadderIfElse { public static void main(String arg[]) { int marks = 85; char grade; if (marks >=90) { grade = 'A' ; } else if (marks >= 70) { grade = 'B' ; } else if (marks >= 50) { grade = 'C'; } else { grade = 'F' } System.out.print("Your Grade: " +grade); } }
The Ladder If-else gave birth to Switch Case Statement, Which is based on the working of Ladder if-else.
Switch Case Statement
The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch.
Its general form is as follows:
switch(<non-long integral expression>)
{
case label1: <statement1>
case label2: <statement2>
…
case labeln: <statementn>
default: <statement>
} // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block.
Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers.
public class SwitchCaseStatementDemo { public static void main(String[] args) { int a = 10, b = 20, c = 30; int status = -1; if(a > b && a > c) { status = 1; } else if (b > c) { status = 2; } else { status = 3; } switch(status) { case 1: System.out.println("a is the greatest"); break; case 2: System.out.println("b is the greatest"); break; case 3: System.out.println("c is the greatest"); break; default: System.out.println("Cannot be determined"); } } }
Output: c is the greatest
Iteration Statements
While Statement
The while statement is a looping construct control statement that executes a block of code while a condition is true. You can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression.
The syntax of the while loop is
while (<loop condition>)
{
<statements>;
}
Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1 to 10.
public class WhileLoopDemo { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); while (count <= 10) { System.out.print(count++); System.out.print(","); if(count==10) { System.out.println("\b"); //backspace } } } }
Output:
Printing Numbers from 1 to 10
1,2,3,4,5,6,7,8,9,10
Do-while Loop Statement
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the beginning. This ensures that the loop will be executed at least once. A do-while loop begins with the keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and the test expression completes the do-while loop. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately following the loop. You can either have a single statement or a block of code within the do-while loop.
The syntax of the do-while loop is:
do
{
<loop body>
}
while (<loop condition>);
Below is an example that demonstrates the looping construct namely do-while loop used to print numbers from 1 to 10.
public class DoWhileLoopDemo { public static void main(String[] args) { int count = 1; System.out.println("Printing Numbers from 1 to 10"); do { System.out.print(count++); System.out.print(","); if(count==10) { System.out.print("\b"); } } while (count <= 10); } }
Output:
Printing Numbers from 1 to 10
1,2,3,4,5,6,7,8,9,10
For Loops
The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a counter controlled loop.
The syntax of the loop is as follows:
for (<initialization>; <loop condition>; <increment expression>)
{
<loop body>;
}
The first part of a for statement is a starting initialization, which executes once before the loop begins. The <initialization> section can also be a comma-separated list of expression statements. The second part of a for statement is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluated as false the first time, the loop will never be executed. The third part of the for statement is the body of the loop. These are the instructions that are repeated each time the program executes the loop. The final part of the for statement is an increment expression that automatically executes after each repetition of the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the loop should continue.
All the sections in the for-header are optional. Any one of them can be left empty, but the two semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop condition is true. The (;;) form of for loop is commonly used to construct an infinite loop.
Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to 10.
public class ForLoopDemo { public static void main(String[] args) { System.out.println("Printing Numbers from 1 to 10"); for (int count = 1; count <= 10; count++) { System.out.print(count+","); if(count==10) { System.out.println("\b"); } } } }
Output:
Printing Numbers from 1 to 10
1,2,3,4,5,6,7,8,9,10
Transfer Statements
Continue Statement
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the nearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not want to exit the loop itself.
The syntax of the continue statement is
continue; // the unlabeled form
continue <label>; // the labeled form
You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops.
Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10.
public class ContinueExample { public static void main(String[] args) { System.out.println("Odd Numbers"); for (int i = 1; i <= 10; ++i) { if (i % 2 == 0) continue; // Rest of loop body skipped when i is even System.out.println(i + " "); } } }
Output:
Odd Numbers
1 3 5 7 9
Break Statement
The break statement transfers control out of the enclosing loop ( for, while, do or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure. You can also provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested loops.
The Syntax for break statement is as shown below;
break; // the unlabeled form
break <label>; // the labeled form
Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.
public class BreakExample { public static void main(String[] args) { System.out.println("Numbers 1 - 10"); for (int i = 1;; ++i) { if (i == 11) break; // Rest of loop body skipped when i is 11 System.out.println(i + " "); } } }
Output:
Numbers 1 - 10
1 2 3 4 5 6 7 8 9 10
Like It? Share It
0 comments:
Popular Posts
-
It's been about three years since Microsoft unveiled a new version of Office, and particularly with Windows 8 just months away from ...
-
There's general agreement that Sony stumbled out of the gate with the PlayStation 3. Months of intense hype were followed by a la...
-
Latest Windows Phone 8 rumor suggests that current Windows Phone devices will receive the update Microsoft has yet to come forward wi...
-
Microsoft is holding an invitation-only press event in San Francisco today at which it is expected to debut the next version of its...
-
Gaming & Gadgets Microsoft kick-started the "next-generation" of gaming on November 22, 2005, when the company release...