Search code examples
javaprefixpostfix-notation

Questions about Java loops and post/prefix operators


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’?


Solution

  • 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.