TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java switch Examples

Use switch, and the case, default and break statements, to run code based on a variable.
Switch. This is a selection statement. It acts upon a variable and selects the case-statement that matches. Switch has limits, but has also advantages and elegance.
Fall through. In a switch, control flow falls through to the next case. We must be careful to use breaks (or returns) to prevent incorrect behavior.Case
Switch, for example. We loop over the number range 0 through 2 inclusive with a for-loop. On each integer, we use a switch statement.For

Default: The switch has no case for 0, so the default block is reached. We print out a message to the console with System.out.

Console

Case 1: For 1 the first case matches. A break exits the switch statement at the end of case 1, and then the loop continues.

Case 2, 3: For 2, the second case block is matched. This would match 3 as well. No break occurs, so it then matches default.

Java program that uses switch public class Program { public static void main(String[] args) { // Loop through 0, 1, and 2. for (int i = 0; i <= 2; i++) { // Switch on number. switch (i) { case 1: { System.out.println("One: " + i); break; } case 2: case 3: { System.out.println("Two or three: " + i); } default: { System.out.println("Default case: " + i); } } } } } Output Default case: 0 One: 1 Two or three: 2 Default case: 2
String switch. This program uses String literals within a switch-statement. If we pass "Max" or "Elle" to getValue, these literals are detected. We return from the switch statement.String Switch
Java program that uses method, Strings public class Program { static int getValue(String name) { // Switch on a String argument. switch (name) { case "Max": return 1; case "Elle": return 2; } return 0; } public static void main(String[] args) { // Call method that uses switch. String name = "Max"; int result = getValue(name); System.out.println(result); System.out.println(getValue("Elle")); } } Output 1 2
Nested switch. We sometimes nest a switch within another one. This program uses two switches. It first checks the first letter of a string (with charAt) and then tests the second char.

Tip: We can check for possible string matches this way. A switch can check all possible characters at each position.

Java program that uses nested switch public class Program { public static void main(String[] args) { String value = "hi"; // Switch on first letter. switch (value.charAt(0)) { case 'h': // Switch on second letter. switch (value.charAt(1)) { case 'i': System.out.println("Values are h, i"); break; case 'e': System.out.println("?"); break; } break; case 'e': System.out.println("?"); break; } } } Output Values are h, i
Constant expressions. A switch cannot have variables in its cases. It must have constants. But we can use compile-time, constant expressions as cases. This can make code clearer.

Note: The compiler evaluates the constant expressions (like 10 * 10) at compile-time. They are the same as constant values (like 100).

Java program that uses expressions in switch public class Program { public static void main(String[] args) { int value = 100; // Match constant-value expressions in cases. switch (value) { case 10 * 1: System.out.println("A"); break; case 10 * 10: System.out.println("B"); break; case 10 * 100: System.out.println("C"); break; } } } Output B
Duplicate cases. A switch cannot have duplicate cases. This error sometimes occur in large switches that are harder to remember. The program does not compile.

Note: Constant expressions are checked for duplication as well. This helps ensure program quality.

Java program that has duplicate cases public class Program { public static void main(String[] args) { int value = 100; // This switch causes compilation problems. switch (value) { case 100: System.out.println(true); break; case 100: System.out.println(true); break; } } } Output Exception in thread "main" java.lang.Error: Unresolved compilation problems: Duplicate case Duplicate case at program.Program.main(Program.java:9)
Type mismatch. Cases in a switch must match the type of the value being switched upon. Java provides this checking to ensure program quality—switch cases are valid based on the type.
Java program that causes type mismatch public class Program { public static void main(String[] args) { byte value = 100; // A byte can never equal 1000 so an error occurs. switch (value) { case 1000: System.out.println(false); return; } } } Output Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to byte at program.Program.main(Program.java:8)
Continue. Statements like continue and return can be used within a switch. But these affect the enclosing block, not the switch itself.

Loop: A continue in a switch moves to the next iteration in an enclosing loop. A return acts on the enclosing method.

Java program that uses continue in switch public class Program { public static void main(String[] args) { for (int i = 0; i < 5; i++) { switch (i) { case 0: case 1: // The continue moves to the next iteration in the loop. continue; default: // This breaks the switch, not the loop. break; } System.out.println(i); } } } Output 2 3 4
Benchmark, switch. Switch sometimes has clear performance advantages over an if-statement. Consider this example. The values 0 through 4 are tested many times.

Version 1: This version of the code uses a switch-statement to test for the values 0 through 4.

Version 2: Here we use an if-else chain to test for the values 0 through 4. We can use more complex expressions here.

Result: The switch statement is faster. But switch can slow down a method—try checking for the most common case in an if-statement.

Java program that times switch, if-statement public class Program { public static void main(String[] args) { long t1 = System.currentTimeMillis(); // Version 1: use switch. int total = 0; for (int i = 0; i < 100000000; i++) { switch (i) { case 0: total--; break; case 1: total -= 2; break; case 2: case 3: case 4: total++; break; } } long t2 = System.currentTimeMillis(); // Version 2: use if-else. int total2 = 0; for (int i = 0; i < 100000000; i++) { if (i == 0) { total2--; } else if (i == 1) { total2 -= 2; } else if (i >= 2 && i <= 4) { total2++; } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 234 ms, switch 281 ms, if/else if
Guide. A switch is best used only when the input is unknown. The example does not follow this guideline. We use the System.out.println method to write the console.

Caution: With switch, problems can occur because of incorrect fall-through cases. Be careful to check that are used when needed.

Also: An alternative control structure is the if-statement. This may be clearer in many program contexts.

If
Analyze performance. Often groups of near numbers are faster in a switch. But if one number occurs most often, it may be faster to simply test it first with an if-statement.

So: Frequency analysis can help with determining whether an if-statement or a switch is optimal.

Tip: Add to a counter on each code statement reached. And then optimize for the most common path.

Alternative. Switch is an alternative selection statement. In some places where many constants must be matched, an if-statement may be awkward.
A review. We use switch to rewrite, and clarify, this code. We benchmarked and tested this construct. Switch supports Strings and constant expressions.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf