Consider the following code.
public class Action {
private static int i=1;
public static void main(String[] args) {
try{
System.out.println(i);
i++;
main(args);
}catch (StackOverflowError e){
System.out.println(i);
i++;
main(args);
}
}
}
I am getting i value up to 4338
correctly. After catching the StackOverflowError
output getting wired as follows.
4336
4337
4338 // up to this point out put can understand
433943394339 // 4339 repeating thrice
434043404340
4341
434243424342
434343434343
4344
4345
434643464346
434743474347
4348
434943494349
435043504350
Consider Live demo here. It is working correctly up to i=4330
. Actually how this happen?
FYI:
I did following code to realize what is happening here.
public class Action {
private static int i = 1;
private static BufferedWriter bw;
static {
try {
bw = new BufferedWriter(new FileWriter("D:\\sample.txt"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
bw.append(String.valueOf(i)+" ");
try {
i++;
main(args);
} catch (StackOverflowError e) {
bw.append(String.valueOf(i)+" ");
i++;
main(args);
}
}
}
Now previous issue not there. now value of i
up to 16824744
correct and and runs further. I am hopping this may runs up to value of i=2,147,483,647
(max value of int) without an issue.
There is some issue with println()
. There are similar answers bellow too. But why?
What will be the actual reason?