0
int a=0;

    for (a=0; a++<=10;) {
        System.out.print(a+ " ");
    }

Output: 1 2 3 4 5 6 7 8 9 10 11  

Why does it prints 11 when the loop is said to end when the variable “a” reaches 10 also why it doesn’t start with 0 as postfix operator is used?

int a=3, b=4;

    int c = a + b++;

    System.out.println(+c);

Output: 7

Why the postfix increment operator doesn’t add a value in variable ‘b’? Shouldn't the output be like ‘8’?

tripleee
  • 175,061
  • 34
  • 275
  • 318
HQuser
  • 640
  • 10
  • 26

1 Answers1

2

a++ means use the value for a, then add 1.

So the first one will read the value of a as 10, then add 1, so it prints a value of 11.

The second one reads b as 4, so c=3+4=7. b becomes 5 after the addition is completed.

mmking
  • 1,564
  • 4
  • 26
  • 36
  • if that's correct then why series doesn't start with 0? – HQuser Mar 18 '15 at 19:52
  • @user2015669: Because by the time you use it in your `println`, it's *already* been incremented. The operator is in the `for` condition, so the `for` condition uses the old value. Then the body of the `for` is executed with `a` having the new value. – T.J. Crowder Mar 18 '15 at 19:53
  • When the condition is being checked in the `for` part, a=0. But after it was checked, it was incremented to a=1. So it will print `1` and not `0`. – mmking Mar 18 '15 at 19:54
  • Thanks a lot for clearing up my concepts! – HQuser Mar 18 '15 at 19:58