What is the result?

Given the code fragment:

What is the result?
A. 3
B. 4
C. -1
D. Compilation fails.

Download Printable PDF. VALID exam to help you PASS.

10 thoughts on “What is the result?

  1. A
    —wd–1—case sun—s-sun
    —wd-0 —case mon—s-mon
    —wd-2—case wed—s-mon
    —wd-4—case wed—s-wed
    —wd-4 —case sat—s-sat
    —wd-3—case sun—s-sat
    3

  2. A ( in provided code “{}” should be used in the string array instead of “()” ):
    # javac Test23.java
    # java Test23
    3

    1. for “sun” wd = -1 and quits switch for the next iteration
      for “mon” wd=wd+1 (totally 0) and wd = wd+2 (totally 2) and exits switch for next iteration
      for “wed” wd = wd+2 (totally 4) and exists the switch
      for “sat” wd=wd-1 (totally 3) and exits the switch via break, program finish itself with 3

  3. If we do not use break statement at the end of each case, program will execute all consecutive case statements until it finds next break statement or till the end of switch case block.

  4. The correct Answer is 3

    public class Test{

    public static void main (String[] args){
    int wd = 0;
    String days[] = {“sun”, “mon”, “wed”, “sat”};
    for (String s: days){
    switch(s){
    case “sat”:
    case “sun”:
    wd -= 1;
    break;
    case “mon”:
    wd++;
    case “wed”:
    wd += 2;
    }
    }
    System.out.println(wd);
    }
    }

    //Result
    //3

Leave a Reply

Your email address will not be published.