Java Programming - Flow Control - Discussion

Discussion :: Flow Control - Finding the output (Q.No.14)

14. 

What will be the output of the program?

int i = 0; 
while(1) 
{
    if(i == 4) 
    {
        break;
    } 
    ++i; 
} 
System.out.println("i = " + i);

[A]. i = 0
[B]. i = 3
[C]. i = 4
[D]. Compilation fails.

Answer: Option D

Explanation:

Compilation fails because the argument of the while loop, the condition, must be of primitive type boolean. In Java, 1 does not represent the true state of a boolean, rather it is seen as an integer.


Aayushkanungo said: (Aug 1, 2018)  
Here, the compilation fails as while(1) is always true and the loop will be in an infinite loop which JVM not supports.

Vinit Nagap said: (Sep 26, 2019)  
while(1) is not an infinite loop in java like c, while(1) gives a compile-time error 1 should be replaced by TRUE.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.