Java increment and decrement operator

An increment or decrement operator provides a more convenient and compact way to increase or decrease the value of a variable by one.
For instance, the statement x=x+1; can be simplified to ++x
Example:

int x =10;
++x; // x is now 11

The decrement operator (–) is used to decrease the value of a variable by one.

For instance, the statement x=x-1; can be simplified to –x

int x = 10;
--x; // x is now 9

Prefix and Postfix

Two forms, prefix and postfix, may be used with both the increment and decrement operators.With prefix form, the operator appears before the operand, while in postfix form, the operator appears after the operand. Below is an explanation of how the two forms work:
Prefix: Increments the variable’s value and uses the new value in the expression.
Example: 

int x = 3;
int y = ++x; // y is 4

The value of x is first incremented to 4, and is then assigned to y, so the values of both x and y are now 4. 

Postfix: The variable’s value is first used in the expression and is then increased.
Example:

int x = 3;
int y = x++; // y is 3

x is first assigned to y, and is then incremented by one. Therefore, x becomes 4, while y is assigned the value of 3.

The same applies to the decrement operator. 

Example:
//pre decrement
int x = 10;
int y = --x; // y is 9

The value of x is first decremented to 9, and is then assigned to y, so the values of both x and y are now 9.

//post decrement
int x = 10;
int y = x--; // y is 10

x is first assigned to y, and is then decremented by one. Therefore, x becomes 9, while y is assigned the value of 10.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s