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

Integer.parseInt("-") returns 0 instead of throwing NumberFormatException

XMLWordPrintable

    • 1.1
    • sparc
    • solaris_1, solaris_2.4
    • Not verified

        [Tim, 6/12/96:] Bug 1228227, a duplicate of this one, also points out that the
        problem exists for Long.parseInt...]

        java.lang.Integer.parseInt("-") returns 0 instead of throwing a
        NumberFormatException. The relevant code:

            public static int parseInt(String s, int radix) throws NumberFormatException {
                if (s == null) {
                    throw new NumberFormatException("null");
                }
        int result = 0;
        boolean negative = false;
        int i=0, max = s.length();
        if (max > 0) {
        if (s.charAt(0) == '-') {
        negative = true;
        i++;
        }
        while (i < max) {
        int digit = Character.digit(s.charAt(i++),radix);
        if (digit < 0)
        throw new NumberFormatException(s);
        result = result * radix + digit;
        }
        } else
        throw new NumberFormatException(s);
        if (negative)
        return -result;
        else
        return result;
            }

        For a string containing just "-", negative is set to true
        but the while loop is never entered. The method then returns zero.


        FWIW -- the original report to java@java:

        > From: ###@###.###
        > Date: Tue, 14 Nov 1995 10:56:35 -0800
        >
        > Why following expression does not throw an exception rather it returns zero.
        >
        > num = Integer.parseInt("-");
        >
        > According to API documentation above expression should throw an exception.

        The description field as copied from bug report 1232934 follows:

        The call Integer.parseInt("-", 10) incorrectly returns 0.
        It should throw a NumberFormatException.

        There is a similar problem with Long.parseLong("-", 10).

              tlindholsunw Timothy Lindholm (Inactive)
              duke J. Duke
              Votes:
              0 Vote for this issue
              Watchers:
              0 Start watching this issue

                Created:
                Updated:
                Resolved:
                Imported:
                Indexed: