Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8316995

String.compareTo() does not compare digits but simply compares char[] from the beginning to the end

XMLWordPrintable

    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      String temp1 = "2";
      String temp2 = "19";
      int result1 = temp1.compareTo(temp2);
      The test code is as above:
      According to the default value of result1, it should be a negative number, but the result is a positive number. I looked at the source code of compareTo, which converts two String types into Char[] arrays to compare the sizes. When compared to char[0] = 2, and When temp2's char[0]=1, the result has been returned. There is no comparison of the digits, but a simple comparison from beginning to end.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
        public static void main(String[] args) {
               //actual quantity
               String temp1 = "2";
               //Actual quantity received
               String temp2 = "19";
               //The number of masters to be issued
               String temp3 = "2.0000";
               //The number of real issuers
               String temp4 = "21.0000";

               int result1 = temp1.compareTo(temp2);
               int result2 = temp3.compareTo(temp4);

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Default result:
      result1 is a negative number
      result2 is a negative number
      ACTUAL -
      actual results:
      result1 is a positive number
      result2 is a negative number
      ---------- BEGIN SOURCE ----------

      public class CompaerNumTest {
          public static void main(String[] args) {
              //actual quantity
               String temp1 = "2";
               //Actual quantity received
               String temp2 = "19";
               //The number of masters to be issued
               String temp3 = "2.0000";
               //The number of real issuers
              String temp4 = "21.0000";

              int result1 = temp1.compareTo(temp2);
              int result2 = temp3.compareTo(temp4);

              if (result1>=0 && result2>=0){
                  System.out.println(result1);
                  System.out.println(result2);
              }

          }
      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      For the time being, I convert the String type to Double type for size comparison.

            tongwan Andrew Wang
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: