Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statement with logic built into it

I know this is probably a really simple question, but I ran across this in some code on a project today. How does the return statement work? What kind of operation is this? Is it similar to a tertiary operator?

The variable access is an int.

return access != IACL.RS_NOACCESS && documentVersion >= 0;
like image 408
Trevor Avatar asked Dec 07 '22 07:12

Trevor


2 Answers

Let's break it down, using parentheses to make the logical groupings explicit:

return ((access != IACL.RS_NOACCESS) && (documentVersion >= 0));

So, the method returns a boolean value, the result of the comparisons being performed. The entire expression is evaluated before the expression's value is returned.

Let's pretend that access is equal to IACL.RS_NOACCESS and documentVersion is equal to 1. Then the statement reduces to:

return ((IACL.RS_NOACCESS != IACL.RS_NOACCESS) && (1 >= 0));

and that evaluates to:

return ((false) && (true));

and that evaluates to:

return false;

One important note, pointed out by Ryan in a comment: logical operators like && and || are "short-circuiting" in most languages, in most scenarios. They are in Java. This means that evaluation proceeds from left to right. If there's no point in evaluating the second part of the expression, then it won't be evaluated.

In the case above, since the first part of the expression evaluates to false, it doesn't matter what the second part of the expression evaluates to - given the AND truth table, the full expression will always evaluate to false. In fact, you could have an expression that generates a run-time error on the right side - it doesn't matter. With these values, the right side never be run.

like image 115
Michael Petrotta Avatar answered Dec 14 '22 23:12

Michael Petrotta


The whole expression to the right of return evaluates to a boolean value, which is what's returned.

return access != IACL.RS_NOACCESS && documentVersion >= 0;

Is equivalent to:

boolean result = (access != IACL.RS_NOACCESS);
result = result && (documentVersion >= 0);
return result;
like image 45
Geeky Guy Avatar answered Dec 14 '22 23:12

Geeky Guy