I came across a strange problem recently. I am using StringBuffer
to create a string and when I added some white spaces to the string, I realized that some characters were gone.
An example:
public static void main(String[] args) throws Exception {
StringBuffer sb = new StringBuffer();
sb.append("000.00 ");
sb.append(filler(800));
sb.append(filler(800));
sb.append(filler(800));
sb.append(filler(800));
sb.append(filler(800));
System.out.println(sb.toString());
System.out.println(sb.toString().charAt(4));
}
public static String filler(Integer size) {
return String.join("", Collections.nCopies(size, " "));
}
Output running in Eclipse:
000.
0
filler
is a function to create blank strings.
When I run that, the last two zeros of my initial string simple disappears. The curious is that if I print the value of the position in those positions, the zero appears.
Is that some kind of bug on StringBuffer class?
It is a rendering problem probably specific to your IDE as you output a String
with a relative important number of characters.
If I run your program on Eclipse I see indeed an unexpected output :
000.
While I expected 000.00
as beginning of the line.
But if I copy the beginning of the line produced in the Eclipse console and I paste it somewhere else, I see the expected output :
000.00
Make a substring of the StringBuilder
and you could see an accurate visible output :
System.out.println(sb.substring(0,6));
For information the problem occurs only at the last append()
:
sb.append(filler(800));
sb.append(filler(800));
sb.append(filler(800));
sb.append(filler(800));
sb.append(filler(800)); // issue in the output from there
Note that you can force in the Eclipse preferences the maximum character width. It will cause a wrap line at each time the maximum character width is reached for a line.
For example with this setting I can see now the output as expected :
000.00
But as side effect, I would have a breakline
in the output at each time my line exceeds the fixed limit.