Difference between revisions of "Flow Control"

From Suhrid.net Wiki
Jump to navigationJump to search
Line 35: Line 35:
 
** This means that we can use a constant typed literally like case 1: or case 2:
 
** This means that we can use a constant typed literally like case 1: or case 2:
 
** Or the variable should be a '''primitive final variable''' that is assigned a literal value.
 
** Or the variable should be a '''primitive final variable''' that is assigned a literal value.
 +
** An enum value can be used as a case constant, but it should be unqualified.
  
 
Example:
 
Example:

Revision as of 01:10, 19 July 2011

If Statement

  • The expression in an if-statement must evaluate to a boolean expression.
  • The else part is optional for an if-statement.
  • The else belongs to the closest preceding if that doesn't have an else. Example:
if(a > b) System.out.println("a > b");
if(a > 1) System.out.println("a > 1");
else System.out.println("a < 1");

//The else belongs to if(a>1)

Switch Statement

  • General form:
switch(expression) {
       case constant1: code block
       case constant2: code block
       default: code block
}
  • The switch statement has probably the most restrictions on usage.
  • Expression has to evaluate to char, byte, short, int or enum.
  • This implies that only variables that can be implicitly promoted to int can be used in the expression.
  • NO long, float or double.
  • The case constant must evaluate to the same type as the switch expression.
  • The case constant must be a COMPILE TIME constant.
    • This means that we can use a constant typed literally like case 1: or case 2:
    • Or the variable should be a primitive final variable that is assigned a literal value.
    • An enum value can be used as a case constant, but it should be unqualified.

Example:

final int a = 1;
final int b;
b = 2;
int x = process();
switch(x) {
   case a : 
   case 2 : 
   case b : //Error. b is not a compile-time constant
}
  • Default case is used when the expression doesnt match any of the other case constants. The default statement can be located anywhere.