I found this code snippet in a program I'm looking at, can someone explain what's going on here?
return methodA() || methodB();
methodA and methodB eventually return booleans. Is this some kind of exception protection or will this statement always return methodA()?
It calls methodA
and checks the result. If true, it returns true immediately. Otherwise, it calls methodB
and returns that.
Anyway, this is known as a short circuiting operator. I'd recommend learning a bit more about Java's operators, because you'll probably see stuff like this a lot.
If the short circuiting behavior was not desired, they could have used
return methodA() | methodB();
Which will call both methods, perform a bitwise or on the results (which is equivalent to logical or on booleans) and return the result.
It means that if methodA
returns true
then use that as the return value, otherwise use the return value of methodB
. A sort of cascadingly evaluated return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With