kc ochibili
kc ochibili

Reputation: 3131

What does the semi-colon at the beginning of this loop mean?

I was reading an open source code when I came across this semi-colon. I initially thought it was an error but it wasn't.

whats the function of the semicolon right after the open brackets of the for-loop below?

       if (nCount > 0){
            for(; nCount > 0; nCount--){
                if (mBitmaplist[nCount - 1] != null){
                    mBitmaplist[nCount - 1].recycle();
                    mBitmaplist[nCount - 1] = null;
                }
            }
        }

Upvotes: 0

Views: 127

Answers (3)

bourneAgainJason
bourneAgainJason

Reputation: 29

Hope this example helps you understand better:

public static void main(String[] args) {
    int i = 0; // you normally put this before the first semicolon in next line
    for (;;) {
        if (i > 5) {
            break; // this "if" normally goes between the 2 semicolons
        }
        System.out.println("printing:" + i);
        i++; // this is what you put after the second semi-colon
    }
}

Have fun with Java and keep coding on!

Upvotes: 1

ajb
ajb

Reputation: 31699

The statement for (PART1; PART2; PART3) { BODY } works something like this:

PART1;

<<TOP OF LOOP>>
if PART2 is false then go to <<END OF LOOP>>;
do the BODY;
PART3;
go to <<TOP OF LOOP>>;

<<END OF LOOP>>

If you say for (; PART2; PART3) that just means PART1 does nothing. (Same thing for PART3. If you leave out PART2, then nothing is tested, and the go to <<END OF LOOP>> never happens. So the only way to get to the end of the loop is with a break or return or something.)

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240928

that means there is no statement for initializer part of for loop

similarly if you want to skip the increment portion of for loop it would look like

for( ; nCount > 0; ){
  // some code
}

// which is like while loop

From JLS this is the format of for loop

BasicForStatement:
    for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement

you can see that all 3 are optional

Upvotes: 5

Related Questions