1It usually happens when the stack pointer exceeds the stack bound. Usually due to deep infinite recursions
1public class Vehicle {
2 public void accelerate(float acceleration, float maxVelocity) {
3 // set the acceleration
4 }
5}
6
7public class SpaceShip extends Vehicle {
8 @Override
9 public void accelerate(float acceleration, float maxVelocity) {
10 // update the flux capacitor and call super.accelerate
11 // oops meant to call super.accelerate(acceleration, maxVelocity);
12 // but accidentally wrote this instead. A StackOverflow is in our future.
13 this.accelerate(acceleration, maxVelocity);
14 }
15}
16
1public class StackOverflowErrorExample {
2
3 public static void recursivePrint(int num) {
4 System.out.println("Number: " + num);
5 if (num == 0)
6 return;
7 else
8 recursivePrint(++num);
9 }
10
11 public static void main(String[] args) {
12 StackOverflowErrorExample.recursivePrint(1);
13 }
14}
15
1Number: 1
2Number: 2
3Number: 3
4...
5Number: 6262
6Number: 6263
7Number: 6264
8Number: 6265
9Number: 6266
10Exception in thread "main" java.lang.StackOverflowError
11 at java.io.PrintStream.write(PrintStream.java:480)
12 at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
13 at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
14 at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
15 at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
16 at java.io.PrintStream.write(PrintStream.java:527)
17 at java.io.PrintStream.print(PrintStream.java:669)
18 at java.io.PrintStream.println(PrintStream.java:806)
19 at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:4)
20 at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
21 at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
22 at StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:9)
23 ...
24