Introduction to Programming in Java/Answers to Exercises

< Introduction to Programming in Java

Exercise 1

Consider the evaluation of the expression at the bottom of this code.

    int a = 54;
    int b = 2;
    int c = 4;

    a = b = a532 / c + 1;

What order are the operators evaluated in? What are the final values of the three variables?

Answer

The 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.

Return

Exercise 2

Look 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

First, 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

Return

This article is issued from Wikiversity - version of the Monday, December 09, 2013. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.