Basically, Java will support two selection statements which include: IF statement and switch statement, these statements will allow to control the flow of our program execution which is based upon conditions which are known only during run time.
IF statement:
IF statement is basically the Java’s conditional branch statement which can be used to route the program execution through two different paths.
Syntax for if statement is:
If(condition)
statement1;
else
statement2;
- Each statement will be a single statement or may be compound statement enclosed in the curly braces.
- Condition will be any expression which will return Boolean value
- Else clause is optional
IF statement will work like this: suppose IF condition is true then statement1 will be executed else statement2 will be executed, in the no case will both statements will be executed.
Let us consider an example:
Int a, b;
// …..
If(a<b)
a=0;
Else
b=0;
- if a is less than b then a is set to zero else
- b is set to zero
- in no case both a & b will be set to zero.
2. Nested IF statement:
Nested IF statements are very common in the programming. When we nest IF, main thing to remember is to that else statement will always refer to the nearest or latest IF statement, that is within same block as the else and that is not associated with else.
Let us consider an example: If ( i == 10) { If (j < 20 ) a = b; If(k > 100) c = d; Else a = c; }
This indicates final else is not associated with if(j < 20) because its not in the same block, final else will be associated with if(k>100) because its closest to IF within the same block.
SWITCH statement:
SWITCH is the multiway branch statement which provides easy way to dispatch execution to the different parts of our code which is based on the value of an expression.
Syntax of SWITCH statement is:
Switch(expression) { Case value1: // statement sequence Break; Case value2: //statement sequence Break; . . . . Case valueN. // statement sequence Break; Default: // default statement sequence }
Expression must be type byte, short, int or char each of the value will be specified in the case statements must be type compatible with the expression, here each case will be unique.
Let us consider an example:
Class simpleswitch { Public static void main (string args []) { Switch(i) { Case 0: System.out.println(“I is zero”); Break; Case 1: System.out.println(“I is one”); Break; Default: System.out.println(“I is greater than 2”); } } }
Output
I is zero
I is one
I is greater than 2
As we can see each time through the loop the statements will be associated with the case constant which will match I are executed rest all are bypassed.After I is greater than 2 no case statement I are executed
Questions:
- What is selection statement?
- Explain IF statement with program
- Explain SWITCH statement with program