Tuesday, January 25, 2011

varibale++ vs ++varibale confustion in Java

I just noticed that variable name ++ assignments can be bit confusing (may be due to the fact that I have been a Microsoft based programmer from almost 10 years).

here goes.


int r = 4;
int result = r++;

guess whats the result value going to be? it is still 4. Because Java won't perform the actual calculation of the operator until you use variable r somewhere in the code.

however if you use

int r = 4;
int result = ++r;

this will perform the arithmetic operation inline and return the result to 'result' variable.

No comments: