Java - Sort three String values using if statement and String.compareTo method

Description

Sort three String values using if statement and String.compareTo method

Demo

public class SortStrings {

  public static void main(String args[]) {

    String a = "hello";
    String b = "goodbye";
    String c = "wake up";

    String temp;//  w  w  w  . j av a 2 s. c  om

    if (b.compareTo(a) < 0) {
      temp = a;
      a = b;
      b = temp;
    }

    else if (c.compareTo(b) < 0) {
      temp = b;
      b = c;
      c = temp;
    }

    else if (b.compareTo(a) < 0) {
      temp = a;
      a = b;
      b = temp;
    }

    System.out.println(a + " " + b + " " + c);
  }
}

Related Topic