11
Hello!
Everyone programming in Java should be tired of using loops for
, that almost always has a syntax similar to this:
for (int x = 0; x < y; x++) {
...
}
I was analyzing some codes and came across a different syntax:
for (String novaString : arrayDeStrings) {
...
{
From what I understand, the loop will repeat X times, where X is equal to the size of the array of strings (arrayDeStrings.length
) and with each repetition, novaString
will receive the contents of one of the strings of arrayDeStrings
.
Doubts
Is this really how this second syntax presented works? Are there other syntaxes besides those mentioned in this question? If so, how do they work?
Right, so that’s how it works. There are other similar?
– AndersonBS
@Deyel by coincidence, I just posted.
– Bacco
Wow, great! I’ll wait a while before giving the best answer, to see if other people know other syntaxes...
– AndersonBS
@Deyel is not in a hurry, there is certainly a good people in Java here (and java is not really my thing). Things can appear much more elaborate!
– Bacco
yeah, I’m also not pro at java haha. Anyway thanks for the clarification!
– AndersonBS
+1 and I would add that the second code (using
Iterator
) is basically what the compiler will generate when it finds the.. in applied to aIterable
and - second that answer in Soen - the second code is what it will generate when applied to an array.– mgibsonbr
@mgibsonbr So you mean that the first syntax presented in the answer was only created to facilitate the use of the second? (mask the complexity)
– AndersonBS
@Deyel Yes, the second and the third. As far as I know, it is only a "syntactic sugar" even, it does not add anything that could not be done without it. But it certainly helps a lot in the clarity and conciseness of the code.
– mgibsonbr
Personally I think the second case is best expressed with a
while
and not afor
. And no, there are no other syntaxes offor
, if that’s what you want to know.– Piovezan
@Piovezan agree, but as the question was about syntax of For, I stayed within the "theme" :)
– Bacco