Q: What is the output of the Java program below? String animal = "GOAT"; switch(animal) { break: System.out.println("DOMESTIC"); }
Solution: Case statements should start with either "case" or "default" only.
Q: What is the output of the Java program below? String college = "OXFORD"; switch("STANFORD") { case college: System.out.println("EXAM TIME"); break; default: System.out.println("UNKNOWN"); }
Solution: case expressions must be constant expressions. So, make the variable final. final String college = "OXFORD";
Q: What is the output of Java program with SWITCH? int num=20; switch(num) { case 10: System.out.println("TEN"); break; case 20: System.out.println("TWENTY"); break; case 30: System.out.println("THIRTY"); }
Solution: no solution
Q: What is the output of Java program below? int num=40; switch(num) { case 5: System.out.println("FIVE"); break; case 35+5: System.out.println("FORTY"); break; case 20+30: System.out.println("FIFTY"); }
Solution: It is allowed to write expressions that result in constant values.
Q: What is the output of the below Java program? int persons = 45; int random = 45; switch(random) { case persons: System.out.print("CRICKET "); default: System.out.println("RUGBY"); }
Solution: Error: case expressions must be constant expressions So, make the variable final. final int persons = 45; //Then, output will be CRICKET
Q: What is the output of the below Java program? switch(15) { case 5*2: System.out.println("TEN");break; case 5*4-5:System.out.println("FIFTEEN");break; case 60/4+5: System.out.println("TWENTY"); }
Solution: Any expression that results in a Constant can be used as a "case constant".
Q: A SWITCH fall through occurs in Java only in the absence of ___.
Solution: no solution
Q: What is the purpose of designing a SWITCH logic with a fall-through in Java?
Solution: This is the way we define ranges in a SWITCH construct.
Q: Does the following Java code-snippet compile? switch(45) { case 10: ; }
Solution: You can specify dummy statements in java using a Semicolon (;).
Q: What is the output of the below Java program with a SWITCH statement? int points=6; switch(points) { case 6: ; case 7: System.out.println("PASS");break; case 8: ; case 9: System.out.println("Excellent");break; case 10: System.out.println("Outstanding"); break; default: System.out.println("FAIL"); }
Solution: This is the way we define ranges in a SWITCH construct.
You Have Score    | /10 |