Java Programming - Flow Control - Discussion
Discussion Forum : Flow Control - Finding the output (Q.No. 6)
6.
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 "); /* Line 13 */
}
}
}
}
Answer: Option
Explanation:
Case expressions must be constant expressions. Since x is marked final, lines 12 and 13 are legal; however y is not a final so the compiler will fail at line 11.
Discussion:
12 comments Page 2 of 2.
Mahesh said:
1 decade ago
Nevermind i got the logic. I forgot when we define x and y as static final. They become constant. So inside switch case - case y will mean case 0 and so on for others.
Mahesh said:
1 decade ago
public class Switch2
{
final static short x = 2;
public static final 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 "); /* Line 13 */
}
}
}
}
// Can you tell me why the above program giving 012122 as output?
{
final static short x = 2;
public static final 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 "); /* Line 13 */
}
}
}
}
// Can you tell me why the above program giving 012122 as output?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers