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.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты