Precedence of Operators in Java Tutorial

In this section, we will learn what the operator precedence is and how it works in Java.

Note: we’re assuming you’re familiar with Java arithmetic operators.

What is Operator Precedence in Java?

Let’s start with a simple expression:

`int res = 10 – 2 * 4 /2`;

What is the value that will be set for the `res` variable?

The final value is 6. But how we’ve got this value?

This is where precedence comes in.

Based on precedence rules, arithmetic operators have different priority.

For example, the priority of the multiplication `*` operator is higher compared to addition `+` operator and so if we had an expression like `10+5*2` the result will be 20. This means in the expression before, first the two values 5 and 2 are multiplied together and the result is added to the value 10.

Arithmetic Operators Precedence

In the list below you can see operators in order of decreasing precedence:

Operators Associativity
() Left to Right
* / Left to Right
+ – Left to Right
= Right to Left

As the table above shows, parentheses have the highest priority and after that we have `multiplication& division` operators and next is `addition& subtraction` operators and at the end we have `assignment` operator with the lowest precedence.

Example: Operator Precedence in Java

For example, if we had an expression like this:

int iVar = (10 + 20) * 10;

First because the parentheses have higher priority than multiplication, the result in the parentheses should be declared first (The result is 30) and then this value 30 is multiplied by 10 and we get 300 and at the end it comes to the assignment operator and so this result is assigned to the `iVar` variable.

What is associativity of Operators in Java?

Associativity declares the order of operand execution.

For example, the associativity in arithmetic operators is from Left to Right. This means if we have an expression like `(4/2)*4`, the left operand executes first and then the right operand. So the result of the mentioned expression is:

2*4 = 8.

As you can see first, the result of the parentheses on the left side was declared and then this result is multiplied to the operand on the right side.

Example: Associativity of Operators in Java

public class Simple {
    public static void main(String[] args){
        int a = 10 ;
        int b = 20;
        int c = 30 ;
        int d = 40;

        int result = (a+b) * d; // (10+20) * 40
        System.out.println("The result is: "+ result);

        result = ((a+b) /2) * c; // ((10+20)/2) * 30
        System.out.println("The result is: "+ result);

        result = c+d/10 * d; // 30+((40/10) * 40)
        System.out.println("The result is: "+ result);

    }
}

Output:

The result is: 1200

The result is: 450

The result is: 190
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies