Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

58 HOUR 5:Storing and Changing Information in a Program


x++;
int answer = x * 10;

It’s easy to become exasperated with the ++and —operators because
they’re not as straightforward as many of the concepts you encounter in
this book.
I hope I’m not breaking some unwritten code of Java programmers by
telling you this, but you don’t need to use the increment and decrement
operators in your own programs. You can achieve the same results by
using the +and –operators like this:
x = x + 1;
y = y - 1;

Incrementing and decrementing are useful shortcuts, but taking the longer
route in an expression is fine, too.

Operator Precedence
When you are using an expression with more than one operator, you need
to know what order the computer uses as it works out the expression.
Consider the following statements:
int y = 10;
x = y * 3 + 5;

Unless you know what order the computer uses when working out the
math in these statements, you cannot be sure what the xvariable will be
set to. It could be set to either 35 or 80, depending on whether y * 3is
evaluated first or 3 + 5is evaluated first.
The following order is used when working out an expression:


  1. Incrementing and decrementing take place first.

  2. Multiplication, division, and modulus division occur next.

  3. Addition and subtraction follow.

  4. Comparisons take place next.

  5. The equal sign (=) is used to set a variable’s value.


Because multiplication takes place before addition, you can revisit the pre-
vious example and come up with the answer: y is multiplied by 3 first,
which equals 30, and then 5 is added. The x variable is set to 35.

NOTE
Back in Hour 1,“Becoming a
Programmer,” the name of the
C++ programming language was
described as a joke you’d
understand later. Now that
you’ve been introduced to the
increment operator ++, you have
all the information you need to
figure out why C++ has two
plus signs in its name instead
of just one. Because C++ adds
new features and functionality
to the C programming language,
it can be considered an incre-
mental increase to C—hence
the name C++.
After you work through all 24
hours of this book,you too will
be able to tell jokes like this
that are incomprehensible to
more than 99 percent of the
world’s population.

Free download pdf