The following code shows How Switch Case Statement in Java Works.

In fact, the switch case statement is a convenient way to represent several conditions instead of nested if…else statement. When there is a check for equality, we can use the switch case statement. Basically, it starts with the keyword switch and followed by an expression. The expression is evaluated. After that it is matched with the case labels until a match is found. When there is no matching case label, either the control falls out of the switch statement or the statements following default are executed.

public class Exercise8
{
	public static void main(String[] args) {
		String code, colorname="";
		code=args[0];
		System.out.println("The color code that you have entered is "+code);
		switch(code)
		{
			case "R": colorname="Red";
				  break;	
			case "G": colorname="Green";
				  break;	
			case "B": colorname="Blue";
				  break;	
			case "O": colorname="Orange";
				  break;	
			case "Y": colorname="Yellow";
				  break;	
			case "W": colorname="White";
				  break;	
			default: System.out.println("Wrong Color Code!");
				 System.exit(0);
		}
		System.out.println("Color Name: "+colorname);
	}
}

Output

The Output of an Example of Switch Case Statement in Java
The Output of an Example of Switch Case Statement in Java

Further Reading

Java Practice Exercise

programmingempire

Princites