Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 4 ■ OPERATORS

The fifth line prints 1 because we use integer literals (as we covered in the previous chapter).
Consequently, we get back an integer literal. Java truncates (that is, throws away) any remainder when
dealing with integers, so 1.5 becomes 1. The last line uses floating-point literals, so it returns 1.5. A value
of 1.9 would also be truncated to 1. Truncation is not a kind of rounding; a truncated value has any value
to the right of the decimal place removed.
As a rule, remember to use parentheses to clarify your code and to ensure the proper order for your
operations. I mention clarity first for a reason: Clarity helps a lot. If you can gain clarity by splitting a line
onto multiple lines to make your operations clear for other developers (and for yourself when you return
to the code at a later date), then do so. Your fellow developers will thank you if they can understand your
code without a struggle.


Postfix Operators


The term postfix has a number of meanings in mathematics, linguistics, and other fields. In computer
science, it means an operator that follows an expression. Java's two postfix operators increment
(increase by one) and decrement (decrease by one) values. Listing 4-2 shows some examples:


Listing 4-2. Postfix operators


private int getC() {
int c = 0;
c++; // c = 1 now
c--; // c = 0 now
return c++; //returns 0;
}


So why does that return 0? Because the postfix operators first return the original value and then
assign the new value to the variable. That particular language detail bites a lot of new Java programmers.
To fix it, use the unary ++ operator (next on our list) before the expression rather than the postfix
operator after the expression or move your return statement to its own line. Parentheses around the
expression (c++) do not make this method return 1, by the way, because c would have been set to 0
within the parentheses.


Unary Operators


Strictly speaking, a unary operator is an operator that takes just one operand. By that definition, the
postfix operators are also unary operators. However, Java distinguishes between the postfix operators
and the other unary operators. As we learned previously, the postfix operators return the value before
the postfix operation has been applied. The unary operators return their values after the operator has
been applied. Table 4-2 briefly describes the unary operators (other than the postfix operators):

Free download pdf