Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
The switch Statement
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
The switch statement compares different primitive data types, String values and other objects to tests whether or not they are equal to a certain value. Play with the example of a switch statement below by changing the value of exampleVariableOne to see the different results.
SwitchStatementExample.java
package exlcode;
public class SwitchStatementExample {
public static int exampleVariableOne = 37;
public static void main(String[] args) {
// checks to see which number exampleVariableOne is
// between 35-40
switch (exampleVariableOne /* expression */){
case 35: // 35 is a label
System.out.println("exampleVariableOne is 35");
break;
case 36: // 36 is a label
System.out.println("exampleVariableOne is 36");
break;
case 37: // 37 is a label
System.out.println("exampleVariableOne is 37");
break;
case 38:
System.out.println("exampleVariableOne is 38");
break;
case 39:
System.out.println("exampleVariableOne is 39");
break;
case 40:
System.out.println("exampleVariableOne is 40");
break;
default:
System.out.println("exampleVariableOne has to be between 35 and 40");
}
}
}
The switch statement tests to see whether or not exampleVariableOne is between 35 and 40. Each "case" within the switch statement checks to see if exampleVariableOne is a certain number, and prints different statements depending on the value exampleVariableOne holds. Keep in mind, just one of these cases is selected per execution of the switch statement, and the data type of the expression has to match the datatype of the label. If none of the case labels matches the value of the expression, the default case is used, and its statements are executed.
A programmer can write many statements after each case, usually followed by a break statement which stops anything after the case from being executed. Let's return to the example above and remove the break statement to see the result and the importance of having a break statement.