4.1 The Increment and Decrement Operators
Incrementing and decrementing are such common operations that Java provides special operators for them. The ++ operator adds one to the current value of an int or char. -- subtracts one. Neither operator works on doubles, booleans or Strings.
/**
* This program demonstrates the ++ and -- operators.
*/
public class IncrementDecrement
{
public static void main(String[] args)
{
int number = 50;
// Display the value in number.
System.out.println("Number is " + number);
// Increment number.
number++;
// Display the value in number.
System.out.println("Now, number is " + number);
// Decrement number.
number--;
// Display the value in number.
System.out.println("Now, number is " + number);
}
}
Output:Number is 50
Now, number is 51
Now, number is 50
Now, number is 51
Now, number is 50
Increment and decrement operators each have two forms: pre and post. In above example we have used the post form of increment and decrement operator
The example of the increment operator is:
Pre-increment:
++number;
Post-increment:
number++
The example of the decrement operator is:
Pre-decrement:
--number;
Post-decrement:
number--
Both the pre- and post-increment operators increment the value of the variable by 1. Similarly, the pre- and post-decrement operators decrement the value of the variable by 1. The difference becomes apparent when the variable using these operators is employed in an expression.
Suppose a and b are int variables and:
a = 5;
b = 10 + (++a);
To execute the second statement, first the value of a is incremented to 6. Then, 10 is added to 6 to get 16, which is then assigned to b. Therefore, after the second statement executes, a is 6 and b is 8.
On the other hand, after the execution of:
a = 5;
b = 10 + (a++);
first the value of a is added to 10, which is then assigned to b, after execution of statement a is incremented. Therefore, after the second statement executes, a is 6 and b is 15.
No comments:
Post a Comment