By Tony Bevis on Tuesday, 10 October 2023
Category: Java

Java programming course: 5.9 Conditionals using switch case

In the previous lesson you leant about the ternary operator.

Conditionals using switch case

An alternative structure to if…else… is the switch…case… block. You can only use this when testing for equality and for the integer primitives (byte, short, int, long and char) and their wrapper classes (Byte, Short, Integer, Long and Character), and for enum types. You can also test for equality on String objects:

Note the following:

If you do not specify break, then the following lines of code will be executed without any further conditional testing!

Example of switch case with a String object

Since Java 7 enables you can use the String type as the subject in a switch block:

While there are many legitimate uses for if…else… and switch…case… blocks you should be aware that their use might possibly be an indication that you have not fully exploited the object-oriented facilities of Java, such as using inheritance and overriding methods.

In the next lesson you will learn about casting.

Next lesson: 5.10 Casting 

Related Posts

Leave Comments