Skip to content
Related Articles

Related Articles

Operators Precedence in Scala
  • Last Updated : 25 Jun, 2019

An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence.

For example, 10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30.
when two operators of the same precedence appear in expression associativity is used. Associativity can be Right to Left or Left to Right. For example ‘*’ and ‘/’ have the same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is worked as “(100 / 10) * 10”.

In below table operators with the highest precedence appear at the top of the table and operators with the lowest precedence appear at the bottom.

Operator

Category

Associativity



()[]Postfix

Left to Right

! ~UnaryRight to Left
* / %MultiplicativeLeft to Right
+ –AdditiveLeft to Right
>> >>> <<ShiftLeft to Right
< <= > >=RelationalLeft to Right
== !=Relational is equal to/is not equal toLeft to Right
== !=EqualityLeft to Right
&Bitwise ANDLeft to Right
^Bitwise exclusive ORLeft to Right
|Bitwise inclusive ORLeft to Right
&&Logical ANDLeft to Right
| |Logical ORLeft to Right
= += -= *= /= %= >>= <<= &= ^= |=AssignmentRight to left

,

Comma (separate expressions)Left to Right

Below is the example of operator Precedence.

Example :




// Scala program to show Operators Precedence
  
// Creating object
object gfg
{
    // Main method
    def main(args: Array[String])
    {
      
        var a:Int = 20;
        var b:Int = 10;
        var c:Int = 15;
        var d:Int = 5;
        var e = 0
          
        // operators with the highest precedence
        // will operate first
        e = a + b * c / d; 
              
        /* step 1: 20 + (10 * 15) /5
            step 2: 20 + (150 /5)
        step 3:(20 + 30)*/
              
        println("Value of a + b * c / d is : " + e )
      
    }
}

Output:

Value of a + b * c / d is : 50

In above example e = a + b * c / d; here, e is assigned 50, not 120 because operator * has a higher precedence than / than +, so it first gets multiplied with 10 * 15, then divide by 5 and then add into 20.

My Personal Notes arrow_drop_up
Recommended Articles
Page :