Saturday, October 25, 2025
HomeLanguagesJavaJava File Class compareTo() Method with Examples

Java File Class compareTo() Method with Examples

The compareTo() function compares two pathnames lexicographically. In Java, the method may be used to sort files. This type of activity is dependent on the system on which JVM is installed. When comparing pathnames on Unix systems, the alphabetic case matters, while it doesn’t on Windows.

Syntax:

public int compareTo(File pathname)

Parameters:

  • pathname – The abstract pathname against which this abstract pathname will be compared.

Returns: This method returns 0 if the argument is equal to this abstract pathname, a negative value if the abstract pathname is lexicographically less than the argument, and a value larger than 0 if the abstract pathname is lexicographically greater than the argument.

Example:

Java




// Java program to demonstrate the working 
// of compareTo() method of File class
  
import java.io.File;
  
public class GFG
{
    public static void main(String[] args) 
    {
        File f1 = new File("c:\\GEEKSFORGEEKS\\Gfg1.txt");
        File f2 = new File("c:\\GEEKSFORGEEKS\\Gfg2.txt");
   
        int value = f1.compareTo(f2);
   
        if (value == 0
        {
            System.out.println("Both files are equal");
        }
        else if (value > 0
        {
            System.out.println(" Gfg1 is greater than Gfg2");
        }
        else 
        {
            System.out.println(" Gfg2 is greater than Gfg1");
        }
    }
}


Output:

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS