2.1 if & switch StatementsHomepage  « Java5 Certification « 2.1 if & switch Statements

In our first lesson within this section we look at code to implement if and switch statements whilst identifying legal argument types for them.

Lets take a look at the points outlined at the Oracle Website for this part of the certification.

  • Section 2: Flow Control

    • Develop code that implements an if or switch statement; and identify legal argument types for these statements.

The if Statementgo to top of page Top

Create a conditional expression using one of the relational operators available in Java to test one operand against another or test the result of a logical operation. We can execute one set of statements if the boolean result of the expression evaluates to true and another if the expression evaluates to false.

The relational and logical operators are discussed in more detail in the Operators lesson.

The following table shows the different forms of the if construct that can be used. We are using blocks of code to wrap statements which is optional, but good practice and will be used here.

Construct Description
Simple if
if (condition) {
    statement1
}

Execute statements in statement1  if condition expression evaluates to true.
if....else
if (condition) {
    statement1
} else {
    statementN
}

Execute statements in statement1  if condition expression evaluates to true,

otherwise execute statements in statement N.
Nested if
if (condition) {
    statement1
    if (condition2) {
        statement2
    } else {
        statement3
    }
} else {
    statement N
}

Execute statements in statement1  if condition expression evaluates to true

Execute statements in statement2  if condition2 expression evaluates to true,

otherwise execute statements in statement3  if condition2 expression evaluates to false,


otherwise execute statements in statement N  if condition expression evaluates to false.
Multiple if....else if
if (condition) {
    statement1

} else if (condition2) {
    statement2

} else if (condition3) {
    statement3
   ...
} else {
    statement N
}

Execute statements in statement1 if  condition expression evaluates to true


Execute statements in statement2  if condition2 expression evaluates to true,


Execute statements in statement3  if condition3 expression evaluates to true etc...,


otherwise execute statements in statement N.

if Rules and Examples

There are a few rules to remember when coding the if statement:

  • The expression we check against, in the parentheses, must evaluate to a boolean type: true or false.
  • One optional else statement can be coded as part of the if construct and must come after any else if statements.
  • Multiple else if statements can be coded after the initial if and before the optional else statement (if coded).
  • As soon as we hit a true condition any other else if statements will not be tested.

Following are some examples showing if statement usage:


/*
  Some code showing if statement usage
*/
boolean b = false;
int i = 2;

 // Simple if
if (b == false) {
    System.out.println("This is executed");
}   

if (i = 2) { // Will not compile, does not evaluate to boolean
    System.out.println(" ");
}   
// if else
if (b = false) { // Assignment not evaluation
    System.out.println("This is NOT executed"); 
} else {
    System.out.println("This is executed");
}   
// Multiple if else
if (i == 0) { 
    System.out.println("This is NOT executed"); 
} else if (i == 1) {
    System.out.println("This is NOT executed");
} else if (i == 2) {
    System.out.println("This is executed");
} else {
    System.out.println("This is NOT executed");
}   

if (i == 0) { 
    System.out.println("This is NOT executed"); 
} else (i == 1) { // Will not compile, else must come last
    System.out.println(" ");
} else if {
    System.out.println(" ");
}

The switch Statementgo to top of page Top

The switch statement can be used instead of the multiple if....else if construct when we are doing a multiway test on the same value. When this scenario arises the switch statement is often a more efficent and elegant way to write our code

The switch statement is where we put the expression we are going to evaluate. Each case constant is evaluated against the switch expression and the statements within the case are processed on a match. We have the option to break from the switch after this if required. We can also code an optional default statement, which can act as a kind of catch all and is normally placed, at the end, after the case statements.

Construct Description
switch
switch (expression) {
   case constant1:
      statements1
      [break;]

   case constant2:
      statements2
      [break;]
   ...

   case constantN:
      statementsN
      [break;]

   default:
      defaultStatements
      [break;]
}
expression can be of type char, byte, short or int.
  constant1 must be a literal of a type compatible with the switch expression.
     Execute statements1 on match.
     Optional break from switch statement.

  constant2 must be a literal of a type compatible with the switch expression.
     Execute statements2 on match.
     Optional break from switch statement.

  constantN must be a literal of a type compatible with the switch expression.
     Execute statementsN on match.
     Optional break from switch statement.

   Optional default statement (catch all).
     Execute defaultStatements.
     Optional break from switch statement.
nested switch
switch (expression1) {
   case constant1:
      switch (expression2) {
         case constant1:
         statements1
         [break;]
          ...
      } // end of inner switch

      [break;]
   ...
   default:
       defaultStatements
      [break;]
}


This is perfectly legal.

switch Rules and Examples

There are a few rules to remember when coding the switch statement:

  • The switch expression we check against, in the parentheses, must evaluate to a char type, or the byte, short or int signed numeric integer types or to an enum.
  • When not using an enum in our switch statement only types that can be implicitly cast to an int are allowed.
  • The switch statement can only check for equality (==) and so the other relational operators won't work with switch.
  • The case constant must evaluate to the same type as the switch expression.
  • The case constant is a compile time constant and because it has to be resolved at compile time, any constant or final variables must have been assigned a value.
  • The value of the case constants must be different.
  • When a case constant evaluates to true the associated code block and any code blocks following are executed, unless a break statement is encountered.
  • The default statement can be placed anywhere within the switch statement and when executed, the associated code block and any code blocks following are executed, unless a break statement is encountered.

Following are some examples showing switch statement usage:


/*
  Some code showing switch statement usage
*/
final int i1 = 2;
final int i2;
byte b = 25;
String s = "java5";

 // switch
switch (i1) {
    case 1:
        System.out.println("This is not executed");
    case 2:
        System.out.println("This is executed");
    case 3:
        System.out.println("This is executed");
}   

switch (i2) {  // Not a compile time constant so won't compile
    case 1:
        System.out.println(" ");
    case 2:
        System.out.println(" ");
    case 3:
        System.out.println(" ");
}   

switch (i1) {
    case 1:
        System.out.println(" ");
    case 2:
        System.out.println(" ");
    case 2:  // Same case value so won't compile
        System.out.println(" ");
}   

switch (b) {
    case 25:
        System.out.println(" ");
    case 128:  // Loss of precision so won't compile
        System.out.println(" ");
}   

switch (s) {  // Incompatible switch type of String so won't compile
    case "java2":
        System.out.println(" ");
    case "java5":
        System.out.println(" ");
    case "java6":
        System.out.println(" ");
}   

 // switch break
int i3 = 2;
switch (i3) {
    case 1:
        System.out.println("This is not executed");
    case 2:
        System.out.println("This is executed");
        break;
    case 3:
        System.out.println("This is not executed");
}   

 // switch default
int i4 = 2;
switch (i4) {
    case 0:
        System.out.println("This is not executed");
    case 1:
        System.out.println("This is not executed");
    default:
        System.out.println("This is executed");
}   

switch (i4) {
    case 0:
        System.out.println("This is not executed");
    default:
        System.out.println("This is executed");
    case 1:
        System.out.println("This is executed");
}

Related Java5 Tutorials

Beginning Java5 - Conditional Statements
Beginning Java5 - Loop Statements
Beginning Java5 - Primitive Variables
Beginning Java5 - Operators

<<  Flow Control                    2.2 Loop Statements  >>

go to home page Java5 Tutor Homepage go to home page Top