Java Tutorial : Switch case( Without break )



To choose one option from several available options, we can use switch statement. Dependiong on the selection option, a perticular task can be performed.

Syntax:

switch(variable)
    {
        case value1 : statements;
        case value2 : statements;
        case value3 : statements;
        case value4 : statements; 
        [default    : Default statements]; 
    }


Here depending upon the value of the case perticular statement will be executed. And if there is no value match then default statement will get executed.


Example :

class switchcase {

  public static void main(String[] args) {
    char color = 'g';
    switch (color) {
      case 'b':
        System.out.println(" Blue ");
      case 'r':
        System.out.println(" Red ");
      case 'g':
        System.out.println(" Green ");
      default:
        System.out.println(" No Color ");
    }
  }
}



Here the output will be as :
Blue
Red 
Green 
No Color


because after executing first statements command will be transfered to next statements.To stop this we have to use BREAK statements aboout wich we will learn on next Tutorial.

2 comments:

Powered by Blogger.