Mixed Expression Gotcha!

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

What type (integer or floating point) of operator is the / in the following:

(12 + 0.0) / 7

Answer:

Floating point. Adding floating point 0.0 to the integer 12 results in a floating point 12.0. Now the division is floating point because one of its operands is. This is a common programming trick.

Mixed Expression Gotcha!

Look again at the rule:

If both operands are integers, then the operation is an integer operation. If any operand is floating point, then the operation is floating point.

The rule has to be applied step-by-step. Consider this expression:

( 1/2 + 3.5 ) / 2.0

What is the result? Apply the rules: innermost parentheses first, within the parentheses the highest precedence operator first:

( 1/2 + 3.5 ) / 2.0
  ---
  do first

Since both operands are integer, the operation is integer division, resulting in:

( 0 + 3.5 ) / 2.0

Now continue to evaluate the expression inside parentheses. The + operator is floating point because one of its operands is, so the parentheses evaluates to 3.5:

3.5 / 2.0

Finally do the last operation:

1.75

This is close to the result that you might have mistakenly expected if you thought both divisions were floating point. An insidious bug might be lurking in your program!

QUESTION 12:

Surely you want to try another! What is the result of evaluating this expression:

( a/b + 4) / 2

Assume that a contains 6 and b contains 12.0