Surprisingly, the following code outputs:
/
-1
The code:
public class LoopOutPut {
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.