Boolean equal: 0 == a, does operand order matter?

2020-04-10 02:01发布

I saw some people wrote this Boolean equal in their code, I usually put constant at the right hand side of "==" operator. I notice 0 == a has faster operation than a == 0. Can someone explain why? And what's the best practice for it?

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-04-10 02:41

There is no difference but if you are working with string object like:

String s = null;

if(s.equals("yourValue")){
    // do something...
} else {
    // do other things...
}

will cause Exception while:

if("yourValue".equals(s)){
    // do something...
} else {
    // do other things...
}

this way will prevent the unnecessary Exceptions.

查看更多
登录 后发表回答