Java – Incremental Operators

This topic will discuss about incremental operation in Java.

public static void main(String[] args) {
  // declare and initialize
  int addFirst = 0;
  int addLater = 0;
		
  System.out.println("AddFirst " + ++addFirst);
  System.out.println("addLater " + addLater++);
}

## Output ##
AddFirst 1
addLater 0

++addFirst yield value increment before it used while addLater++ yield value before increment. These are know as pre-increment and post-increment.

int a = 5;
int b = 3 - 2 * ++a; // increase then use

//  b = 3 - 2 * 6
//  b = 3 - 12
//  b = -9
System.out.println("b = " + b);

## Output """
-9


int c = 5;
int d = 3 - 2 * a++; // use then increase

// d = 3 - 2 * 5;
// d = 3 - 10;
// d = -7

Another example

int a = 5;
int b = ++a;  // increase then use, a = 6, b = 6
System.out.println("a = " + a + " b " + b);

## Output ## 
a = 6, b = 6


int c = 5;
int d = c++; // use then increase, d = 5,  c = 6
System.out.println("c = " + c + ", d = " + d);
## Output ## 
c = 6, d = 5

## Equivalent ##
int c = 5;
int d = 5;
c = c + 1;
System.out.println("c = " + c + ", d = " + d);
## Output ## 
c = 6, d = 5

Tricky question 1, what is the output?

int x = 3;
int y = ++x * 5 / x-- + --x;
System.out.println("X = " + x + " , Y = " + y);

Keep in mind, ++x = increase then use, x++ = use then increase. We can use x(y) for post-increment to indicate (current_value)(next_value).

int x = 3;
int y = ++x * 5 / x-- + --x;

x = 3;
y = 4 * 5 / 4(3) + --3(2); // x from 4(3) become 3, then --3 = 2
y = 4 * 5 / 4 + 2
y = 5 + 2
y = 7

System.out.println("X = " + x + " , Y = " + y);
## Output ##
X = 2 , Y = 7

Tricky question 2, what is the output?

int g = 6;
int h = 2;
int i = ++h + --g * 3 + 2 * g++ - h-- % --g;
System.out.println("g = " + g + " , h = " + h + " , i = " + i);

Explain

X(Y) to indicate post-increment value change to become later value.

int g = 6;
int h = 2;
int i = ++h + --g * 3 + 2 * g++ - h-- % --g;

=> (++2) + (--6) * 3 + 2 * g++  - h--  % --g;
=> (h=3) + (g=5) * 3 + 2 * 5(6) - 3(2) % (--6);  // g 5(6) become --6 = 5
=>  3 + 5 * 3 + 2 * 5 - 3 % 5;                   // h = 2, but never use 
=>  3 + 15 + 10 - 3;
=> i = 25, h = 2, g = 5
Java – Incremental Operators

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.