They can often replace each other.
|
can be written as follows using a for-statement:
(We simply use an empty statement as the INIT-STATEMENT and as the INCR-STATEMENT)
While-statement | Equivalent for-statement |
---|---|
a = 1; while ( a <= 10 ) { System.out.println(a); a++; } |
a = 1; for ( ; a <= 10 ; ) { System.out.println(a); a++; } |
that does not contain a continue-statement, can be written as follows using a while-statement:
(We move the INIT-STATEMENT before the while-statement and put the INCR-STATEMENT as the last statement in the body)
For-statement | Equivalent while-statement |
---|---|
for ( a = 1 ; a <= 10 ; a++ ) { System.out.println(a); } |
a = 1; while ( a <= 10 ) { System.out.println(a); a++; } |
|
Example:
Original for-statement | Abused for-statement |
---|---|
for ( a = 1 ; a <= 10 ; a++ ) { System.out.println(a); } |
a = 1; for ( ; a <= 10 ; ) { System.out.println(a); a++; } |
How to run the program:
|