How does Increment operator work in Java?

explain working of post and pre increment operator in Java

  • can you explain me the output of this in case of Java int a=5,i; i=++a + ++a + a++; i=a++ + ++a + ++a; a=++a + ++a + a++; System.out.println(a); System.out.println(i); The output is 20 in both cases

  • Answer:

    Does this help? i=++a + ++a + a++; => i=6 + 7 + 7; (a=8) i=a++ + ++a + ++a; => i=5 + 7 + 8; (a=8)

Ankit Sachan at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

i=++a + ++a + a++; is i = 6 + 7 + 7 Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8. i=a++ + ++a + ++a; is i=5 + 7 + 8 Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.

codaddict

++a increments a before it is evaluated. a++ evaluates a and then increments it.

Aurril

when a is 5, then a++ gives a 5 to the expression, and ++a gives a 6 to the expression. So you calculate i = 6 + 7 + 7 i = 5 + 7 + 8

Thorbjørn Ravn Andersen

++a increments and then uses the variable a++ uses and then increments the variable if you have a = 1 and you do System.out.println(a++) //you will see 1 //Now a is 2 System.out.println(++a) //you will see 3 codaddict explains your particular snippet

Lombo

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.