Given:
2. public class Main { 3. public static void main(String[] args) { 4. String r = "-"; 5. char[] c = {'a', 'b', 'c', 'z'}; 6. for(char c1: c) 7. switch (c1) { 8. case 'a': r += "a"; 9. case 'b': r += "b"; break; 10. default: r += "X"; 11. case 'z': r+= "z"; 12. } // w ww .ja va2 s. c o m 13. System.out.println(r); 14. } 15.}
What is the result?
A. -abXz B. -abbXz C. -abbXzz D. -abbXzXz E. Compilation fails due to a single error. F. Compilation fails due to multiple errors.
C is correct.
Remember that a matching case represents the entry point for code execution, not the only point that will be executed.
Also, even though the default comes before case "z", when the switch variable equals "z" the switch will skip the default and choose case "z".