Java Programming - Flow Control - Discussion

Discussion Forum : Flow Control - Finding the output (Q.No. 8)
8.
What will be the output of the program?
public class Test 
{
    public static void main(String [] args) 
    {
        int I = 1;
        do while ( I < 1 )
        System.out.print("I is " + I);
        while ( I > 1 ) ;
    }
}
I is 1
I is 1 I is 1
No output is produced.
Compilation error
Answer: Option
Explanation:

There are two different looping constructs in this problem. The first is a do-while loop and the second is a while loop, nested inside the do-while. The body of the do-while is only a single statement-brackets are not needed. You are assured that the while expression will be evaluated at least once, followed by an evaluation of the do-while expression. Both expressions are false and no output is produced.

Discussion:
14 comments Page 1 of 2.

Rajat Bansal said:   9 years ago
code can be write as:

do
{
while(I>1)S.O.P("I is :"+I);
}
while(I<1);

As 1 statement ends with the encounter of; which is present at the end of the print statement that's why there is no need of braces after "do" . and both conditions are false that's why no output.
(2)

Pawan said:   2 decades ago
Is do-while syntax correct? guess not.

Ashi said:   1 decade ago
I guess there is a syntax error.

Srikar said:   1 decade ago
More clarified equivalent of above program is:

do
{
while(i<1)
{
System.out.....;
}
}
while(i>1);

Jaics said:   1 decade ago
while ( I < 1 )
System.out.print("I is " + I)

They form two statements, how can they be a single statement...So curly bracket is required..right?

Austin said:   1 decade ago
The compiler will try to associate the 1st "while" encountered with the last "do" encountered.

Hence, it should give compilation error as statement missing;

Simar said:   1 decade ago
From what I understand here is that expressions are not counted as statements. So technically there is only one statement i.e in the while (I < 1).

I could also add more expressions, and it would still be the same. Hope the following example helps you understand it better.

class Test
{
public static void main(String [] args)
{
int I = 1;
do for(int j = 0; j < 5; j++) while(I < 1)
System.out.print("I is " + I);
while ( I > 1 ) ;
}
}

Suresh said:   1 decade ago
public class Test
{
public static void main(String [] args)
{
int I = 1;
do
while ( I < 1 ){
System.out.print("I is " + I);
}
while ( I > 1 ) ;
}
}

As per my understanding above code inside do-while loop while expression is having only one statement that is reason there is no brackets required.

Raj said:   1 decade ago
do while(); semicolon is required.

Zoran said:   10 years ago
Obviously this is the answer :)

public static void main(String [] args)
{
int I = 5;
do //start do while
while ( I < 10 ) System.out.print("I is " + I);//one statement
while ( I > 1 ) ; //end do while
}


Post your comments here:

Your comments will be displayed after verification.