Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java comparesto, How does it work?

Options
  • 04-11-2013 10:20am
    #1
    Registered Users Posts: 474 ✭✭


    Hi there,
    I have (yet another!) question in Java. I am currently doing an exercise in Strings and my issue is with compares to.

    Essentially the exercise is this:
    Given the following code that prints, “0”:          
    1. Modify the string(s) so that a value greater than 0 is printed,
    and explain why this happens.    
    2. Modify the string(s) so that a value less than 0 is printed, and
    explain why this happens.


    This is the code I have:
    public class Ex_3_4 {

    public static void main(String[] args) {
    String eggs1 = "Cackle fruit";
    String eggs2 = "Cackle fruit";

    System.out.println(eggs1.compareTo(eggs2));//0

    eggs1 = "Cackles fruit";
    System.out.println(eggs1.compareTo(eggs2));//83

    eggs1 = "Cackle frui";
    System.out.println(eggs1.compareTo(eggs2));//-1

    }

    }

    what I want to know is, why am I getting the values 83 and -1?


Comments

  • Registered Users Posts: 1,990 ✭✭✭lynchie


    Javadoc for string explains the return values for compareTo inside Comparable. As to the reason for the exact return value look at the source inside String.java


Advertisement