Java Switch Statement

The switch statement in Java is a decision making statement. It has the following syntax:

switch ( expression ) {
case a : // statements
         break;
case b :  // statements
         break;
// other cases
default : // statements
}

The expression must evaluate to byte, short, char, int or String. The value of expression is compared with a, b, c etc. When a match occurs, the statements in that case are executed. If no match occurs, the statements under default are executed.

Here is an example :

int a = 3;
switch (a) {
    case 3:
        System.out.println("a is 3");
        break;
    case 4:
        System.out.println("a is 4");
        break;
    case 7:
        System.out.println("a is 7");
        break;
    default:
        System.out.println("a is neither 3 nor 4 nor 7");
        break;
}

The value of a is compared with 3, 4 and 7 and the corresponding statement in printed. If a is 3, then “a is 3″ is printed. If a is 4, then “a is 4″ is printed. If a is 7, then “a is 7″ is printed. If a is neither 3 nor 4 nor 7, then “a is neither 3 nor 4 nor 7″ is printed.

The break statement in the default part can be omitted. Even then, the program will still be correct.

int a = 3;
switch (a) {
    case 3:
        System.out.println("a is 3");
        break;
    case 4:
        System.out.println("a is 4");
        break;
    case 7:
        System.out.println("a is 7");
        break;
    default:
        System.out.println("a is neither 3 nor 4 nor 7");
}

We can also completely omit the break statement as shown below. In that case, nothing will be printed when a is neither 3 nor 4 nor 7.

int a = 3;
switch (a) {
    case 3:
        System.out.println("a is 3");
        break;
    case 4:
        System.out.println("a is 4");
        break;
    case 7:
        System.out.println("a is 7");
        break;
}

If break is removed, statements from other cases will be executed irrespective of whether a match occurs or not until a break is encountered.

See the following for example :

int a = 3;
switch (a) {
    case 3:
        System.out.println("a is 3");
    case 4:
        System.out.println("a is 4");
        break;
    case 7:
        System.out.println("a is 7");
    default:
        System.out.println("a is neither 3 nor 4 nor 7");
        break;
}

Output when a = 3
a is 3
a is 4

Output when a = 4
a is 4

Output when a = 7
a is 7
a is neither 3 nor 4 nor 7

Output when a is neither 3 nor 4 nor 7
a is neither 3 nor 4 nor 7

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>