Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.650 :

Posted: Tue Feb 15, 2011 9:35 pm
by ETS User
What letters will be printed by this program?

Code: Select all

public class ForSwitch
{
    public static void main(String args[])
    {
        char i;
        LOOP: for (i=0;i<5;i++)
        {
            switch(i++)
            {
                case '0': System.out.println("A");
                case 1: System.out.println("B"); break LOOP;
                case 2: System.out.println("C"); break;
                case 3: System.out.println("D"); break;
                case 4: System.out.println("E");
                case 'E' : System.out.println("F");
            }
        }
    }
}
Explanation:
integer 0 or 1, 2 etc. is not same as char '0', '1' or '2' etc.
so when i is equal to 0, nothing gets printed and i is incremented to 1 (due to i++ in the switch).
i is then incremented again by the for loop for next iteration. so i becomes 2.
when i = 2, "C" is printed and i is incremented to 3 (due to i++ in the switch) and then i is incremented to 4 by the for loop so i becomes 4.
when i = 4, "E" is printed and since there is no break, it falls through to case '5' and "F" is printed.
i is incremented to 5 and the for loop ends.
...."when I = 4, "E" is printed...." "E" is not an option in the answer selection list. When you ask the question "What letters will be printed by this program?" and you state that "E is printed", Should "E" have been one of the answers to select?

Re: About Question com.enthuware.ets.scjp.v6.2.650 :

Posted: Wed Feb 16, 2011 10:41 am
by admin
Hello,
It is not necessary that the question will have all the possible answers. You need to select the options that satisfy the given question. So, yes, it will print E as well. If it is not one of the options, that's fine because question is not asking for everything that the program will print. The question is asking which of the given options/letters will be printed. E does not necessarily have to be among the options.

You may get similar situation in the real exam as well.

HTH,
Paul.