Search⌘ K

Solution Review 2: Expression Evaluation

Explore how to evaluate Java expressions by tracking variable changes, applying operator precedence, and using type casting. Learn to interpret shorthand operators and complex expressions to deepen your understanding of primitive types and arithmetic operations for the AP Computer Science exam.

We'll cover the following...
Java
class ExpressionEvaluattion
{
public static void main(String args[])
{
int x = 2; // x = 2
int y = 3; // y = 3, x = 2
double z = 5; // z = 5.0, y = 3, x = 2
x *= y; // z = 5.0, y = 3, x = 2*3 = 6
y = x + y + (int) z; // z = 5.0, y = 6+3+5 = 14, x = 6
z = x + y + y / z; // z = 6+14+(14/5.0) = 22.8, y = 14, x = 6
y++; // z = 22.8, y = 15, x = 6
x--; // z = 22.8, y = 15, x = 5
x = (int) z + y * x / y % x; // x = 22 + ((15*5) / 15)) % 5 = 22
System.out.println(x);
}
}

Explanation

Let’s go over the code line by line and keep track of each of the three variables.

  • In lines 5-7, we have three variables declared; variables x and y are of int type, whereas variable z is of double type.

  • Now, look at line 9. Remember that *= is shorthand for the arithmetic operation of multiplying the two numbers and assigning the resulting value to the variable on the left side of the *= sign. Thus, this line translates to:

    x = x * y;
    

    This way, the value of x is updated to 2×3=62 \times 3 = 6.

  • Now, look at line 10. Here, the value of y is updated to the sum of the three variables we have. Since we cannot add variables of different types, variable z is being type casted to int. Otherwise, it is a simple sum, i.e., the value of y becomes 6+3+5=146+3+5=14 ...