Java Programming/Answers to Exercises
Exercise 1
editConsider the evaluation of the expression at the bottom of this code.
int a = 1; int b = 2; int c = 4; a = b = a * b / c + 1;
What order are the operators evaluated in? What are the final values of the three variables?
Answer
editThe operations with the highest precedence are the multiplication and the division. They associate left to right so the multiplication goes first, then the division and the addition. The assignment on the right goes next because assignment associates left to right.
Here is how it would go:
a = b = (a * b) / c + 1 a = b = (1 * 2) / c + 1 a = b = (2 / c) + 1 a = b = (2 / 4) + 1 a = b = 0 + 1 a = b = 1 -> assign 1 to b a = 1 -> assign 1 to a
The final values of the variables are a = 1, b = 1 and c = 4.
Exercise 2
editLook at the following code:
int i = 1; int j = 2; int k = i+++j; System.out.println ("i = " + i); System.out.println ("j = " + j); System.out.println ("k = " + k);
What is the output?
Extra credit: Change the declaration of k to be int k = i ++ + ++ j; What is the output now?
Answer
editFirst, evaluate the expression:
int k = i ++ + j; -> unary operator is postfix, remember it for later. int k = 1 + 2; int k = 3; -> assign 3 to k -> apply unary operator, i is now 2
So the output would be:
i = 2 j = 2 k = 3
Extra credit: First evaluate the expression:
int k = i ++ + ++ j; -> apply prefix operator, j is now 3 int k = i ++ + 3; -> unary operator is postfix, remember it for later int k = 1 + 3; int k = 4; -> assign 4 to k -> apply unary operator, i is now 2
So the output would be:
i = 2 j = 3 k = 4