Skip to main content

Section 2.4 Worked Example: Basic Knowledge

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

You can watch this video or read through the content below it.
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;
int eta, gamma;
double omega = 2.5;
double theta = -1.3;
double kappa = 3.0;
double lambda, rho;

lambda = alpha + delta;

Subsection 2.4.2 SG1 : Determine resultant data type of expression

The expression is the right-hand-side (RHS) of the statement: alpha + delta. In the first two lines, these variables were declared to be int type. Their sum will also be an int value.

Subsection 2.4.3 SG2: Update variable for pre-increment or pre-decrement operators (side effect)

NOT USED IN THIS EXAMPLE

Subsection 2.4.4 SG3: Evaluate arithmetic expression according to operator precedence

In the declarations, alpha was initialized with a value of 2, and delta was initialized with a value of 3.
The RHS of the statement is alpha + delta, so we replace those variable names with their actual values 2 + 3, which results in a sum of 5.

Subsection 2.4.5 SG4: 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.

The LHS is a variable of type double, and the RHS is type int. This is valid, as Java automatically promotes an int value when we assign it to a double.

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

NOT USED IN THIS EXAMPLE

Subsection 2.4.7 Questions to check understanding

int alpha = 2;
int delta = 3;
double lambda, rho;
lambda = alpha + delta;
Q1) In line 4 above, is the LHS of the statement a variable? What data type?
Q2) What is the resulting data type after evaluating the RHS of line 4?
Q3) Can the data type of the RHS result be assigned to the LHS variable in line 4?
Answer.
Q1-Answer) Yes, lambda is declared as a double
Q2-Answer) On the RHS, alpha + delta is evaluated as int + int which is int
Q3-Answer) Yes, an int can be assigned to a double (automatic promotion by adding .0)

Practice Pages.

You have attempted of activities on this page.