Java Reference
In-Depth Information
The result is n equal to 5000. However, using the compound operator avoids the cast.
The following statements compile successfully and assign n to 5000:
19. long m = 1000;
20. int n = 5;
21. n *= m;
In this case, the value of m is implicitly cast to an int before the multiplication occurs.
An int times an int results in an int , so no cast is needed.
The Assignment Operators
According to the SCJP exam objectives, knowledge of the assignment operators is
limited to =, += and -=. Of course, if you understand how += and -= work, you understand
how the other compound assignment operators work!
The Arithmetic Operators
The exam objectives specifi cally mention having working knowledge of the following
arithmetic operators :
+ — : addition and subtraction
* / : multiplication and division
% : modulus
++ —— : increment and decrement
We will now discuss each of these operators in detail.
The Additive Operators
The operators + and - are referred to as additive operators . They can be evaluated on any
of the primitive types except boolean . Additionally, the + operator can be applied to String
objects, which results in string concatenation.
If the operands are of different types, the smaller operand is promoted to the larger. At a
minimum, the operands are promoted to int s. For example, the following innocent-looking
code does not compile. Can you see why?
short s1 = 10, s2 = 12;
short sum = s1 + s2; //does not compile!
Because a short is smaller than an int , both s1 and s2 are promoted to int s before the
addition. The result of s1 + s2 is an int , so you can only store the result in a short if you
Search WWH ::




Custom Search