Articles → Java → Switch case in Java

Switch case in Java






Purpose







Syntax


switch (variable_name) {
    case 'value1':
        ..Code block to be executed
        break;
    case 'value2':
        ..Code block to be executed
        break;
    default:
        ..Code block to be executed
}





Example


/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;



/* Name of the class has to be "Main" only if the class is public. */
class Test {
    public static void main(String[] args) throws java.lang.Exception {
        char color = 'W';

        switch (color) {
            case 'R':
                System.out.println("You selected RED");
                break;
            case 'G':
                System.out.println("You selected GREEN");
                break;
            default:
                System.out.println("You have not selected the valid color");

        }
    }
}



Output









Posted By  -  Karan Gupta
 
Posted On  -  Monday, January 2, 2017

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250