Java - What is the output: for(num = 1; num <= 10; System.out.println(++num));

Question

What is the output?

for(int num = 1; num <= 10; System.out.println(num++));
for(int num = 1; num <= 10; System.out.println(++num));


Click to view the answer

1
2
3
4
5
6
7
8
9
10

2
3
4
5
6
7
8
9
10
11

Demo

public class Main {
  public static void main(String[] args) {
    for(int num = 1; num <= 10; System.out.println(num++));
    System.out.println();/*from  ww w .  ja  v  a2s  .c  om*/
    for(int num = 1; num <= 10; System.out.println(++num));
  }
}

Result

Note

num is checked and then ++num is computed.

for(int num = 1; num <= 10; System.out.println(num++));

can be rewritten as

for(int num = 1; num <= 10; System.out.println(num),num++);

while

for(int num = 1; num <= 10; System.out.println(++num));

can be rewritten as

for(int num = 1; num <= 10; num++, System.out.println(num));

Demo

public class Main {
  public static void main(String[] args) {
    for(int num = 1; num <= 10; System.out.println(num++));
    System.out.println();/*w  ww . java2s.c o  m*/
    for(int num = 1; num <= 10; System.out.println(++num));

    System.out.println();
    for(int num = 1; num <= 10; System.out.println(num),num++);
    System.out.println();
    for(int num = 1; num <= 10; num++, System.out.println(num));

  }
}

Result

Related Quiz