Operators

Mixed Expressions

🙋 Need help? Ask an expert now!

Mixed expressions are comprised of multiple sub expressions at once. This is not as rampant in Java as it is in advanced algebra courses, but it is essential to remember the rules and use them. Take a look at these two mixed expressions.

MixedExpressionsExample.java
package exlcode;

public class MixedExpressionsExample {

  // Keep in mind that 1/3 = 0 because both 1 and 3 are integers
  public static double exampleVariableOne = ((1/3+7.5) / 2.5);
  public static int exampleVariableTwo = ((7/4 + 2/6) + 4);

  public static void main(String[] args) {
    System.out.println(exampleVariableOne);
    System.out.println(exampleVariableTwo);
  }
}

Do either of the results surprise you? Take a look at the details. Remember, if any of the operands are a floating point, the whole arithmetic operation becomes floating point. Also, parenthesis have the highest precedence in the order of operations and must be evaluated first. Let's rearrange the mixed expressions to the correct order of evaluation:

(1/3+7.5) / 2.5 = (0+7.5) / 2.5 = (7.5) / 2.5 = 3.0

(exampleVariableOne is a double, so the result is 3.0, not 3)

(7/4 + 2/6) + 4 = (1 + 0) + 4 = 5

Edit Me on GitHub!

Application Question

What will the value of varOne be after the following expression is evaluated?

double varOne = 8+7x4-2.0/4 + (5-3x4-2);