Java Operator Precedence

Profile picture for user arilio666

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

OperatorsPrecedenceAssociativity
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< > <= >= instanceofleft 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.

Tags