I found out yesterday that you can make a Java for-loop that looks like this
for (int j = 0; j < myArray.length; System.out.println(j), j++ ) {
/* code */
}
This looks really unusual to me. When is coding like this acceptable/useful?
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.
For Loop: A for loop is an iteration method that is best used when you know the number of iterations ahead of time. It's always followed by the initialization, expression and increment statements.
Java provides three repetition statements/looping statements that enable programmers to control the flow of execution by repetitively performing a set of statements as long as the continuation condition remains true. These three looping statements are called for, while, and do… while statements.
The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more readable. It is known as the for-each loop because it traverses each element one by one. The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order.
I would only ever do something like this if I had two loop variables, eg:
for(int i = 0, j = 10; i < 10 && j > 0; i++, j--) {
...
}
Apart from that, I would not recommend doing this as it obscures what the for loop is actually doing. It would be better to place any method calls with side effects inside the actual body.
This is equivalent to:
for (int j = 0; j < myArray.length; j++ ) {
System.out.println(j);
}
I dont see any advantage of using it other than to trick students in the exam. It could be useful to check if student understands the functioning of for
loop thoroughly.
You may also do it this way
for (int j = 0; j < myArray.length; System.out.println(j++)) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With