Control statements

Control statements:
The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code.
For example, let's say that you are making a program for a bank. If someone wants to see his records, and gives his password, you don't always want to let him see the records. First, you need to see if his password is correct. You then create a control statement saying "if" the password is correct, then run the code to let him see the records. "else" run the code for people who enter the wrong password. You can even put one control statement inside another.
There are three main categories of control flow statements; -
· Selection statements: if, if-else and switch
· Loop statements: while, do-while and for
· Jump statements: break, continue, return
Selection Statements:
Selection statements are used in a program to choose different paths of execution based upon the outcome of an expression or the state of a variable.
* 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.
Prinipal Forms: -
if (condition)
statement;
if (condition)
statement;
public class IfStatement {
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-then-else Statement: -
The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.
Example: - class IfElse{
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
Output: -
Grade = C
* Switch Case : - 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:
public class SwitchCase {
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
Loop statements:
In computer science, control flow (or alternatively, flow of control) refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.
Within an imperative programming language, a control flow statement is a statement whose execution results in a choice being made as to which of two or more paths should be followed. For non-strict functional languages, functions and language constructs exist to achieve the same result, but they are not necessarily called control flow statements.
Imagine you have to write a program which performs a repetitive task such as printing 1 to 100. Coding 100 lines to do this would be mundane. There has to be an easier way, right? This is where loops come into the picture. Loops are specifically designed to perform repetitive tasks with one set of code. Loops save a lot of time.
There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the following three loops: -
1. while Loop
2. do...while Loop
3. for Loop
1. The while Loop: -
The while loop works differently than the for loop. The for loop repeats a segment of code a specific number of times, while the while loop repeats a segment of code an unknown number of times. The code within a while loop will execute while the specified condition is true.
Example: -
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
2. The do...while Loop: -
The do-while loop is very similar to the while loop, but it does things in reverse order. The while loop - while a condition is true, perform a certain action, the do-while loop - perform a certain action while a condition is true. Also, the code within a do-while loop will always execute at least once, even if the specified condition is false. This is because the code is executed before the condition is tested.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
3. The for Loop: -
The for loop is used to repeat a task a set number of times. It has three parts.
* variable declaration - Initializes the variable at the beginning of the loop to some value. This value is the starting point of the loop.
* condition - Decides whether the loop will continue running or not. While this condition is true, the loop will continue running. Once the condition becomes false, the loop will stop running.
* increment statement - The part of the loop that changes the value of the variable created in the variable declaration part of the loop. The increment statement is the part of the loop which will eventually stop the loop from running.
Example: -
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Preventing endless loops:
A necessary precaution when working with a loop is to make sure that the loop is not endless. To prevent endless loops, you need to ensure that the condition in a loop will eventually become false.
Jump Statements
Jump statements can be used to modify the behavior of conditional and iterative statements. Jump statements allow you to exit a loop, start the next iteration of a loop, or explicitly transfer program control to a specified location in your program.
Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program.
1. break.
2. continue.
3. return.
1. The break statement: -
* This statement is used to jump out of a loop.
* Break statement was previously used in switch – case statements.
* On encountering a break statement within a loop, the execution continues with the next statement outside the loop.
* The remaining statements which are after the break and within the loop are skipped.
* Break statement can also be used with the label of a statement.
* A statement can be labeled as follows.
statementName : SomeJavaStatement
* When we use break statement along with label as
break statementName;
Example: -
class break1
{
public static void main(String args[])
{
int i = 1;
while (i<=10)
{
System.out.println("\n" + i);
i++;
if (i==5)
{
break;
}
}
}
}
Output : -
1
2
3
4
2. Continue statement
* This statement is used only within looping statements.
* When the continue statement is encountered, the next iteration starts.
* The remaining statements in the loop are skipped. The execution starts from the top of loop again.
Example: -
class continue1
{
public static void main(String args[])
{
for (int i=1; i<1=0; i++)
{
if (i%2 == 0)
continue;
System.out.println("\n" + i);
}
}
}
Output : -
1
3
5
7
9
3. The return statement: -
* The last control statement is 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.
* the return statement immediately terminates the method in which it is executed.
class Return1
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t)
return; // return to caller
System.out.println("This won't execute.");
}
}
Output : -
Before the return
Label: -
Labels are the destinations of GOTO statements as well as the ON_ERROR and ON_IOERROR procedures. The label field is simply an identifier followed by a colon. Label identifiers, as with variable names, consist of 1 to 15 alphanumeric characters, and are case insensitive. The dollar sign ($) and underscore (_) characters can appear after the first character. Some examples of labels are as follows.
public class BreakContinueWithLabel {
public static void main(String args[]) {
int[] numbers= new int[]{100,18,21,30};
//Outer loop checks if number is multiple of 2
OUTER: //outer label
for(int i = 0; i if(i % 2 == 0){
System.out.println("Odd number: " + i + ", continue from OUTER label");
continue OUTER;
}
INNER:
for(int j = 0; j System.out.println("Even number: " + i + ", break from INNER label");
break INNER;
}
}
}
}
Output:
Odd number: 0, continue from OUTER label
Even number: 1, break from INNER label
Odd number: 2, continue from OUTER label
Even number: 3, break from INNER label


Free Web Hosting