Search code examples
javaoperatorspost-incrementpre-increment

Output is 23.Please explain


This is my code snippet.

class Example{
public static void main(String[] args) {
int a=10;
int x;
 x= ++a + ++a;
System.out.println(x);
}
}

Output is 23. Need little help.


Solution

  • You can divide x= ++a + ++a; into 3 pieces.

    Firstly, the first ++a will be done. Then the second ++a will be done. Then the + will be done.

    So after the first ++a, a will be 11. After the second ++a, a will be 12. After the +, a will be 11 + 12 = 23.