質問

I read somewhere that Java is supposed to 'short-circuit' once the If statement has reached a True boolean. However, I am currently experiencing a null pointer exception in the following code (which I have simplified for the purpose of this question):

currentFragment.setTag(HOME);
if( !currentFragment.getTag().equals(PROFILE) | 
        ( currentFragment.getArguments() != null &  
        currentFragment.getArguments().getInt("authorId") != userId) ) { }

Android developers will know that setTag() is not a real method, but in my actual code I have made sure that currentFragment.getTag() != PROFILE by error logging. However, when this code runs, it causes a null point exception at

currentFragment.getArguments().getInt("authorId") != userId

It should short-circuit at the very first condition before the | (OR) operator. Failing that, the next line should make sure the getArguments() != null, so why is it going all the way to the final condition? Can any explain the inner workings of what is going on here. Thanks.

役に立ちましたか?

解決

You're using & instead of &&. The former is bitwise AND and will evaluate both sides always. The latter stands for logical AND and will do short-circuit conditional evaluation.

More info: Java Tutorials: Operators

Solution for your current problem: use logical AND && instead of bitwise AND &. Similar for your bitwise OR |.

if( !currentFragment.getTag().equals(PROFILE) ||
    ( currentFragment.getArguments() != null &&
    currentFragment.getArguments().getInt("authorId") != userId) ) { }

他のヒント

& - Bitwise operator for AND
&& - Logical AND (AND gate of Digital logic)

The logical AND && performs Short-Circuit

"&" and "|" have two meanings, depending on their operands. Applied to integers, they are bitwise AND and OR respectively. Applied to boolean operands, they are the non-short-circuit versions of logical AND and OR.

People often forget their logical operator meaning, because almost always we use the short-cicuit equivalents, "&&" and "||".

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top