Given the below code:
package com.example.so.questions;
public class SO47660627CompilationAndIncrement {
public static void main(String[] args) {
int a = 0;
int b = 1;
int c = 0;
int d = 1;
int e = 0;
int f = 0;
int g = 1;
int h = 1;
int i = 0;
int j = 0;
a = b++;
c = ++d;
e = e++;
f = ++f;
i = g-(g++);
j = h-(++h);
System.out.println(" int a=0; b=1; a=b++ // a is : "+a+" and b is : "+b);
System.out.println(" int c=0; d=1; c=++d // c is : "+c+" and d is : "+d);
System.out.println(" int e=0; e = e++ ; // e is : "+e);
System.out.println(" int f=0; f = ++f ; // f is : "+f);
System.out.println(" int g=1; int i = g-(g++); // i is : "+ i);
System.out.println(" int h=1; int j = h-(++h); // j is : "+ j);
}
}
If you run FindBugs source code analyzer, it flags as a concern - the line comprising :
e = e++;
The explanation is :
Bug: Overwritten increment in
com.example.so.questions.SO47660627CompilationAndIncrement.main(String[])
The code performs an increment operation (e.g., i++) and then
immediately overwrites it. For example, i = i++ immediately overwrites
the incremented value with the original value.
On running the above code, the output is :
int a=0; b=1; a=b++ // a is : 1 and b is : 2
int c=0; d=1; c=++d // c is : 2 and d is : 2
int e=0; e = e++ ; // e is : 0
int f=0; f = ++f ; // f is : 1
int g=1; int i = g-(g++); // i is : 0
int h=1; int j = h-(++h); // j is : -1
From the above output, we can conclude that the the post or pre increment operation involves the creation of a temporary variable that stores the original value - prior to increment operation in case of post-increment operation and after the increment in case of pre-increment operation and then applies the result stored in the temporary variable further in the expression.