Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

Java comparesto, How does it work?

  • 04-11-2013 09:20AM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2, Paid Member Posts: 2,032 ✭✭✭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