As I told in a previous post selection statements control the execution of the program. There are two selection statemens, if and switch.
IF
The simplest form of if is this
If(condition) Statement
If there is only one statement the code is fine like this but if there are more than one you neet to put the curly braces like that
If(condition) { Statement1; Statement2; }
The condition can be any expression that return a Boolean value like true o false.
If you want to do something if the condition is not true you can use else like this:
If(condition) { Statement1; Statement2; } else { Statement3 }
Here how it works: if the condition is true, the program will execute statement1 and statement2 while if the condition is false, the program will execute statement3.
There is also a way to check for more than one condition, like this:
If(condition1) { Statement1; Statement2; } else If(condition2) { Statement3; Statement4; } else { Statement5 }
If the condition1 is true execute statement1 and statement2, if condition1 is false check condition2 and if this is true execute statement3 and statement4, if also condition2 is false, execute statement5.
The if statements can be also written in a nested way:
If(condition1) { Statement1; If(condition2) { Statement3; Statement4; } else { Statement5 } Statement2; }
In this way you can check for a certain condition inside another if statement.
Switch
In one of the previous example you can see multiple if…else statement one after another to check for multiple conditions. Java, like many other programming languages, provide a better alternative, the switch . Whit this you can compare the value of an expression with the values of multiple cases:
switch(expression) { case val1: statement1 break; case val2: statement2 break; case val3: statement3 break; default: statement }
So, the expression is compared with each case, when a match is found the statement of that case is executed. Note the break at the end of each statement; it tells the program to exit from the switch statement and continue the rest of the program. The default case tells what to do when no other case above match the expression.
1 Comment
Java Control Statements - bSteatus · October 7, 2017 at 1:15 pm
[…] Selection statement control the execution of the program based on certain conditions. Selection statements are if and switch. […]