Calculating with Numbers

beginner55 min

Basic mathematical operations

Java uses +, -, *, and / with the usual precedence: * and / before + and -.

Simple calculations

Precedence and parentheses

Parentheses run first. Without them, multiplication and division happen before addition and subtraction.

Order of operations

Key ideas

  • Expression: Values and operators that produce a single value.
  • Statement: A full instruction, usually ending with ;.
  • Precedence: * and / bind tighter than + and -.
  • Parentheses: Force a different evaluation order.

Calculating and printing

With +, Java evaluates left to right. Once one operand is a String, the rest are converted to strings and appended. Parentheses around (2 + 3) do the math first.

Division and data types

If both operands are integers, / truncates toward zero. If either operand is floating-point, you get a decimal result.

Integer vs floating-point division

Division habits

Good Practices:

  • Use double for calculations requiring decimal precision
  • Cast to (double) before division for exact results
  • Be aware of integer division truncation
  • Use parentheses to control evaluation order

Avoid:

  • Expecting decimals from integer division
  • Casting after division: (double)(a/b)
  • Dividing by zero (causes runtime error)
  • Forgetting precedence in mixed operations

Practical robot calculations

Assignment copies a value

  • a = b copies the value from b into a; b is unchanged.
  • Later changes to b do not change a.
  • Assignment runs once when that line executes.

Variable assignment example

Try It Yourself:

Exercise 1: Calculation Practice

  • Calculate the area of a rectangular robot base (length × width)
  • Compute average speed from distance and time with proper division
  • Create a battery percentage calculator with remaining time
  • Demonstrate the difference between integer and floating-point division
Practice with mathematical operations and calculations: