Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what cases would it be useful to put a command within a Java for-loop update statement? [closed]

Tags:

java

for-loop

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?

like image 997
Caffeinated Avatar asked Nov 14 '15 21:11

Caffeinated


People also ask

When would you use a looping statement in Java?

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.

Which situation work best with a 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.

What are the 3 looping statements used in Java?

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.

What is the importance of Java for-each loop?

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.


3 Answers

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.

like image 110
tixopi Avatar answered Oct 26 '22 05:10

tixopi


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.

like image 3
Ankur Shanbhag Avatar answered Oct 26 '22 04:10

Ankur Shanbhag


You may also do it this way

for (int j = 0; j < myArray.length; System.out.println(j++)) {

}
like image 3
Huzaima Khan Avatar answered Oct 26 '22 04:10

Huzaima Khan