Home » Java programming language

Java File Class int compareTo(Object o) method with Example

Java File Class int compareTo(Object o) method: Here, we are going to learn about the int compareTo(Object o) method of File class with its syntax and example.
Submitted by Preeti Jain, on July 16, 2019

File Class int compareTo(Object o)

  • This method is available in package java.io.File.compareTo(Object o).
  • This method is used to compare string object with the given object passed as an argument whether they are lexicographically equal or not.
  • The return type is int that means if it returns 0 then both string and the given object are equal if it returns negative value then the string will be less than the given object as an argument and if it returns greater than 0 then the string will be greater than 0.

Syntax:

    int compareTo(Object o){
    }

Parameter(s):

We pass only one object as a parameter in the method of the File i.e Object of any type whether it is of string, int, etc. This argument will be compared with other string arguments.

Return value:

The return type of this method is int, it return integer value (0, greater than 0, and less than 0)

Java program to demonstrate example of compareTo() method

// import the File class because we will use File class methods
import java.io.File;

// import the Exception class because it may raise an 
// exception when working with files
import java.lang.Exception;

public class CompareStringWithObject {
    public static void main(String[] args) {
        try {
            int compare;

            // Declare a string .
            String str = "Hi, We are in Java World!!";

            // By using compareTo("Hi, We are in Java World!!") 
            // this method will return greater than 0 integer 
            // because String str length will be greater than the given argument.
            compare = str.compareTo("Hi, We are in Java World!!");

            if (compare == 0)
                System.out.println("Both are equal");
            if (compare < 0)
                System.out.println("string str is less than given argument in the method");
            if (compare > 0)
                System.out.println("string str is greater than the given argument in the method");

        } catch (Exception e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Output

E:\Programs>javac CompareStringWithObject.java

E:\Programs>java CompareStringWithObject
Both are equal


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.