The Java T compareTo method is used for comparing two objects of type T. It returns an integer value depending on the comparison result. If the first object is greater than the second, it returns a positive value. If the second is greater, it returns a negative value. If they are equal, it returns zero.
Examples:
1. Comparing Strings
String str1 = "hello"; String str2 = "world"; int result = str1.compareTo(str2); System.out.println(result); // Output: -15
In this example, the compareTo method is used to compare two String objects. They are not equal, and the compareTo method returns a negative value (-15), indicating that the first string is less than the second string.
2. Comparing Integers
Integer num1 = 10; Integer num2 = 5; int result = num1.compareTo(num2); System.out.println(result); // Output: 1
Here, the compareTo method is used to compare two Integer objects. The first object is greater than the second, so the compareTo method returns a positive value (1).
Package Library:
The T compareTo method is part of the Java standard library, which is included with the installation of the Java Development Kit (JDK). It is located in the java.lang package, which is automatically imported into all Java programs. No other package library is required to use this method.
Java T.compareTo - 30 examples found. These are the top rated real world Java examples of T.compareTo extracted from open source projects. You can rate examples to help us improve the quality of examples.