Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of "return methodA() || methodB()" in Java

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()?

like image 486
LiamRyan Avatar asked Dec 06 '22 09:12

LiamRyan


2 Answers

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.

like image 83
Antimony Avatar answered Dec 21 '22 23:12

Antimony


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.

like image 38
Grant Thomas Avatar answered Dec 22 '22 01:12

Grant Thomas