Empty-rectangle results from java.awt.Rectangle.intersection: safe to rely on for containment checks?
20K reputation · 13 Oct 2025, 10:29 UTC
I am working with java.awt.Rectangle and need to decide how to handle the result of intersection(Rectangle) when two rectangles do not overlap. The API documentation indicates the method returns an empty rectangle rather than null, and that a rectangle is empty when its width or height is less than or equal to zero.
My uncertainty is about downstream behavior: an empty rectangle contains no points, so a naive contains(x, y) check on the intersection result would simply return false. That seems convenient, but I am unsure whether relying on isEmpty() versus explicitly calling intersects() first is the intended pattern, especially since intersects avoids allocating a result object when only a boolean is needed.
A second concern is precision: Rectangle uses integer coordinates, while some of my inputs originate as floating-point geometry. I am unsure when the documented Rectangle2D.Double alternative becomes necessary, and whether negative width or height values in unnormalized inputs could silently produce empty results.
Is checking isEmpty() on the intersection result a documented, reliable way to detect non-overlap, or should intersects() always be preferred? At what point does integer precision justify switching to Rectangle2D? Do negative dimensions require normalization before any of these operations?