Java Programming - Flow Control - Discussion

Discussion Forum : Flow Control - Finding the output (Q.No. 15)
15.
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'); 
        } 
    } 
}
ABDCBDCB
ABCDABCD
Compilation fails.
An exception is thrown at runtime.
Answer: Option
Explanation:

'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

Discussion:
15 comments Page 2 of 2.

Yatin sharma said:   1 decade ago
The code using short circuit operator for the check i.e. && due to which the right hand condition will not be checked and loop will be infinite.

Rajendra said:   1 decade ago
@Sahil.

Did you really tried to run this program?

It gave me output as mentioned in option A.

Sahil said:   1 decade ago
Try to run this code, it will neither produce any output nor throws exception...

Dinesh said:   1 decade ago
Hi guys, this program will not execute "i<2" since there is a short circuit operator, right? So this program will not terminate and produce an error at runtime. Guys if anyone know pls clarify me?

Dilipkumarsah said:   1 decade ago
When foo ("A") is executed in the intilizing section of loop then the funtion return a boolean value. But there is no any varible to catch it. So this program thorw an error in runtime.


Post your comments here:

Your comments will be displayed after verification.