1  import java.util.Scanner;
  2  
  3  /**
  4     This program demonstrates comparisons of numbers and strings.
  5  */
  6  public class Compare
  7  {
  8     public static void main(String[] args)
  9     {  
 10        // Integers 
 11  
 12        int m = 2;
 13        int n = 4;
 14  
 15        if (m * m == n)
 16        {
 17           System.out.println("2 times 2 is four.");
 18        }
 19  
 20        // Floating-point numbers
 21        
 22        double x = Math.sqrt(2);
 23        double y = 2.0;
 24  
 25        if (x * x == y)
 26        {
 27           System.out.println("sqrt(2) times sqrt(2) is 2");
 28        }
 29        else
 30        {
 31           System.out.printf("sqrt(2) times sqrt(2) is not four but %.18f\n", x * x);
 32        }
 33  
 34        final double EPSILON = 1E-14;
 35        if (Math.abs(x * x - y) < EPSILON)
 36        {
 37           System.out.println("sqrt(2) times sqrt(2) is approximately 2");
 38        }
 39  
 40        // Strings
 41  
 42        String s = "120";
 43        String t = "20";
 44  
 45        int result = s.compareTo(t);
 46  
 47        String comparison;
 48        if (result < 0) 
 49        {
 50           comparison = "comes before";
 51        }
 52        else if (result > 0)
 53        {
 54           comparison = "comes after";
 55        }
 56        else
 57        {
 58           comparison = "is the same as";
 59        }
 60  
 61        System.out.printf("The string \"%s\" %s the string \"%s\"\n", s, comparison, t);
 62  
 63        String u = "1" + t;
 64        
 65        System.out.printf("The strings \"%s\" and \"%s\" are ", s, u);
 66        if (s != u) { System.out.print("not "); }
 67        System.out.print("identical. They are "); 
 68        if (!s.equals(u)) { System.out.print("not "); }
 69        System.out.println("equal."); 
 70     }
 71  }
 72  
 73