learn more...Like other programming languages java offers the control statements to control the execution of a program. The control statements in java are the selection statements, loop constructs and the jumping statements. The selection statements define the route of the execution considering different conditions. Loops control the iteration of one of more statements within a program considering specific conditions. And the jumping statements are used to jump from the regular sequential control of program to the user chosen path.
The selection statements in java are used to choose the path of the execution of the program considering different conditions. If one condition is found true the program may follow another route and if it is not, the program may follow a different path. So considering different conditions the execution of the program is defined, so as to get the results as intended by the programmer. Java offers two control statements, which are:
Both of them are used for controlling the execution path but they have their own limitations. So we study both of them in detail.
1. IF STATEMENT:
The simple if statement is very simple to understand. It checks out a condition, and if finds it true, it executes the if block statements, otherwise not. The if statements are executed if and only if the condition is true. Lets check its syntax.
if (condition ) statement ;
Now this statement is the if statement, and it would run only if the condition is true. The statement just following the if (condition) is the if statement. This is the statement that is controlled by the condition. If the programmer wants to add more statements than one, a block of statements is needed. All the statements in that block are then said to be in if block and are controlled by the if's condition. It would looks like:
if ( condition ) { statement 1; ...... .. statement n; }
Another variation in the if statement is the else clause. The else clause is used as the part of the if statement; if a programmer needs to give an alternative path i.e. what if the condition is not true? In normal execution if the condition is not true the control comes to the next statement after the if statement and nothing happens. But adding the else clause one can give an alternative route, as what should be done if the condition is not true. Its syntax is like:
if ( condition ) { statement 1; ...... .. statement 10; } else statement 11;
Now if the condition is true, the if block would be executed i.e. statements from 1 to 10. But if the condition is false, the control won't jump out of if statement, the statement of else would execute i.e. statement 11. Just like the if block one can add more statements in the else by creating a block of statements.
if ( condition ) { statement 1; ...... .. statement 10; } else { statement 11; ...... .. statement 15; }
Lets check this fragment of code for a clear understanding of the else if structure.
if( a > b) { System.out.println("A = " + a + "\tB = " + b); System.out.print("A is greater than B"); } else { System.out.print("A = " + a + "\tB = " + b); System.out.print("Either both are equal or B is greater"); }
Now in this case if a is greater than b, the if block would execute, if it is false the else block would execute. The point to notice is that in no case would both of the blocks execute. What ever the values of A and B may be, but the path of execution will be either one of them, not both.
Normally the if condition involves relational operators, thus creating a boolean expression resulting in true or false. But an exception to using the boolean expression is using the boolean variable. The value of the boolean operator than controls the if statement. Lets check it.
boolean val = true; if (val ) System.out.println("value is true");
Normally simple boolean expressions are used for the if conditions, but we can use more logical and complex boolean expressions too. For example
if (a > 0 && a < =10 ) System.out.println("a is a positive value from 1 to 10.");
Sometimes we have more than one choices to consider. It means that instead of checking one condition for following a path with an alternative, we can check more than one conditions too. This is done by the usage of if else if ladder. In this case the "else if" clause also contains the condition, which is checked and if it gets true, the else block is executed. We can add as many "else if" clauses, as we need. And at the end, if we want a default execution path, we can specify an else without condition. Its syntax is like:
if (condition) Statement 1;
else if (condition ) Statement 2;
else if (condition ) Statement 3;
else Statement 4;
In this case, first of all the if statement would be checked, if it gets true, no other else clauses would be checked. If it gets to be false, the next 'else if' clause is checked and is executed if true or passed if false. This keeps going till the last 'else if' clause. The last else clause without condition is optional i.e. it is executed when no other condition comes out to be true. Now lets check an example for a complete concept.
Example: If Statement
class Example4_1{ public static void main (String Args[]){
int a = 5; boolean val = false;
if(val) System.out.println("val is false, so it won't execute";
else if (a < 0 ) System.out.println("A is a negative value");
else if (a > 0) System.out.println("A is a positive value");
else System.out.println("A is equal to zero"); } }
Nested if statements: When the if statements get more complex than instead of making difficult boolean conditions, we can use the nested if statements. The nested if statements are very easy to understand. One or more if statements are used within another if's block. It means that the control comes to the inner if statement only and only if the outer if statement is true. Its syntax would look like:
if (condition) { if ( condition) Statement; else Statement; } else Statement;
The nested if statements are normally used to check two conditions instead of one. And the inner if statement executes when the outer if statement is true. Lets check an example for this.
Example: Nested If Statements
class Example4_2{ public static void main(String Args[]){
int a = 3;
if (a <= 10 && a > 0) { System.out.print("Number is valid."); if ( a < 5) System.out.println("From 1 to 5"); else System.out.println("From 5 to 10"); } else System.out.print("Number is not valid"); } }
2. SWITCH STATEMENT:
The switch statement of java is another selection statement that defines different paths of execution for a program. The right path is then chosen by the case value matching that of the original expression to be checked. It is often a better alternative to the if else if ladder. It is more efficient that the if statement. But its area of implementation is quite limited. Check out the syntax of a switch statement.
switch (expression){ case value1: statements; [break;]
case value2: statements; [break;]
--- --- --- case valueN: statements; [break;]
default: statements; [break;] }
The expression must be of type int, short, byte or char. The selection in the switch statement is determined by the values between the parenthesis after the keyword switch and the expression. Possible switch positions are defined by one or not case values using the keyword case. The type of the case values must match with the type of the expression. And each case value should be a unique literal. It means that no duplicate values are allowed and the value must be a literal not a variable.
The working of the switch statement is very simple. The value of the expression is compared with each of the case values. It ignores the cases that do not match and executes the statements that are defined under the matching case. If no case matches the default statements are executed. The default statements are optional. If no case matches and a default statement is present it would execute, otherwise no action would be taken.
One thing that limits the working of the switch statement as compared to the if statement is that the if statement works on a boolean expression. The if statement evaluates the boolean expression and executes if the result is true and does not if the value is false. But in case of the switch statement it only takes the int, short, byte and char expressions and checks it against their case constants for equality. The switch statement can not work on other logical operators expect the equality.
The break statement is used in each sequence case value statements to terminate this sequence i.e. a break statement shows that the sequence for this case value ends up here. When the control comes to a break statement, it jumps from that point to the end of the switch statement and executes the first statement after the switch statement. Lets check out an example.
Example: Switch statement
class Example4_3{ public static void main(String Args[]){
int month = 3;
switch (month){
case 1: System.out.println("The month of January"); break;
case 2: System.out.println("The month of February"); break;
case 3: System.out.println("The month of March"); break;
case 4: System.out.println("The month of April"); break;
case 5: System.out.println("The month of May"); break;
case 6: System.out.println("The month of June"); break;
case 7: System.out.println("The month of July"); break;
case 8: System.out.println("The month of August"); break;
case 9: System.out.println("The month of September"); break;
case 10: System.out.println("The month of October"); break;
case 11: System.out.println("The month of November"); break;
case 12: System.out.println("The month of December"); break;
default: System.out.println("Invalid month"); } } }
The output of this program would be
The month of March
The break statement is optional in the switch statement. If the break statement is omitted the execution of the statement sequence does not stop and carries on to the next case and continues until encounters a break statement or till the end of switch. Sometime the break statements are intentionally omitted to get the desired results. Check the following fragment of code.
switch (alph){ case 'a': case 'e': case 'i': case 'o': case 'u': System.out.println("Character is a vowel"); break;
default: System.out.println("Character is not a vowel"); }
Now in this code the execution of each case falls down until a break statement is encountered. Thus the String "Character is a vowel", would print in all the above five cases. Lets check out an example for this special case of omitting break statement in switch.
Example: Switch statement - omitting break
class Example4_4{ public static void main(String Args[]){
int a = 5;
switch(a){ case 0: case 1: case 2: case 3: case 4: case 5: System.out.println("Value is either 5 or less"); break; case 6: case 7: case 8: case 9: case 10: System.out.println("Value is greater than 5 and less than 11"); break;
default: System.out.println("Value is either less than 0 or greater than 10");
} } }
Nested switch: Switch can be used in the statement sequence of a case value in another switch statement. This is called a nested switch statement. Each switch statement defines its own block by specifying a parenthesis, so the values of the inner switch and the outer switch never conflict. A nested switch is more efficient than nested if statements. The syntax would be:
switch(expression){ case 1: statements; switch(expression){ case 1: statements; break; case 2: statements; break; default: statements; } break;
case N: statements; break;
default: Statements; }
In the nested switch statements the case 1 of the outer switch never conflicts with the case 1 of the inner switch. The outer case is checked for equality against the outer expression and the inner case is checked against the expression of the inner switch, and the parenthesis separate both of them. Lets check an example for the nested switch.
Example: Nested Switch Statements
class Example4_5{ public static void main(String Args[]){
int x = 1, y = -1;
switch(x){
case 1: switch(y){ case 1: System.out.println("First Quadrant 1, 1"); break; case -1: System.out.println("Second Quadrant 1, -1"); break; default: System.out.println("invalid"); } break;
case -1: switch(y){ case 1: System.out.println("Third Quadrant -1, 1"); break; case -1: System.out.println("Fourth Quadrant -1, -1"); break; default: System.out.println("invalid"); } break;
default: System.out.println("Invalide");
} } }
|
||||||
Disclaimer
1) E-articles is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringement, please read the terms of service and contact us to investigate the problem.
2) E-articles is not responsible for inaccuracies, falsehoods, or any other types of misinformation this article may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. link to this article |