Flow Control

Q1: What will be the output of the program?
public class Delta 
{ 
    static boolean foo(char c) 
    {
        System.out.print(c); 
        return true; 
    } 
    public static void main( String[] argv ) 
    {
        int i = 0; 
        for (foo('A'); foo('B') && (i < 2); foo('C')) 
        {
            i++; 
            foo('D'); 
        } 
    } 
}

A An exception is thrown at runtime.

B ABDCBDCB

C ABCDABCD

D Compilation fails.

ANS:A - ABDCBDCB

'A' is only printed once at the very start as it is in the initialisation section of the for loop. The loop will only initialise that once. 'B' is printed as it is part of the test carried out in order to run the loop. 'D' is printed as it is in the loop. 'C' is printed as it is in the increment section of the loop and will 'increment' only at the end of each loop. Here ends the first loop. Again 'B' is printed as part of the loop test. 'D' is printed as it is in the loop. 'C' is printed as it 'increments' at the end of each loop. Again 'B' is printed as part of the loop test. At this point the test fails because the other part of the test (i < 2) is no longer true. i has been increased in value by 1 for each loop with the line: i++; This results in a printout of ABDCBDCB

What will be the output of the program?
public class Delta 
{ 
    static boolean foo(char c) 
    {
        System.out.print(c); 
        return true; 
    } 
    public static void main( String[] argv ) 
    {
        int i = 0; 
        for (foo('A'); foo('B') && (i < 2); foo('C')) 
        {
            i++; 
            foo('D'); 
        } 
    } 
}



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.