src/java.base/share/classes/java/util/Formatter.java

Print this page
rev 10977 : 8065070: (fmt) Avoid creating substrings when building FormatSpecifier
Reviewed-by: duke

@@ -2622,14 +2622,15 @@
         private int width;
         private int precision;
         private boolean dt = false;
         private char c;
 
-        private int index(String s) {
-            if (s != null) {
+        private int index(String s, int start, int end) {
+            if (start >= 0) {
                 try {
-                    index = Integer.parseInt(s.substring(0, s.length() - 1));
+                    // remove the matched trailing $
+                    index = Integer.parseInt(s, start, end - 1, 10);
                 } catch (NumberFormatException x) {
                     assert(false);
                 }
             } else {
                 index = 0;

@@ -2646,30 +2647,30 @@
             if (f.contains(Flags.PREVIOUS))
                 index = -1;
             return f;
         }
 
-        private int width(String s) {
+        private int width(String s, int start, int end) {
             width = -1;
-            if (s != null) {
+            if (start >= 0) {
                 try {
-                    width  = Integer.parseInt(s);
+                    width = Integer.parseInt(s, start, end, 10);
                     if (width < 0)
                         throw new IllegalFormatWidthException(width);
                 } catch (NumberFormatException x) {
                     assert(false);
                 }
             }
             return width;
         }
 
-        private int precision(String s) {
+        private int precision(String s, int start, int end) {
             precision = -1;
-            if (s != null) {
+            if (start >= 0) {
                 try {
                     // remove the '.'
-                    precision = Integer.parseInt(s.substring(1));
+                    precision = Integer.parseInt(s, start + 1, end, 10);
                     if (precision < 0)
                         throw new IllegalFormatPrecisionException(precision);
                 } catch (NumberFormatException x) {
                     assert(false);
                 }

@@ -2695,14 +2696,14 @@
         }
 
         FormatSpecifier(String s, Matcher m) {
             int idx = 1;
 
-            index(m.group(idx++));
+            index(s, m.start(idx), m.end(idx++));
             flags(s, m.start(idx), m.end(idx++));
-            width(m.group(idx++));
-            precision(m.group(idx++));
+            width(s, m.start(idx), m.end(idx++));
+            precision(s, m.start(idx), m.end(idx++));
 
             int tTStart = m.start(idx);
             int tTEnd = m.end(idx++);
             if (tTStart != -1 && tTEnd != -1) {
                 dt = true;