Java Reference
In-Depth Information
Continued from previous page
What value is z assigned? The answer is 220 . The third assignment increments
x to 11 and decrements y to 19, but in computing the value of z , it uses the new
value of x ( ++x ) times the old value of y ( y -- ), which is 11 times 20, or 220.
There is a simple mnemonic to remember this: When you see x++ , read it as
“give me x , then increment,” and when you see ++x, read it as “increment, then
give me x .” Another memory device that might help is to remember that C++ is a
bad name for a programming language. The expression “C++” would be inter-
preted as “evaluate to the old value of C and then increment C.” In other words,
even though you're trying to come up with something new and different, you're
really stuck with the old awful language. The language you want is ++C, which
would be a new and improved language rather than the old one. Some people
have suggested that perhaps Java is ++C.
Variables and Mixing Types
You already know that when you declare a variable, you must tell Java what type of
value it will be storing. For example, you might declare a variable of type int for
integer values or of type double for real values. The situation is fairly clear when
you have just integers or just reals, but what happens when you start mixing the
types? For example, the following code is clearly okay:
int x;
double y;
x = 2 + 3;
y = 3.4 * 2.9;
Here, we have an integer variable that we assign an integer value and a double vari-
able that we assign a double value. But what if we try to do it the other way around?
int x;
double y;
x = 3.4 * 2.9; // illegal
y = 2 + 3;
// okay
As the comments indicate, you can't assign an integer variable a double value,
but you can assign a double variable an integer value. Let's consider the second case
first. The expression 2 + 3 evaluates to the integer 5 . This value isn't a double ,but
every integer is a real value, so it is easy enough for Java to convert the integer into a
double . The technical term is that Java promotes the integer into a double .
The first case is more problematic. The expression 3.4 * 2.9 evaluates to the
double value 9.86 . This value can't be stored in an integer because it isn't an integer.
If you want to perform this kind of operation, you'll have to tell Java to convert this
 
Search WWH ::




Custom Search