Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)
edited by

Below is my code implementation to sort by age-wise with compareTo method :

 public int compareTo(Student sNew)

    {

        return this.age-sNew.age;

    }

What is the use of “-”  in compareTo? 

Because here’s my code implementation without using “-” in compareTo method:

public int compareTo(Student sNew)

    {

        int returnValue=0;

        if(this.age>sNew.age)

        {

            returnValue=1;

        }else if(this.age<sNew.age){

            returnValue=-1;

        }else if(this.age==sNew.age)

        {

            returnValue=0;

        }

        return returnValue;

    }

Can anyone tell me what’s the use ‘-’ in compareTo operator and where it returns the value (0,1,-1)

1 Answer

0 votes
by (19.7k points)

compareTo method doesn’t return (0,1,-1). It returns 1 if the string is greater than the compared string. It returns -1 if the string is less than the compared string. It returns 0 if both the strings are equal. 

The “-” will simply subtract the ages. 

Interested in Java? Check out this Java Certification by Intellipaat.  

Related questions

0 votes
1 answer
asked Mar 3, 2021 in Java by RohitSingh (2.6k points)
0 votes
1 answer
asked Sep 11, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
asked Dec 17, 2020 in Python by laddulakshana (16.4k points)
0 votes
1 answer

Browse Categories

...