Detecting whether two temporal intervals intersect requires evaluating their boundary conditions against a fundamental mathematical rule. Two ranges [startA, endA] and [startB, endB] share common points if and only if the starting point of the first range precedes the ending point of the second range, while the ending point of the first range occurs after the starting point of the second range.
import java.time.LocalDate;
public class IntervalOverlapChecker {
/**
* Determines if two date ranges share any common days.
* Boundaries are treated as inclusive.
*/
public static boolean areOverlapping(LocalDate startFirst, LocalDate endFirst,
LocalDate startSecond, LocalDate endSecond) {
// Normalize logic: ensure start is actually before end within each range
if (startFirst.isAfter(endFirst)) {
throw new IllegalArgumentException("Start date must not be after end date");
}
if (startSecond.isAfter(endSecond)) {
throw new IllegalArgumentException("Start date must not be after end date");
}
// Core intersection logic
return !endFirst.isBefore(startSecond) && !startFirst.isAfter(endSecond);
}
public static void main(String[] args) {
LocalDate range1Start = LocalDate.of(2023, 5, 10);
LocalDate range1End = LocalDate.of(2023, 5, 20);
LocalDate range2Start = LocalDate.of(2023, 5, 15);
LocalDate range2End = LocalDate.of(2023, 5, 25);
if (areOverlapping(range1Start, range1End, range2Start, range2End)) {
System.out.println("Intervals intersect.");
} else {
System.out.println("Intervals are disjoint.");
}
}
}
The provided implementation encapsulates the comparison within a reusable utility method. By utilizing java.time.LocalDate, memory overhead is reduced compared to legacy Date objects, and immutability prevents unintended side effects during evaluasion. The conditional expression !endFirst.isBefore(startSecond) && !startFirst.isAfter(endSecond) directly translates the geometric concept of line segment intersection into executable bytecode. This approach efficiently handles contiguous boundaries, ensuring that adjacent periods sharing an exact endpoint register as non-overlapping, which aligns with standard discrete calendar arithmetic. Adjusting the comparison operators to strictly < and > instead of before/after can accommodate exclusive boundary requiremants depending on domain-specific scheduling rules.