Saturday 3 August 2013

16:if, if-else, switch

Learning Objectives
After completing this session, you will be able to:
‰  Use decision control structures (if, if-else, switch), which allows selection of specific
sections of code to be executed.
Control Structures
Control structures allows you to change the ordering of how the statements in your programs are
executed
Two types of control structures are:
‰  Decision control structures: Allows you to select specific sections of code to be
executed
‰  Repetition control structures: Allows you to execute specific sections of the code a
number of times.
Decision Control Structures
Decision control structures are Java statements that allows you to select and execute specific
blocks of code while skipping other sections
Types of decision control structures are:
‰  if-statement
‰  if-else-statement
‰  if-else if-statement
if-statement
if-statement specifies that a statement (or block of code) will be executed if and only if a certain
boolean statement is true.
if-statement has the form:
if( boolean_expression )
statement
or
if( boolean_expression ){
statement1;
statement2;
}
where boolean_expression is either a boolean expression or boolean variable.
 if-statement Flowchart
The following figure shows the flowchart of an if statement:

Examples of if-statement
Example 1:
int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");
Example 2:
int grade = 68;
if( grade > 60 ) {
System.out.println("Congratulations!");
System.out.println("You passed!");
}
Coding Guidelines
‰  The boolean_expression part of a statementshould evaluate to a boolean value,
which means that the execution of the condition should either result to a value of true
or a false.
‰  Indent the statements inside the if-block.
‰  For example,
if( boolean_expression ) {
//statement1;
//statement2;
}
if-else Statement
‰  if-else statement is used when you want to execute a certain statement if a condition is
true, and a different statement if the condition is false.
‰  if-else statement has the form:
if( boolean_expression ) {
statement1;
statement2;
. . .
}
else {
statement3;
statement4;
. . .
}
if-else Flowchart
The following figure shows the flowchart of an if-else statement:
Examples of if-else Statement
Example 1:
int grade = 68;
if( grade > 60 )
System.out.println("Congratulations!");
else
System.out.println("Sorry you failed");
Example 2:
int grade = 68;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println(“You passed!");
}
else{
System.out.println("Sorry you failed");
}
Coding Guidelines
‰  To avoid confusion, always place the statement or statements of an if or if-else block
inside brackets {}.
‰  You can have nested if-else blocks. This means that you can have other if-else blocks
inside another if-else block.
‰  For example,
if( boolean_expression ){
if( boolean_expression ){
//some statements here
}
}
else{
//some statements here
}
if-else-else if Statement
‰  The statement in the else-clause of an if-else block can be another if-else structure.
‰  This cascading of structures allows you to make more complex selections.
‰  The statement has the form:
if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else
statement3;
if-else-else if Flowchart
The following figure shows the flowchart of an if-else-else if statement


Example of if-else-else if Statement
Example:
int grade = 68;
if( grade > 90 ){
System.out.println("Very good!");
}
else if (grade > 60){
System.out.println("Good");
}
else{
System.out.println("Sorry you failed");
}
Common Errors
The condition inside the if-statement does not evaluate to a booleanvalue,
for example,
//WRONG
int number = 0;
if( number ) {
//some statements here
}
The variable numberdoes not hold a booleanvalue.
Writing elseif instead of else if
Using = instead of == for comparison.
For example,
//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}
This should be written as,
//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}
Sample Program
1 public class Grade {
public static void main( String[] args )
{
4 double grade = 92.0;
5 if( grade >= 90 ){
6 System.out.println( "Excellent!" );
7 }
8 else if( (grade < 90) && (grade >= 80)){
9 System.out.println("Good job!" );
10 }
11 else if( (grade < 80) && (grade >= 60)){
12 System.out.println("Study harder!" );
13 }
14 else{
15 System.out.println("Sorry, you failed.");
16 }
17 }
18 }
switch Statement
switch allows branching on multiple outcomes
switch statement has the form:
switch( switch_expression ){
case case_selector1:
statement1;//
statement2;//block 1
break;
case case_selector2:
statement1;//
statement2;//block 2
break;
:
default:
statement1;//
statement2;//block n
}
where:
switch_expression is an integer or character expression
case_selector1, case_selector2 and so on, are unique integer or character constants
When a switch is encountered:
‰  Java first evaluates the switch_expression, and jumps to the case whose selector
matches the value of the expression.
‰  The program executes the statements in order from that point on until a break
statement is encountered, skipping then to the first statement after the end of the
switch structure.
‰  If none of the cases are satisfied, then the default block is executed. Take note
however, that the default part is optional.
Note:
‰  Unlike with the if statement, the multiplestatements are executed in the switch
statement without needing the curly braces.
‰  When a case in a switch statement has been matched, all the statements associated
with that case are executed. Not only that, the statements associated with the
succeeding cases are also executed.
‰  To prevent the program from executing statements in the subsequent cases, you use
a break statement as your last statement.
Flowchart of switch Statement
Sample Program:
1 public class Grade {
2 public static void main( String[] args )
3 {
4 int grade = 92;
5 switch(grade){
6 case 100:
7 System.out.println( "Excellent!" );
8 break;
9 case 90:
10 System.out.println("Good job!" );
11 break;
12 case 80:
13 System.out.println("Study harder!" );
14 break;
15 default:
16 System.out.println("Sorry, you failed.");
17 }
18 }
19 }
Coding Guidelines
Deciding whether to use an if statement or a switch statement, is a judgment call. You can decide
which to use, based on readability and other factors.
An if statement can be used to make decisions based on ranges of values or conditions, whereas
a switch statement can make decisions based only ona single integer or character value. Also, the
value provided to each case statement must be unique.
Tips and Tricks:
List out the few important tips on selection statements.
Solution:
‰  if (false) { x = 3}; // will compile, to provide the ability to conditionally compile the code.
‰  The if statement takes boolean arguments. Parenthesis is required. else part is
optional.
‰  The compiler checks each case value against the range of the data type of switch
expression.
‰  The following code will not compile.
byte b;
switch (b) {
case 200: // 200 not in the range of byte
default:
}
‰  You need to place a break statement in each case block to prevent the execution to
fall through other case blocks. But this isnot a part of switch statement and not
enforced by the compiler.
‰  Default case can be placed anywhere. It will be executed only if none of the case
values match.
‰  Empty switch construct is a valid construct. But any statement within the switch block
should come under a case label or the default case label.
Summary
‰  The only legal expression in an if statement is a boolean expression; in other words an
expression that resolves to a boolean or a Boolean variable.
‰  Watch out for boolean assignments (=) that can be mistaken for boolean equality (==)
tests.
‰  Curly braces are optional for if blocks that have only one conditional statement. But
watch out for misleading indentations.
‰  switch statements can evaluate only to enums or the byte, short, int, and char data
types.
‰  The case constant must be a literal or final variable, or a constant expression,
including an enum. You cannot have a case that includes a non-final variable, or a
range of values.
‰  The default keyword can be located anywhere in the switch block.

No comments:

Post a Comment