previous | start | next

Order Comparisons

Another common mistake is to use one of the relational operators <, >, etc to compare class types.

Unlike ==, the compiler will catch this error.

Basic types

Use the relational operators: <, <=, etc., to compare the order of basic types:

    1   public static void main(String[] args)
    2   {
    3     Scanner in = new Scanner(System.in);
    4     int x, y;
    5   
    6     x = in.nextInt();
    7     y = in.nextInt();
    8   
    9     if (x < y) {
   10       System.out.printf("max is " + y);
   11     } else {
   12       System.out.printf("max is " + x);
   13     }
   14   }
Class types

Use the compareTo method to compare the order of class types. (Note that not all class types have this method.)

    1   public static void main(String[] args)
    2   {
    3     Scanner in = new Scanner(System.in);
    4     String x, y;
    5   
    6     x = in.next();
    7     y = in.next();
    8   
    9     if (x.compareTo(y) < 0) {
   10       System.out.printf("max is " + y);
   11     } else {
   12       System.out.printf("max is " + x);
   13     }
   14   }

Here max means occurs later in the ordering of the class type.

      x.compareTo(y)   Meaning
        < 0         x comes before y in the ordering
        == 0           x is equal to y
        > 0         x comes after y in the ordering

   


previous | start | next