views:

159

answers:

4

Hi, I know that from C/C++, autoincrement operator has a different meaning depending on where it is applied (eg: integer = i++ vs. integer = ++i).

In Java do the following two statements mean the same thing?

int i = 1

driverVO.setUid(String.valueOf(i++)); //1?

driverVO.setUid(String.valueOf(++i)); //2?

+2  A: 
int x = 1;    
System.out.println(++x); // prints 2


int y = 1;
System.out.println(y++); // prints 1
gmcalab
Dead on, but for clarification this should be split into two examples:-------int x = 1; System.out.println(++x); // prints 2System.out.println(x); // prints 2-------int x = 1; System.out.println(x++); // prints 1System.out.println(x); // prints 2
Michael Krauklis
i fixed that, good point man.
gmcalab
+2  A: 
Groovy Shell (1.6.0, JVM: 1.6.0_05)
Type 'help' or '\h' for help.
-----------------------------------------------------
groovy:000> i=0
===> 0
groovy:000> j=0
===> 0
groovy:000> i++
===> 0
groovy:000> ++j
===> 1
groovy:000>

They operate as they do in C. Groovy is awesome for executing quick java tests.

(And yes, I realize they made some minor changes, but for the most part, if you execute Java code in groovy, it will execute just as it does in Java)

Bill K
Now, this is a tool that I need! Thanks :D
Midnight Blue
+3  A: 

In the first example, i will be incremented AFTER the rest of the statement.

In the second example, i will be incremented BEFORE it.

Aaron
that is a simple and concise answer; thank you
Midnight Blue
A: 

There is also a implementation difference between these two operators.

i++ ->It first copies a value of i to a temporary space, increments i and returns the saved value.

++i->Increments the value and returns it.

I might be wrong on that but using the second one will probably have better performance (Especially if i is an object).

Birkan Cilingir
I cannot be an object in java, ++ is only implemented for native variables (and I don't think for floating point). Also, the Runtime probably does very smart things--for instance if you don't use the result, it probably doesn't even generate one. I wouldn't bet on it following the same rules as C++
Bill K