Student who enjoys programming here. I've been programming with java for 4 years, and I feel like I have a fairly good understanding of how the language works. Recently, however, I stumbled on something that surprised me quite a bit. While thinking about for loops, I thought "Hey the increment part of a for loop is just an operation, can I put other things in there?" and eventually after some playing around I decided to try this:
for(int i = 0; i < 10; i++, System.out.print("foo"), System.out.print("bar")){}
This is a totally empty for loop, with the print calls inside the loop's increment step. To my surprise, this loop functions correctly, and every time it loops it prints foo and bar. As far as I can tell, you can put as many methods in there as you'd like.
So what is this? I searched for it and didn't find anything. I've never learned about this. Should it be avoided? Should it be used? Why does it even work? I can't find any resources that show examples of this in use. Any input from real programmers would be great to hear!
This is covered by the Java Language Specification. Extract:
if the ForUpdate part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded.
Should it be used? In my opinion, no. It makes the code harder to read, and isn't idiomatic at all.
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