javafor-loop

Multi-variable for-loop declaration in Java


What is the correct declaration of multi-variable for-loop declaration in Java?

  1. for (int a = 1; int b = 1; a <= 5; a++; b++)

  2. for (int a = 1, b = 1; a <= 5; a++; b++)

Different books uses different declaration.

I used both of them but in both cases, it resulted in syntax error.


Solution

  •     for (int a = 1, b = 1; a <= 5; a++, b++) {
            System.out.println(a);
            System.out.println(b);
        }
    

    Notice it should be a++, b++ and not a++ ; b++