Saturday 18 March 2017

What will be execution process for this statement in java -- > for(;;){ //your code}

In a recent interview that my friend attended, he was given below code by interviewer

//your code

And then interviewer asked him to explain how this for loop will execute. He discussed this question with me as he failed to answer it. I am aware of this answer as luckily same question was asked by my college teacher during viva.

But any way if you don't know it lets explore its execution process now.

First lets understand basic structure of for loop in java. Lets consider given example,

for(int i=0; i<5;i++){

How above for loop works?

For the very first time when code enters the for loop, then initialization statement i=0 is executed once.
Then conditional statement i<5 is executed. If it executes to be true then body inside the for loop is executed. Otherwise loop gets terminated.
In our case it executes to be true as i = 0, so our code will enter inside loop and print : Executed
Now incremental statement i++ is executed and i increases by 1 (i.e i=1)
Again conditional statement is executed and 1<5 is true so body inside loop is executed.
Now incremental statement i++ is executed and i increases by 1 (i.e i=2)
Again conditional statement is executed.
This process follows till the conditional statement turns out to be false(i.e i=5)

Now consider,

Try to compare this with the code explained above.
Take it as,
for(   ;   ;   ) {
 // your code

In this case when code enters for loop first time then as there is no initialization statement so nothing is executed.
Next we move on to conditional statement which is also empty. Remember, that empty statement here will execute to be true. So body inside for will get executed.
Now moving on to incremental statement, we see it is also empty so nothing gets executed.
Then conditional statement is executed again which will evaluate to true. So body inside for will get executed again.
This process will follow till eternity.

Conclusion Drawn :

for(   ;   ;   ) or for(;;)  will enter into infinite loop.

Reason : No initialization statement, its conditional statement always evaluates to be true and this statement has no increment/decrement value

You may also like to read:

No comments:

Post a Comment

If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.