What will be the output of the program?int i = 1, j = -1; switch (i) { case 0, 1: j = 1; /* Line 4 */ case 2: j = 2; default: j = 0; } System.out.println("j = " + j); j = -1j = 0j = 1Compilation fails.
Question
What will be the output of the program?int i = 1, j = -1; switch (i) { case 0, 1: j = 1; /* Line 4 */ case 2: j = 2; default: j = 0; } System.out.println("j = " + j); j = -1j = 0j = 1Compilation fails.
Solution
The output of the program will be "j = 0". Here's why:
- The variable
iis initialized with a value of 1. - The
switchstatement evaluatesi. - The
case 0, 1:matches the value ofi, sojis set to 1. - However, there are no
breakstatements after eachcase, so the program "falls through" to the nextcaseanddefaultstatements. - The
case 2:does not match, but thedefault:statement is always executed if no othercasematches or if there is a "fall through" as in this case. - Therefore,
jis set to 0 in thedefault:statement. - Finally, "j = 0" is printed to the console.
Similar Questions
What will be the output of the program?public class Test { public static void main(String args[]) { int i = 1, j = 0; switch(i) { case 2: j += 6; case 4: j += 1; default: j += 2; case 0: j += 4; } System.out.println("j = " + j); } }j = 0j = 2j = 4j = 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 < 4; z++) { switch (z) { case x: System.out.print("0 "); default: System.out.print("def "); case x-1: System.out.print("1 "); break; case x-2: System.out.print("2 "); } } }}0 def 12 1 0 def 12 1 0 def def2 1 0 def 1 def 1
What is the output of following code:void main(){int i=5;switch(i){case 3: printf(“three”);case 4: printf(“four”);case 5: printf(“five”);case 6: printf(“six”);break;case 7: printf(“seven”);default: printf(“default”);}}a.fiveb.fivesixsevendefaultc.fivesixd.fivesixseven
3 answersyou want the program to print 3 to the output. What of the following values for x will do thisswitch(x){case(1);System.out.println("1");case(2);case(3);System.out.println("3");}A. any valueB. 3C. 2D. 1E. 0F. 4
Select the correct answerWhat will be the output of the following code?int b = 7;switch (b) { case 6: System.out.println("Six"); break; case 7: System.out.println("Seven"); break; case 8: System.out.println("Eight"); break; default: System.out.println("Default");}OptionsEightSevenSixDefault
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.