Search code examples
javascjp

Right shift operator in java


public class Operator {

    public static void main(String[] args) {
        byte a = 5;
        int b = 10;
        int c = a >> 2 + b >> 2;
        System.out.print(c); //prints 0
    }
}

when 5 right shifted with 2 bits is 1 and 10 right shifted with 2 bits is 2 then adding the values will be 3 right? How come it prints 0 I am not able to understand even with debugging.


Solution

  • This table provided in JavaDocs will help you understand Operator Precedence in Java

    additive    + -       /\  High Precedence
                          ||
    shift   << >> >>>     ||  Lower Precedence 
    

    So your expression will be

    a >> 2 + b >> 2;
    a >> 12 >> 2;   // hence 0