Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

java. The output is -- B B A -- B C. Can you explain me the code following? publ

ID: 3743401 • Letter: J

Question

java. The output is -- B B A -- B C.  Can you explain me the code following?

public class ForSwitch {

    final static short x = 2;

     final static int y = 3;

    public static void main(String [] args) {

      

          for (int z = 0; z < 4; z++) {

           switch (z) {

                case x:

                    System.out.print("A ");

                default:

                   System.out.print("-- ");

                case x - 1:

                    System.out.print("B ");

                    break;

                case y:

                    System.out.print("C ");

           }

           }

     }

}

Explanation / Answer

loop goes from 0 to 3 switch (z) { case 2: System.out.print("A "); default: System.out.print("-- "); case 1: System.out.print("B "); break; case 3: System.out.print("C "); } when z is 0 it first switches to default since there is not case 0(prints "-- ") since there is no break after default, it switches to case 1(prints "B ") since there is a break after case 1, this switch ends when z is 1 it first switches to case 1(prints "B ") since there is a break after case 1, this switch ends when z is 2 it first switches to case 2(prints "A ") since there is no break after case 2, it then switches to default(prints "-- ") since there is no break after default, it switches to case 1(prints "B ") since there is a break after case 1, this switch ends when z is 3 it first switches to case 3(prints "C ") since this is last case in switch, this switch ends So, output is "-- B B A -- B C"