Java Switch Block

If you want to evaluate an expression, based on the evaluation results some piece of code needs to be executed then we have a switch block.

switch block evaluates expression based on the expression results, switch case will be executed.

If there is no switch case have the same value as what expression is resulted then default block will be executed.

Please remember switch block will be executed only once.

Java Switch Block Example

public class SwitchBlockExample {

	public static void main(String[] args) {
	
			int i=2;
			switch(i)
			{
			
			case 1:
			System.out.println("Case 1 block executed");
			break;
			case 2:
			System.out.println("Case 2 block executed");
			break;
			case 3:
			System.out.println("Case 3 block executed");
			break;
			
			case 4:
			System.out.println("Case 4 block executed");
			break;
			default:
			System.out.println("Default block executed");
			
			}
	}

}
Output
Case 2 block executed