Saturday, 23 July 2016

Beginning Java Programming Chapter-6

tement in the block will not be executed; the whole if block will be skipped. Now consider the case in which we don't use the curly braces:
1. if ( x > 0 )
2. System.out.println("x is greater than zero.");
3. System.out.println("Who cares what x is.");
Line 2 will be executed only if x is greater than 0, whereas line 3 will always be executed independent of the value of x . Remember that the <expression> in the parentheses of if() must evaluate to a boolean value: true or false . Also remember that = is an assignment operator and not the comparison operator. For example, if(x=y) is illegal whereas the legal form is if(x==y) . However, if x and y are boolean , then if(x=y) will compile but will give the wrong results. As an illustration, consider the code :
1. class IfTest {
2. public static void main(String[] args)
3. {
4. boolean b1 = false;
5. boolean b2 = true;
6. if(b1=b2){
7. System.out.println("The value of b1: " + b1);
8. }
9. }
10.}
the code will compile, but it will change the value of b1 from false to true because it assigns the value of b2 to b1 , and now, ecause b1 is true , the test will pass, and the body of the if block will be executed. The output from the code: The value of b1: true
¦ Note The legal argument type of an if() statement is a boolean . That means the expression in the parentheses of the if() statement must result in a boolean value.
The if construct handles a very simple situation and takes an action only if the condition is true . A bit more sophisticated case will do something if a condition is true , else do something else.
The if-else Construct You can handle two blocks of code with the if-else construct. If a condition is true , the first block of code will be executed, otherwise the second block of code will be executed. The syntax for the if-else construct follows:
if( <expression> ) {
// if <expression> returns true, statements in this block are executed.
}
else {
// if <expression> is false, then statements in this block will be executed.
}
For example, consider the following code fragment:
if ( x > 0 ) {
System.out.println("x is greater than zero.");
}
else {
System.out.println("x is not greater than zero.");
}
If the value of x is greater than zero, the output of this code is : x is greater than zero, Otherwise the output is, x is not greater than zero.
The if and if-else constructs can test only one expression, which may contain one or more conditions. However, you may encounter situations in which multiple conditional expressions exist and you want to test one after the other. You handle this type of situation with the if-else if construct .
The if-else if Construct With the if-else if construct you can handle multiple blocks of code, and only one of those blocks will be executed at most. The syntax for the if-else construct follows:
if( <expression1> ) {
// if <expression1> returns true, statements in this block are executed.
}
else if ( <expression2>) {
// if <expression1> is false and <expression2> is true,
then statements in this block will be executed.
}
else if (<expression3>) {
// if <expression1> is false, and <expression2> is false, and <expression3> is
true, then statements in this block will be executed.
}
Note that in an if-else if construct, the expressions will be tested one by one starting from the top. If an expression returns true , the block following the expression will be executed and all the following else if blocks will be skipped. Also note that it is possible that no block will be executed, a possibility that does not exist with the if-else construct. However, Java does offer a construct that enables you to handle multiple blocks of code and ensure that one of them will certainly be executed, discussed next.
The if-else if-else Construct The syntax for the if-else if-else construct follows:
if( <expression1> ) {
// if <expression1> returns true, statements in this block are executed.
}
else if (<expression2>) {
// if <expression1> is false and <expression2> is true,
then statements in this block will be executed.
}
else if (<expression3>) {
// if <expression1> is false and <expression2> is false, and
<expression3> is true, then statements in this block
will be executed.
}
else {
// if the expression in the if statement and the expressions
in all the else if statements were false, then the statements
in this block will be executed.
}
Keep in mind that the condition in the if or else if statement can be a compound condition, such as: if(i > 2 && j < 100)
However, the condition should always evaluate to a boolean .
Summary of the if Constructs
The following list summarizes the if family of constructs:
• There are two constructs for a single expression: if where it is possible that no block will be executed, and if-else where one block will certainly be executed.
• There are also two constructs corresponding to multiple expressions: if-else if where it is possible that no block will be executed, and if-else if-else where one block will certainly be executed.
• The first construct is always if .
• Any of these constructs may be nested inside any other construct. The condition for the inner construct will be tested only if the condition for the outer construct was tested and was true .
Again, consider the if-else if construct, and assume that it finds the expression in an else if statement to be true . In this case, the code block related to that else if statement will be executed and all the other following blocks will be ignored. What if you want all or some of the following blocks executed as well after a block with a true expression is found? You can handle this situation with another selection statement, the switch statement.
The switch Statement The switch statement is used to make the choices for multiple blocks with the possibility of executing more than one of them. Let's start with an example:
switch (x){
case 5:
System.out.println("The value of x is 5." );
break;
case 4:
System.out.println("The value of x is 4." );
case 7:
System.out.println("The value of x is 7." );
case 2:
System.out.println("The value of x is 7." );
case 1:
System.out.println("The value of x is 1." );
default:
System.out.println("The value of x is default.");
}
In this code, x is an integral variable (any integral variable except long ) with a certain value assigned to it. If the value of x is 5, the print statement under case 5 is executed. Following this, the break statement is executed. Execution of the break statement moves the execution control to the first line after the switch block. If the value of x is not 5, the next case is tested; that is, it would be checked if the value of x is equal to 4. If it is, the print statement under case 4 is executed. Because there is no break statement after this, all the following statements under all case labels, including the default label, would be executed. This is called a fall through . If the value of x is not equal to any value following any case label, the statement(s) under label default are executed.
For example, for x=1 , the preceding code will generate the following output: The value of x is 1, The value of x is default.
The default label could go anywhere in the switch block; it does not have to be put at the end. In this case, it was executed because there was no break statement in the previous block executed before it.
Note In the switch statement, the default case does not have to appear at the end. It can appear anywhere in the switch block.
If the default case is not at the end, and is executed, the execution can fall through in this case as well if there is no break statement in it. For example, the following is a perfectly valid code fragment:
int x=3
switch (x) {
case 1:
System.out.println("The value of x is 1." );
break;
case 2:
System.out.println("The value of x is 2." );
default:
System.out.println("The value of x is default.");
case 4:
System.out.println("The value of x is 4." );
}
It will generate the following output: The value of x is default, The value of x is 4.
Remember the following about the default block:
• The default does not have to be at the end of the switch .
• When the execution control faces a default block, it executes it.
• If there is no break statement in the default block, there will be fall through just like in any other block.
The comparison of values following the case labels with the value of the argument of switch determines the execution path. Once the execution path of a particular case is chosen, the execution falls through until it runs into a break statement.
Note the following:
• The argument of switch() must be one of the following types: byte , short , char , int , or enum .
• The argument of case must be a literal integral type number, such as 2, or a literal number expression that could be evaluated at compile time, such as 2+3.
• There should be no duplicate case labels; that is, the same value cannot be used twice.
• The variable x in switch(x) cannot be declared inside the parentheses. To illustrate the last point, the following statement is illegal:
switch ( int x=2;)
However, a simple mathematical expression inside the parentheses is fine, such as the following:
switch ( x+ y )
or
switch(x++)
where x and y are already declared variables of the correct type. So, the legal argument type of a switch statement is int , or any other type that can be promoted to int : byte , short , or char . If you use some other type, such as long , float , or double , you will receive a compiler error. Also be careful about the implications of this. For example, the following code fragment is illegal because one of the case labels is too big to be a byte :
byte x=5;
switch(x){
case 5 : System.out.println("five");
case 130 : System.out.println(" one thirty "); // compiler error
}
This generates a compiler error because the compiler will look at 130 as an int , which can't fit into a byte .
Also note that an enum , the new kid on the block, can also be used as a legal argument for a switch statement.
¦ Note The legal argument types of a switch statement are byte , short , char , int , and enum . You will receive a compiler error if you use any other type.
To summarize, starting from the top of the switch block, each non-default case is tested. If a case turns out to be true , the tatements in that case and all the following cases are executed until a break statement is encountered. If none of the non-default cases is true , and the execution control faces the default case, then the statements in the default case and all the following cases are executed until a break statement is encountered. The default statement can be anywhere in the switch block. To illustrate this, presents a complete runnable example of a switch statement that uses an enum as an argument.
1. class SwitchTest {
2. public static void main(String[] args)
3. {
4. Signal sig = Enum.valueOf(Signal.class, args[0].toUpperCase());
5. switch(sig){
6. case RED:
7. sig.redSays();
8. break;
9. case YELLOW:
10. sig.yellowSays();
11. case bGREEN:
12. sig.greenSays();
13. }
14. }
15. }
16. enum Signal {RED, YELLOW, GREEN;
17. public void redSays(){
18. System.out.println("STOP");
19. }
20. public void yellowSays(){
21. System.out.println("STOP if it is safe to do so.");
22. System.out.println("Otherwise");
23. }
24. public void greenSays(){
25. System.out.println("Keep going.");
26. }
27. }
As an example, you can execute this code with the following command: java SwitchTest yellow , The output follows:
STOP if it is safe to do so. Otherwise Keep going.

No comments:

Post a Comment