11.10. CompareTo Method Overview

CompareTo method overview

  • Eclipse: Oxygen
  • Java: 1.8

compareTo() method

This is a very useful method in Java. The compared methods are used to compare TWO OBJECTS and not two primitive datatypes. The output of the compared to the method is explained on the basis of some arguments. If we want to compare two primitive datatypes, we have to use Wrapper Class as studied earlier and convert it to objects.

The following snippet demonstrates the comparison between Part 1 and Part 2.

Let’s understand the compareTo method by the following table.

In the following program compareTo() method compares two Integer objects. This method returns the value 0 if both Integer is equal else it only results in either negative or positive value.

Output

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments