简体   繁体   中英

Java logical operators in return statements

So I'm working my way through some of the questions on codingbat.com to solidify some of the things I've learned so far, and es expected there's some questions where the provided answer is different than how I solved the problem. So for one question I used a style/format I saw in an answer for an earlier question and got it to work fine, but I just want some clarification on the logic.

Here is the question:

Given 2 int values, return true if they are both in the range 30..40 inclusive, or they are both in the range 40..50 inclusive.

Here is my code:

public boolean in3050(int a, int b) {
  boolean in3040 = (a >= 30 && a <= 40) && (b >= 30 && b <= 40);
  boolean in4050 = (a >= 40 && a <= 50) && (b >= 40 && b <= 50);

  return in3040 || in4050;
}

So this answer worked, however I would like an expplanation on the return statement and exactly how the OR operator works with the two boolean variables. Also how would the statement work if there was an AND operator or a NOT before one of the variables.

Thanks!

In Java a logical term is evaluated from left to right. This means:

  • for an OR-Statement: a || b --> if a is already true, then the whole term has to be true, b won't be evaluated, if a is false, b can still be true, in that case both variables would have been evaluated
  • for an AND-Statement: a && b-> if a is already false, then same logic applies: the b variable doesn't need to be evaluated

You can imagine rewriting your conditional operation as follows:

if (in3040) {
 return true;
}
if (in4050) {
 return true;
}

Considering the case of using the &&-Operator it would look like

if (!in3040) {
 return false;
}
if(!in4050) {
 return false;
}
return true;

这些运算符在return语句中的工作与程序中其他所有地方的工作完全相同。

Equivalency

return [some expression] is equivalent to return ([some expression])

Thus, return in3040 || in4050; return in3040 || in4050; is equivalent to return ( in3040 || in4050 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM