bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Tutorial
Java•Java Tutorial

Java Operator Precedence

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java Operator Precedence?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ result1 = 2 + 3 * 4; // 2 + 12 = 14
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Order of Operations
Why Does This Happen?
Java Operator Precedence

When a calculation contains more than one operator, Java follows order of operations rules to decide which part to calculate first.

For example, multiplication happens before addition:

Example

int result1 = 2 + 3 * 4;     // 2 + 12 = 14
int result2 = (2 + 3) * 4;   // 5 * 4 = 20
System.out.println(result1);
System.out.println(result2);

Why Does This Happen?

In 2 + 3 * 4 , the multiplication is done first, so the answer is 14 .

If you want the addition to happen first, you must use parentheses: (2 + 3) * 4 , which gives 20 .

Tip

Always use parentheses ( ) if you want to make sure the calculation is done in the order you expect. It also makes your code easier to read.

Order of Operations

Here are some common operators, from highest to lowest priority:

  • () - Parentheses
  • * , / , % - Multiplication, Division, Modulus
  • + , - - Addition, Subtraction
  • > , < , >= , <= - Comparison
  • == , != - Equality
  • && - Logical AND
-- Logical OR
  • = - Assignment

Another Example

Subtraction and addition are done from left to right, unless you add parentheses:

Example

int result1 = 10 - 2 + 5;    // (10 - 2) + 5 = 13
int result2 = 10 - (2 + 5);  // 10 - 7 = 3
System.out.println(result1);
System.out.println(result2);

Remember

Parentheses always come first. Use them to control the order of your calculations.

Previous

Java Logical Operators

Next

Java Strings