Java Operator Precedence

If there are multiple operators in java and it has to do certain actions based on that java programming language has certain precedence over the operators.

It means it will determine what operator goes first against the other operator.

Also, The large precedence operator is present on both ways it will determine the order associativity from where to start. It is simple as to which goes first and which comes second.

Example - Operator Precedence (* and +)

if we take precedence between * and + the * has precedence over the + operator.

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 10 , val2 = 20, val3, val4 = 10, val5;

        val5 = val2 + val1 * val4;
        System.out.println(val5);
    }
}

So from here, you may be wondering the output is going to be 300. But wrong, as we discussed java will give more importance to * first and performs the shared variable of * first. After that, it performs the + and thus bringing out the output of 120.

Output: 120

Operator Precedence And Associativity

Operators Precedence Associativity
postfix increment and decrement ++ -- left to right
prefix increment and decrement, and unary ++ -- + - ~ ! right to left
multiplicative * / % left to right
additive + - left to right
shift << >> >>> left to right
relational < > <= >= instanceof left to right
equality == != left to right
bitwise AND & left to right
bitwise exclusive OR ^ left to right
bitwise inclusive OR | left to right
logical AND && left to right
logical OR || left to right
ternary ? : right to left

assignment

= += -+ *= /+ %=

right to left

&= ^= |= <<= >>= >>>=

Example: Operator Associativity

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 10 , val2 = 20, val3, val4 = 10,val5;
    
        val5 = val2 + val1 * val4 / val2;
        System.out.println(val5);
    }
}

Output: 25

So, here based on the precedence and associativity of * and / which is from left to right. The first precedence is multiplication and then the division and then it adds up with val1.

Tue, 10/19/2021 - 11:28

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags