Let’s discuss the opCmp function in this lesson.

opCmp for class objects

This operator is used when sorting class objects. opCmp is the function that gets called behind the scenes for the <, <=, >, and >=.

This operator must return a negative value when the left-hand object is before, a positive value when the left-hand object is after, and zero when both objects have the same sorting order.

Warning: The definition of this function must be consistent with opEquals(); for two objects that opEquals() returns true, opCmp() must return zero.

Unlike toString and opEquals, there is no default implementation of this function in Object. If the implementation is not available, comparing objects for sort order causes an exception to be thrown:

Get hands-on with 1200+ tech skills courses.