-4

I have a program like this:

public class OCAJP {
    public static void main(String[] args) {
        int i=0;
        for(;i<2;i=i+5) {
            if(i<5) {
                continue;
            }
            System.out.print(i);
        }
        System.out.print(i);
    }
}

This gives me an output to be 5 rather than giving me 05. The continue statement used in if block must not be executing the if block but it shows its functionality to continue the for loop.

Vignan Sankati
  • 380
  • 5
  • 15
  • 2
    Why do you think it should give 05 ? – Suresh Atta Aug 11 '17 at 17:33
  • What do you think `continue` actually does? Because once reached, it goes back to the start of the loop, executes the statement `i=i+5`, checks it against the iteration value `i<2` returns `false` and then continues, but it still executes the `i=i+5` statement. – AntonH Aug 11 '17 at 17:34
  • 1
    Check out [Branching Statements](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html) – Vince Aug 11 '17 at 17:34
  • since continue is in if block, it should come out of if loop rather than not executing the rest of the statements in for loop. – Vignan Sankati Aug 11 '17 at 17:36
  • 2
    @Vignan You appear to be confusing `continue` and `break`. Continue will go back to the start of the loop, Break will break out of the loop. Also, `if` is not a loop. – AntonH Aug 11 '17 at 17:37
  • 3
    `continue` statements don't apply to `if` statements, only loops. You can't `continue` an `if` statement, so it will apply to the closest loop. Check out the link I posted. – Vince Aug 11 '17 at 17:37
  • continue is attached to the loop not the if (which is not a loop even though you are calling it one). – takendarkk Aug 11 '17 at 17:37
  • @AntonH @ Vince Emigh. Thanks :) – Vignan Sankati Aug 11 '17 at 17:39
  • Check out https://stackoverflow.com/questions/389741/what-is-the-continue-keyword-and-how-does-it-work-in-java?rq=1 it's in the recommended links to this question, and is quite à propos. – AntonH Aug 11 '17 at 17:39

3 Answers3

0

It doesn't print on the first round because of the continue statement since

i 

is still less than 5.

isaace
  • 3,336
  • 1
  • 9
  • 22
0

Yes, the block inside the if must be executed because 0 < 5. The increment is executed after the first loop, EVEN if the increment is a line before. Unfortunately it is confusing, sorry

Grim
  • 1,938
  • 10
  • 56
  • 123
0

You already said everything about how it works. continue statement is connected to for loop and you can use it to control the loop. It's meaning is "leave this iteration of loop, go back to loop definition and proceed with next iteration". Hence the first print, for i=0, doesn't execute.

Egan Wolf
  • 3,533
  • 1
  • 14
  • 29