1/*
2 * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/*
25 * @test
26 * @bug 8136500
27 * @summary Test Integer.toString method
28 */
29
30public class ToString {
31
32    public static void main(String[] args) throws Exception {
33        test("-2147483648", Integer.MIN_VALUE);
34        test("2147483647",  Integer.MAX_VALUE);
35        test("0", 0);
36
37        // Wiggle around the exponentially increasing base.
38        final int LIMIT = (1 << 15);
39        int base = 10000;
40        while (base < Integer.MAX_VALUE / 10) {
41            for (int d = -LIMIT; d < LIMIT; d++) {
42                int c = base + d;
43                if (c > 0) {
44                    buildAndTest(c);
45                }
46            }
47            base *= 10;
48        }
49
50        for (int c = 1; c < LIMIT; c++) {
51            buildAndTest(Integer.MAX_VALUE - LIMIT + c);
52        }
53    }
54
55    private static void buildAndTest(int c) {
56        if (c <= 0) {
57            throw new IllegalArgumentException("Test bug: can only handle positives, " + c);
58        }
59
60        StringBuilder sbN = new StringBuilder();
61        StringBuilder sbP = new StringBuilder();
62
63        int t = c;
64        while (t > 0) {
65            char digit = (char) ('0' + (t % 10));
66            sbN.append(digit);
67            sbP.append(digit);
68            t = t / 10;
69        }
70
71        sbN.append("-");
72        sbN.reverse();
73        sbP.reverse();
74
75        test(sbN.toString(), -c);
76        test(sbP.toString(), c);
77    }
78
79    private static void test(String expected, int value) {
80        String actual = Integer.toString(value);
81        if (!expected.equals(actual)) {
82            throw new RuntimeException("Expected " + expected + ", but got " + actual);
83        }
84    }
85}
86