JDK-7088271 : (fmt) String.format throws ArrayIndexOutOfBoundsException
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util
  • Affected Version: 6u26
  • Priority: P4
  • Status: Resolved
  • Resolution: Duplicate
  • OS: windows_7
  • CPU: x86
  • Submitted: 2011-09-08
  • Updated: 2013-06-20
  • Resolved: 2013-06-20
Related Reports
Duplicate :  
Description
FULL PRODUCT VERSION :
java version "1.6.0_27"
Java(TM) SE Runtime Environment (build 1.6.0_27-b07)
Java HotSpot(TM) 64-Bit Server VM (build 20.2-b06, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows [Version 6.1.7601]

A DESCRIPTION OF THE PROBLEM :
This code throws an ArrayIndexOutOfBoundsException:

String.format("%3.0g", 0.0);

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
The code above is 100% reliable. I tested it on 3 different machines.

ACTUAL -
ArrayIndexOutOfBoundsException

ERROR MESSAGES/STACK TRACES THAT OCCUR :
Here's the stack trace:
java.lang.ArrayIndexOutOfBoundsException
	at java.lang.System.arraycopy(Native Method)
	at java.util.Formatter$FormatSpecifier.addZeros(Formatter.java:3357)
	at java.util.Formatter$FormatSpecifier.print(Formatter.java:3251)
	at java.util.Formatter$FormatSpecifier.print(Formatter.java:3146)
	at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2718)
	at java.util.Formatter$FormatSpecifier.print(Formatter.java:2667)
	at java.util.Formatter.format(Formatter.java:2433)
	at java.util.Formatter.format(Formatter.java:2367)
	at java.lang.String.format(String.java:2769)
...

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
Source code to reproduce:
  String s = String.format("%3.0g", 0.0);

The code in error seems to be in java.util.Formatter$FormatSpecifier.addZeros:3357:
	    // Create new array with existing contents.
	    char[] tmp
		= new char[v.length + prec - outPrec + (needDot ? 1 : 0)];
	    System.arraycopy(v, 0, tmp, 0, v.length);

If prec - outPrec + (needDot ? 1 : 0) > 0, it tries to copy too much, which throws the exception.
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
round the double to a long and print that instead

Comments
Problem in both cases is due to the specified precision being 0 or 1 when the value to be formatted is zero thereby causing an AIOOBE in Formatter.addZeros().
20-06-2013