java - Increment Decrement operator use -


in below programs , post increment operator used after completion of expression evaluation. first program shouldn't answer 40 n value of incremented 41.n likewise program 2 answer should 41 instead of 42?

class incrementdemo{ public static void main(string [] args){      int a=20;     a= a++ + a++;     system.out.println(a); //answer given 41 }  class incrementdemo{ public static void main(string [] args){      int a=20;     a= a++ + ++a;      system.out.println(a); }  

answer given 42 second program.

you can understand behaviour if analyze how statement executed , state of a in meanwhile.

a = 20 a++ executed, 20 result of evaluation, = 21 second a++ executed, 21 result, = 22 2 results added, 20 + 21 = 41, = 41 

on other side, in second case:

a = 20 a++ executed, 20 result of evaluation, = 21 ++a executed, = 22, 22 result 2 results added, 20 + 22 = 42, = 42 

this because 2 increment operators evaluated sequentially, second sees effect of first one.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -