Discussion
What will be the output of the program?
public class Switch2
{
final static short x = 2;
public static int y = 0;
public static void main(String [] args)
{
for (int z=0; z < 3; z++)
{
switch (z)
{
case y: System.out.print("0 "); /* Line 11 */
case x-1: System.out.print("1 "); /* Line 12 */
case x: System.out.print("2 ");
}
}
}
}
Answer: C
Correct answer: Compilation fails at line 11.
A case label must be a compile-time constant. x qualifies, being final static short with an initialiser, so case x and case x-1 are both legal. y does not: it is declared public static int without final, so its value could change and the compiler rejects it at line 11. Had it compiled, the fall-through would have printed 0 1 2 1 2 2 - which is the option offered beside the key.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development