Help Explain Java Function

Posted on 2011-10-22
Medium Priority
Last Modified: 2012-05-12
Can someone please do two things for me.

import java.util.Arrays;

class Person implements Comparable<Person> {
  public Person(String firstName, String surname) {
    this.firstName = firstName;
    this.surname = surname;
  public String toString() {
    return firstName + " " + surname;
  public int compareTo(Person person) {
    int result = surname.compareTo(person.surname);
    return result == 0 ? firstName.compareTo(((Person) person).firstName) : result;
  private String firstName;
  private String surname;
public class MainClass {
  public static void main(String[] args) {
    Person[] authors = { new Person("A", "B"), 
                         new Person("C", "D"),
                         new Person("E", "F"), 
                         new Person("Z", "Y"),
                         new Person("X", "T"), 
                         new Person("O", "R") };
    System.out.println("\nThe cast is ascending sequence is:\n");
    for (Person person : authors) {

Open in new window

1) Tell me when does the compareTo function get called? Because Comparable is implemented, does it automatically get ran when the Person class is initiated?

2) Rewrite the line:

return result == 0 ? firstName.compareTo(((Person) person).firstName) : result;

to a more simplified if statement

Question by:InquisitiveProgrammer
  • 2
  • 2
  • 2

Accepted Solution

mlempert earned 2000 total points
ID: 37012710
1) Arrays.sort(authors); calls compareTo() on the Objects in the array.  compareTo()  is not called when the the Object is instantiated.

if (result ==0) {
    result = firstName.compareTo(person.firstName);
return result;

Author Comment

ID: 37012793
How does the program know not to use the generic Arrays.sort method?
LVL 47

Expert Comment

ID: 37013220
What do you mean by generic Arrays.sort method ?

I think your invocation

corresponds only to this method
public static void sort(Object[] a)


Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!


Author Comment

ID: 37013246
What I mean is, how does the line


know to call the compareTo function of the Person class
LVL 47

Expert Comment

ID: 37013285
Well, it looks at your array - it figures out that your array is composed of objects of the type Person
and uses Person's compareTo function.
that is something which is called polymorphism in Java -
when a method is invoked on the object, then the method corresponding to
the actual type of the instance is invoked (basically method corresponding to new command
which was used to construct this instance) is invoked, not the method of its parent.

It is like this:

class A {

public void method(){
//some stuff


class B extends A {

public void method() {
// another stuff


class TestPolymorphism {

public static void main(String [] args){

A a = new A();

A b = new B();


// at this point if you invoke method b.method() then   //another stuff   will be exected from overriden method of subclass
// not the method of superclass, even though you declared b as belonging to type A
// the method corresponding to creation of b with new B() operator will work
//this is called polymorphism; it applies only to methods; variables of inherited classes behave differently



Therefore even though sort method expects Objects it will recognize that your objects are in fact Persons
at the time when it needs to invoke their

read more about polymorphism here:


Expert Comment

ID: 37019270
All elements in the array must implement the Comparable interface which forces your objects to have the compareTo(Object) method implemented.
The sort will cast each element of the array as a Comparable and call compareTo(Object) to order the array.  This is a snippet from the Arrays class:
            for (int i=low; i<high; i++)
                for (int j=i; j>low &&
                   ((Comparable)dest[j-1]).compareTo((Comparable)dest[j]) > 0; j--)
                      swap(dest, j, j-1);

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month15 days, 20 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question