Java: Apply switch instructions - so it'll work
In certain cases, you can prefer the if conditions in Java Switch statements. We'll tell you when that makes sense and how you program a switch statement.
Java: switch statement - what is it?
A switch statement in Java corresponds to an if-else branch with a different syntax:
- An if statement checks boolean values, so "true" or "false". These result from comparisons that you query in the body of an If condition. In the picture gallery you can see examples of the respective cases.
- The switch statement does these comparisons for you. However, you can only compare data of the type "byte", "short", "int", "char", "String" or "enum". In earlier versions of Java (1.6 and lower), only integer values work.
- Conclusion: With if-else branches more complex queries are possible, whereby you have to type a few more characters. A switch is an elegant variant to compare variables of certain data types efficiently and compactly.
Program switch statement in Java
- A switch statement begins with the keyword "switch".
- The variable that you want to compare with the cases (cases) follows in the parentheses after it - i.e. in the argument. All cases are enclosed in curly brackets.
- There is always a colon after a "case". You can place the instructions behind it that you want to execute - if the comparison is correct.
- Warning: Do not forget the "break" according to your instructions. Otherwise, this would mean that all of the following cases will also be processed until a "break" occurs. This is a popular source of error for beginners.
- As a last case, you can implement a "default case" (see picture gallery). The is called if no other comparison has been made. However, this is not absolutely necessary.
Want to program? We also show you how to create classes in Java using Eclipse.