Here are some for-loop tricks you can do. Some of them are quite useful, and some of them are bad programming practice, but perfectly legal to the compiler.
Here's the general layout for a for loop:
Code :for (init;conditions;increment)
The for loop works like this:
a. Run init
b. Check the condition. If true, run the for-loop code. Else, stop
c. Run increment. Repeat b & c until stop
1. You don't need to have anything in any of init,conditions, or increment spots, or you can have any combination of used/unused spots. Note that if the condition block is empty, it will automatically assume true.
Code :for(;;) for (int i = 0;true;)
2. You can put valid single statement in any of the slots. Note that the conditions slot MUST evaluate to a boolean, or be empty. Code Blocks are not allowed.
Code :for (System.out.println("Initializing");true; System.out.println("Incrementing")) for (int i = 0, j = 0; i < 5 && j < 5; i++)
3. You can create a "for-each" loop on object types that implement the Iterator interface. Note however, if you do choose to use this method, you have absolutely no access to the location of that object within the original collection (mostly when working with arrays, or collections implemented with some sort of indices system)
Code :int[] a = new int[5]; for (int x :a){}
