java System.out.println() strange behavior long string

前端 未结 5 1358
再見小時候
再見小時候 2021-01-12 17:31

Can somebody explain me why this code does not print the numbers?

      String text = new String("SomeString");
      for (int i=0; i<1500; i++)          


        
5条回答
  •  自闭症患者
    2021-01-12 18:20

    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.

提交回复
热议问题