byank
byank

Reputation: 1

Initialization before or inside the for loop in Java

Please tell me what's the difference of these two snippets of code:

int i = 0;
for(i; i < test; i++) {...}

and

for(int i = 0; i < test; i++) {...}

Is there any difference between these ways of initializing the i-increment variable? Does it affect anything or not?

Upvotes: 0

Views: 2176

Answers (4)

Fritz
Fritz

Reputation: 10055

In both cases, the variable is being defined once (no significant performance or memory issues). The differences come in scope and representation. On the first case i will be available outside the scope of the for statement.

The first case is useful, for example, if you want to find a the particular index of an element (tough there do exist better alternatives to this approach) or if you want to iterate until a certain condition is met and, then, know which index did your loop stop at.

Upvotes: 1

someone
someone

Reputation: 6572

in case one you can use i variable in out side of the for loop scope. in case two you cant do so. Only can use in for loop scope.

Upvotes: 1

P.P
P.P

Reputation: 121427

Difference is the scope of the variable i.

In the first one, i is visible outside the for loop and in the second one, it isn't.

Upvotes: 5

Matt Ball
Matt Ball

Reputation: 360026

The second one is idiomatic. The first one is not, and as such violates the principle of least astonishment.

Only use the second one if you need access to i before or after the for loop. I see nothing in this code to suggest that is the case, however.

Upvotes: 0

Related Questions