Search code examples
javapost-incrementpre-increment

Semantics of pre- and postfix "++" operator in Java


I wondering to know why this snippet of code give output 112
How this last digit 2 was creating?

public static void main(String[] args) {
    int i = 0;
    System.out.print(++i);
    System.out.print(i++);
    System.out.print(i);

Why does this happen?


Solution

  • Your snippet it's translated as

    int i = 0;
    i = i + 1; // 1
    System.out.print(i); // 1
    System.out.print(i); // 1
    i = i + 1; // 2
    System.out.print(i); // 2
    

    That's why the final result it's a 2.

    ++i it's incrementing the variable before being called by the print method and i++ it's incrementing the variable after the method execution.