Path compareTo() method in Java with Examples
The Java Path interface was added to Java NIO in Java 7. The Path interface is located in the java.nio.file package, so the fully qualified name of the Java Path interface is java.nio.file.Path. A Java Path instance represents a path in the file system. A path can use to locate either a file or a directory.path of an entity could be of two types one is an absolute path and the other is a relative path. The absolute path is the location address from the root to the entity while the relative path is the location address that is relative to some other path.
compareTo(java.nio.file.Path) method of java.nio.file.Path used to compare two abstract paths lexicographically. Two paths can be compared by this method. The ordering of paths defined by this method is provider-specific, and in the case of the default provider, platform specific. This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument. This method does not access the file system. There is no need for a file is required to exist. This method may not be used to compare paths that are associated with different file system providers.
int compareTo(Path other)
Parameters: This method accepts a single parameter another path which is the path compared to this current path.
Return value: This method returns zero if the argument is equal to this path, a value less than zero if this path is lexicographically less than the argument, or a value greater than zero if this path is lexicographically greater than the argument.
Exception: This method throw and Exception ClassCastException if the paths are associated with different providers.
Below programs illustrate compareTo(java.nio.file.Path) method:
Both are equal
Path 2 is greater than path 1
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.