False positive on squid:S2275

When passing an array as the second argument to String.format, SonarLint picks it up as me providing too few arguments.

  • SonarLint for Eclipse
  • JDK8
  • Spring Tool Suite 4 - 4.6.1.RELEASE

Code to reproduce:

String.format("%d%d", IntStream.range(0, 2).toArray());

// or

String.format("%d%d", IntStream.range(0, 2).toArray(Object[]::new));

Hello @ShioT,

I’m confused, when I run the first example, I have an error and I can not even compile the second one.
Is IntStream indeed from java.util.stream? Am I missing something?

That being said, I agree that String.format supports arrays as argument, so

String.format("%d and %d", getArray()); // S2275: not enough arguments. FP

Object[] getArray() {
  return new Object[]{1,2};

should not raise an issue.

I will probably create a ticket once we figure out what I missed from the initial post.

Yes, IntStream is from the package you mentioned. It has been available since Java 8.


What is the error that you are facing? If you can’t compile the second one, I think you might be using jdk 7 or earlier.

For the first one, I have a runtime exception:

IllegalFormatConversionException: d != [I

And for the second one, IntStream does not have toArray() with an argument.

For the record, I already created a ticket (SONARJAVA-3506), since without even considering your examples we already have misbehavior when an array is passed as an argument of format.

Good to know, thanks. I am sorry that I have not verified my example; my actual (proprietary) code had some .map() in the middle of the stream operation and I did not realize that IntStream does not support Stream<Integer> methods. Adding a .mapToObj(Integer::valueOf) before .toArray() fixes the compilation problem (this time I have verified it):

String.format("%d%d", IntStream.range(0, 2).mapToObj(Integer::valueOf).toArray());
String.format("%d%d", IntStream.range(0, 2).mapToObj(Integer::valueOf).toArray(Object[]::new));

The problem behind is the same as the one I described in the ticket, I added the examples you shared there to be sure we correctly support them.

Thanks for coming back with precision.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.