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