The output -1 becomes a slash in the loop

前端 未结 3 1522
轻奢々
轻奢々 2021-01-31 07:26

Surprisingly, the following code outputs:

/
-1

The code:

public class LoopOutPut {

           


        
3条回答
  •  野性不改
    2021-01-31 07:47

    Don't know why Java is giving such random output but the issue is in your concatenation that fails for larger values of i inside the for loop.

    If you replace String value = i + ""; line with String value = String.valueOf(i) ; your code works as expected.

    Concatenation using + to convert the int to string is native and might be buggy (Oddly we are founding it now probably) and causing such issue.

    Note: I reduced the value of i inside for loop to 10000 and I didn't face issue with + concatenation.

    This issue must be reported to Java stakeholders & they can give their opinion on same.

    Edit I updated the value of i in for loop to 3 million and saw a new set of errors as below:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
        at java.lang.Integer.getChars(Integer.java:463)
        at java.lang.Integer.toString(Integer.java:402)
        at java.lang.String.valueOf(String.java:3099)
        at solving.LoopOutPut.test(LoopOutPut.java:16)
        at solving.LoopOutPut.main(LoopOutPut.java:8)
    

    My Java version is 8.

提交回复
热议问题