Increment / Decrement Operators ( JAVA )

Example 1 : Program that displays use of post-increment operator

class PostIncrOptDemo
{
public static void main(String args[])
{
int i = 5, j = 5, sum = 0;

System.out.println(“Value of i is ” + i + “, j is ” + j ” and sum is ” + sum);
sum = i + j++;
System.out.println(“Value of i is ” + i + “, j is ” + j ” and sum is ” + sum);
}
}

Output

Value of i is 5, j is 5 and sum is 0
Value of i is 5, j is 6 and sum is 10

Increment of variable j takes place after value of variable j is returned to expression so it will return value 5 to the expression.

Example 2 : Program that displays use of post-decrement operator

class PostDecrOptDemo
{
public static void main(String args[])
{
int i = 5, j = 5, sum = 0;

System.out.println(“Value of i is ” + i + “, j is ” + j ” and sum is ” + sum);
sum = i + j–;
System.out.println(“Value of i is ” + i + “, j is ” + j ” and sum is ” + sum);
}
}

Output

Value of i is 5, j is 5 and sum is 0
Value of i is 5, j is 4 and sum is 10

Decrement of variable j takes place after value of variable j is returned to expression so it will return value 5 to the expression.

Example 3 : Program that displays use of pre-increment operator

class PreIncrOptDemo
{
public static void main(String args[])
{
int i = 5, j = 5, sum = 0;

System.out.println(“Value of i is ” + i + “, j is ” + j ” and sum is ” + sum);
sum = i + ++j;
System.out.println(“Value of i is ” + i + “, j is ” + j ” and sum is ” + sum);
}
}

Output

Value of i is 5, j is 5 and sum is 0
Value of i is 5, j is 6 and sum is 11

Increment of variable j takes place before value of variable j is returned to expression so it will return incremented value 6 to the expression.

Example 4 : Program that displays use of pre-decrement operator


class PreDecrOptDemo
{
public static void main(String args[])
{
int i = 5, j = 5, sum = 0;

System.out.println(“Value of i is ” + i + “, j is ” + j ” and sum is ” + sum);
sum = i + –j;
System.out.println(“Value of i is ” + i + “, j is ” + j ” and sum is ” + sum);
}
}

Output

Value of i is 5, j is 5 and sum is 0
Value of i is 5, j is 4 and sum is 9

Decrement of variable j takes place before value of variable j is returned to expression so it will return decremented value 4 to the expression.

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

%d bloggers like this: