What will be the result of compiling and running the following code?

public class MyFirst {
    static public  void main(String[] args) {  //1
        int a = 5;
        a = a!=0 ? a>1 ? a>>2 : a<<2 : a<1 ? a<<2 : a>>2;   //2
        System.out.println(a);
    }
}
Explanation
Ternary operator (elvis operator) ?: is executed like this:
condition ? expression if true : expression if false

Hence the given code can be replaced with several conditional operators:
a = [a != 0]?
[(a>1)?(a>>2):(a<<2)] <-if a is not equal to 0
:
[(a<1)?(a<<2):(a>>2)]; <-if a is equal to 0

and finally a will get the value of (a>>2), that is shifting 5 (binary value is 0101) to the right for 2 bits - that will be 0001, that equals to 1.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes