Skip to content
Advertisement

Can we use semicolon independently at the beginning of a for-loop?

What is the meaning of this type of syntax in the for-loop?

public class ReverseNumber {

    public static void main(String[] args) {

        int num = 1234567, reversed = 0;

        for (; num != 0; num /= 10) { // <-- meaning of the first ; ?
            int digit = num % 10;
            
            reversed = reversed * 10 + digit;
        }

        System.out.println("Reversed Number: " + reversed);
    }
}

Advertisement

Answer

A for statement is composed of 3 parts for(statement A; statement B; statement C):

  • Statement A is the initializer statement. It is executed only one time. Usually, you create your variables you want to use in the for loop
  • Statement B is the stop condition. It is executed every time at the beginning of the for loop, to determine if you should do the for loop one more time
  • Statement C is the operation to execute every time at the end of the for loop (like incrementing your variable for instance).

All of them are optional. Here some examples of for loop:

for(;;) {
    // infinite loop
}

for(int i = 0; i < 10; i++) {
    // Loop 10 times and increment i each time
}
int b = i; // impossible. i does not exist anymore
// this for is equivalent to :
int i = 0;

for(; i < 10; i++) {
    // Almost the same. The difference here is that I can be accessed after the for loop
}
int b = i; // possible, because i is still visible. 

for(int a = 0;; a++) {
    // Infinite loop (because no stop condition) to increment variable a
    System.out.println(a);
}
for(int constant = 0;;) {
    // Infinite loop (no stop condition) and you can use constant variable (but will always be 0)
    System.out.println(constant);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement