Skip to main content

Section 2.32 Worked Example: Method Calls

Subgoals for evaluating an assignment statement.

  1. Determine resultant data type of expression
  2. Update variable for pre operators based on side effect
  3. Solve arithmetic equation, operator precedence
  4. Is the Left Hand Side (LHS) of the assignment statement a variable? Check the data type of the value on right hand side (RHS) against data type of LHS variable.
  5. Update variable for post operators based on side effect

Subsection 2.32.1

Given the following code snippet, evaluate the final statement (the last line). If invalid, give the reason. If valid, what value is assigned to the variable? Note any possible side effects.
int alpha = 2;
int beta = 1;
int delta = 3;
double rho;

rho = beta + Math.pow(delta, alpha);

Subsection 2.32.2 SG1 : Determine resultant data type of expression

The expression is the right-hand-side (RHS) of the statement: beta + Math.pow(delta, alpha). Despite beta, delta, and alpha all being defined as int variables, we must check the API documentation for Math.pow to see what it returns.
Figure 2.32.1.
In this official documentation, directly from Oracle, the left-hand column includes the return type, specified here as double.
Since beta is an int, it will be promoted when it is added to the double value returned by Math.pow, and the final result is a double value.

Subsection 2.32.3 SG2: Update variables for any pre-increment or pre-decrement operators (side effects)

NOT USED IN THIS EXAMPLE

Subsection 2.32.4 SG3: Evaluate arithmetic expression according to operator precedence

To determine the result of the addition operator, we must first figure out the value returned from the method call to Math.pow().
So, we start with Math.pow(3, 2), and we must again check the documentation to be sure we know which argument is which. The API doc says, “Returns the value of the first argument raised to the power of the second argument.” Thus, we use base 3 to the power of 2, which is 9. Since the API doc indicates a return type double, we should think of this value as 9.0.
Then we can add beta, so 1 + 9.0 gives us the final return value 10.0

Subsection 2.32.5 SG4: If an assignment statement (=), is Left Hand Side (LHS) a variable? Check data type of value against data type of variable.

The LHS is a variable of type double, and the RHS is type double. This is valid.
If we had tried to assign the value of the RHS to an int variable, believing that all of the int operands would give us an int result, we would have had a compilation error for incompatible types. Ensuring compatible types is a common reason to check the API documentation for return types.

Subsection 2.32.6 SG5: Update variable for post-increment or post-decrement operators (side effect)

NOT USED IN THIS EXAMPLE
Answer.
rho is 10.0;

Practice Pages.

You have attempted of activities on this page.