+ 3
How come the operation of a for statement does not need a semicolon?
public class HelloWorld { public static void main(String[] args) { for(int x = 0; x < 9; x++) { System.out.println("Hello World"); } } } My code gets an output of 9 hello worlds but my question is why does the declaration and initialization of my for statement have a semicolon and my condition of my for statement have a semicolon but the operator used at the end of the for statement not require a semicolon?
3 odpowiedzi
+ 3
in case of loops you put semicolon to end the loop at the particular instant . This type of loops with semicolon is used in case of do while statement .
do {
....statement 1
....statement 2
....
....
....statement n
}while(condition);
in case of conditions like if , else or switch we can't put a semicolon it will show an error cause what's the need of a condition when you end it at the same time when you start it .
+ 2
The for-loop contains of 3 parts:
1. Initialization of the counter
2. Condition
3. Update of the counter
So, only two semicolons are required for the loop to distinguish these parts.
Note, that you can place these parts out of the for-loop braces, but the semicolons are still necessary for the for-loop to be a valid one.
int i = 0; // Counter initialization
for (;;) {
if (i >= 10) break; // Condition
System.out.println(i);
i++; // Counter update
}
As you can see, if there is no condition in the body to break the loop, it will be eternal. So, don't use the for-loop in this variant, because it highly decreases the readability.
+ 1
I still don't understand. When we make an increment of the variable x its a statement so we add a semicolon but in this paticular scenario when x++ is put in a for statement the semicolon is not required.