Can somebody explain me why this code does not print the numbers?
String text = new String("SomeString");
for (int i=0; i<1500; i++)
This is eclipse bug. Fixed width console fixes the output.
There are a couple things you could try. I'll give you an example of both.
First, in Java you can simply add strings together. Primitives such as int
should be automatically converted:
String text = new String("SomeString");
for (int i = 0; i < 1500; i++) {
text += i;
}
System.out.println(text);
Second, if the first method still isn't working for you then you can try to explicitly convert your int
to a String
like so:
String text = new String("SomeString");
for (int i = 0; i < 1500; i++) {
text += Integer.toString(i);
}
System.out.println(text);
To do the same more efficiently
StringBuilder text = new StringBuilder("SomeString");
for (int i = 0; i < 1500; i++) {
text.append(i);
}
System.out.println(text);
Both examples work for me on Java 6 update 32 and Java 7 update 3.
Woah, this is weird. I got the same result. At first glance, it looks like a bug in the JVM, but I tried running the program from the command-line and it works fine. It must be a bug in the Eclipse console. I found that changing the console to have a fixed width solves the display issue.
I also found that if you replace i + ""
with i + ","
it displays fine. It seems there's something Eclipse console doesn't like about having a long continuous stretch of pure numbers.
String text = "SomeString";
for (int i = 0; i < 15000; i++) {
// text = text.concat(i + ""); // Doesn't display correctly
// text += i; // Doesn't display correctly
text = text.concat(i + ","); // Displays correctly
// text += i + ","; // Displays correctly
}
System.out.println(text);
This bug is somewhat worrying to me. Good find!
UPDATE: I tried just printing a long line of "xxxxxx" and found that up to 32000 characters are displayed correctly. When the line goes to 32001 it's not displayed. When I put "12345" + "xxxxxxxxx...", I was still able to display 32000 "x" characters which means the line length is longer than 32000, so it's nothing to do with total line length. It seems that it's to do with the length of parts of String objects.
String.concat() accepts a String
parameter.
If you add "a number and a character" you are adding a string because the +
operator understands you are chaining String and numeric data.
Anyway code runs fine to me, numbers appended till 1499 as expected.