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


  1. If the value of variable ‘color’ is ‘R’, then ‘You selected ‘RED’ is printed on the screen
  2. If the value of variable ‘color’ is ‘G’, then ‘You selected ‘GREEN’ is printed on the screen
  3. If the value of variable ‘color’ is ‘W’, then ‘You have not selected the valid color’ is printed on the screen



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

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250