switch Statements : switch « Statements « SCJP

Home
SCJP
1.Java Source And Data Type
2.Operators
3.Modifiers
4.Type Casting
5.Statements
6.Object Oriented
7.Thread
8.Utility Classes
9.File
SCJP » Statements » switch 
5.8.1.switch Statements
The general form of the switch statement is:

switch (expression) {
  case constant1: code block
  case constant2: code block
  default: code block
}

switch's expression must evaluate to a char, byte, short, int, or an enum

If you're not using an enum, only variables that can be promoted to an int are acceptable. 

public class MainClass{
    public static void main(String[] argv){
        int x = 3;
        switch (x) {
           case 1:
              System.out.println("x is equal to 1");
              break;
           case 2:
              System.out.println("x is equal to 2");
              break;
           case 3:
              System.out.println("x is equal to 3");
              break;
           default:
              System.out.println("Still no idea what x is");
        }

    }
}
x is equal to 3
5.8.switch
5.8.1.switch Statements
5.8.2.Case constant must be a compile time constant!
5.8.3.Method being invoked on the object reference must return a value compatible with an int.
5.8.4.It's illegal to have more than one case label using the same value.
5.8.5.It is legal to leverage the power of boxing in a switch expression.
5.8.6.Break and Fall-Through in switch Blocks
5.8.7.Insert a break into each case
5.8.8.Fall-through logic
5.8.9.The Default Case
5.8.10.The default case doesn't have to come at the end of the switch.
5.8.11.default works just like any other case for fall-through!
5.8.12.To ensure that only one case of a switch statement is executed, you need to use the break statement.
5.8.13.The break statement transfers execution out of an enclosing statement.
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.