1

I don't think that the following:

i += 1

or

i = i + 1

is the same as ++i. Or am I wrong? Is there any way to do pre increment without using ++ operator?

jxStackOverflow
  • 328
  • 1
  • 7
  • 17
  • I believe there's lots out there on this. Your two statements are equivalent to ++i or i++ if they standalone (except maybe for some performance considerations). Where things get interesting is if you were to say things like array[i++] or array[++i] – Jeremy Kahan Feb 12 '20 at 03:35
  • Is there any way to use preincrement without the ++ operator? Yes, `i = i + 1` then use `i`. :) – datashaman Feb 12 '20 at 05:19

3 Answers3

2

They are the same. Unless for very simple expressions (like a loop condition), it is better to avoid the ++ or -- operators.

Jonas Fagundes
  • 1,519
  • 1
  • 11
  • 18
0

I can't add comments so posting related stackoverflow question here:

How do the post increment (i++) and pre increment (++i) operators work in Java?

JavaBloxx
  • 31
  • 1
  • 1
  • 5
0

As Jeremy already commented, i+=1; and i=i+1; are equivalent to ++i or i++ if they standalone lines of code. To achieve pre/post increment you will have to do the increment before/after the line where you want to use the variable as per the case.

eg- for post increment of a variable named i:

//use value of i here
i += 1;

for pre increment:

i += 1;
//use value of i here

In case of a loop, post increment is pretty straight forward:

for(var i=someValue; i<maxValue; i+=1){
//code here
}

For pre increment:

var i = someValue + 1;
for(; i<maxValue; i+=1){
//code here
}
Akash Bhardwaj
  • 346
  • 1
  • 3
  • 9