Shortcut assignment and Pre – Postfixes
There also are two shortcut arithmetic operators, ++ which increments its operand by 1, and -- which decrements its operand by 1. There are two versions of this, prefix and postfix. Both the prefix and postfix versions of this operator increment the operand by 1. So why are there two different versions? Because each version evaluates a different value: x++ evaluates to the value of the operand before the increment operation, and ++x evaluates the value of the operand after the increment operation.
You use the basic assignment operator, = , to assign one value to another. Java also provides several short cut assignment operators that allow you to perform an arithmetic or logical operation and an assignment operation all with one operator. Suppose you wanted to add a number to a variable and assign the result back into the variable, like this:
x = x + 7;
You can shorten this statement using the short cut operator +=.
x += 7;
The two previous lines of CodeText are equivalent.
The table shows the shortcut assignment operators and their lengthy equivalents:
Operator Use Equivalent to
+= x += y x = x + y
–= x –= y x = x – y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
Exercise 3 – 1 evaluate the prefix and postfix operators
· Type in the following Code and compile it. Before you run the application, answer the questions that are in the comments. Now run the Code and see if your answers match the output.
public class Shortcut{
public static void main(String args[]){
int x = 10;
int y = 0;
// x will equal 10
System.out.println("X = " + x);
x+=2;
// question (1) what will x equal?
System.out.println("X = " + x);
y = x++;
// question (2) now what will y equal?
System.out.println("Y = " + y);
// question (3) but what is x now?
System.out.println("X = " + x);
y = ++x;
// question (4) what do you think y is now?
System.out.println("Y = " + y);
// question (5) how about x now?
System.out.println("X = " + x);
}
}
No comments:
Post a Comment