This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Is it the last one ?
Posted by Kishori Sharan on October 02, 2000 at 10:37 AM
Hi Joe If I use ++ means it is also valid for -- . There are two kinds of increment operator e.g. pre increment operator and post increment operator. If you put the ++ before any variable it is known as pre-increment oparator e.g. ++myvar . When you put ++ after any variable then it is called post increment operator e.g. myvar++ . When you are using a variable like ++myvar in any expression then it means the variable's value will be incremented by one before evaluating the expression and the expression will be evaluated using the new incremented value of that variable. In case of post increment operator the expression uses the old value of the variable when evaluating the expression and after that it increments the value. Lets take an example. int a = 10 , b= 20, c = 0 ; c = a + b++ ; // value of c will be 30 and b will be 21 in this line Here we are using post increment operator with variable b. So the above ststement is equivalent of writing the two statements like c = a + b ; b = b + 1 ; So we combined the above two statements in c = a + b++ . However, if we use pre increment operator as c = a + ++b ; // Value of c will be 31 and value of b will be 21 In this case the statement is equivalent of writing b = b + 1 ; c = a + b ; Note that this time b = b + 1 ; is done first and c = a + b ; is done second. However, when you use increment ( post/pre ) operator on any variable like a++ ; //or ++a ; here it doesn't matter which type of increment operator you are using ( post/pre ) both have the same effect of incrementing the variable a by one. It doesn't matter in this case because you are not using the value of a ( pre-incremented or post-incremented ) anywhere else. If you use it you will be using after that statement ( a++; or ++a; ) is done. I would like to tell you one good/bad thing about these operator. Try a = a++ ; and a = ++a ; and see the result. When you try the same on C/C++ the result will be different. int a = 10 ; a = a++ ; System.out.println ( a ) ; will still print 10. So where did my theory of breaking the above statement in two go a = a++ ; can be writtenm as a = a ; a = a + 1 ; but it doesn't work in java. Try to figure it our. Thanx Kishori
Replies:
|