Java Switch Statement

The switch statement is used to execute a block of statements based on the switch expression value. An expression must be of type int, short, byte, or char. A case value should be a constant literal value and can not be duplicated. The expression value is compared with each case value. If a match is found corresponding block of statements will be executed. A break statement is used to terminate the execution of statements. If no case value matches with the expression value then the default block of statements will be executed. If a break statement is not used within the case, all matching cases will be executed.

Syntax:

switch(expression){
                case value1:
                         //block of statements
                         break;
                
                case value2:
                        //block of statements
                        break;
                
                ...
                 
                default:
                     //block of statements
                     break;
                 
}

Program to use switch statement in Java.

public class SwitchStatementExample {	
	static void switchTest(int caseValue){
		switch(caseValue) {
                case 0:
                        System.out.println("Case 0.");
                        break;               
                case 1:
                        System.out.println("Case 1.");
                        break;               
                case 2:
                        System.out.println("Case 2.");
                        break;               
                default:
                        System.out.println("Default Case.");
                       
        }
	}	
	
	public static void main(String args[]){ 
		//method call 
		switchTest(1); 
	}
}

Output

Case 1.

 

Please follow and like us:
Content Protection by DMCA.com