'Java: if statement can be simplified (box contains point)
I have the following statement to check if a Vector2D is within a box, and IntelliJ gives me a warning: "if statement can be simplified".
if(point.x < minX || point.x > maxX || point.y < minY || point.y > maxY)
return false;
How can I simplify this?
Solution 1:[1]
Whenever IntelliJ warns of a possible simplification, it often offers to perform the simplification (by clicking the yellow light bulb). What happens if you do that?
Solution 2:[2]
Try separating it into two if statements: one for "x" coordinates, one for "y".
if(point.x < minX || maxX < point.x)
return false;
else if(point.y < minY || maxY < point.y)
return false;
Solution 3:[3]
Maybe you could try something like this:
return new Rectangle(minX, maxX, minY, maxY).contains(point);
As far as simplifying from a boolean algebra perspective, you must be looking for Martin's answer. In fact, you don't even need to simplify it because the compiler will automatically do it for you. For example, !(a && b) will simplify to !a || !b because it is quicker to check each variable separately as opposed to creating a temp variable and check the value of that.
Solution 4:[4]
I would just do this.
return !(point.x < minX || point.x > maxX || point.y < minY || point.y > maxY);
and it would remove the warning.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MrBackend |
| Solution 2 | Stanislav Mamontov |
| Solution 3 | Josh M |
| Solution 4 | Neha Agarwal |
