10/19/2011

Example of StackOverflowError

One cause of java.lang.StackOverflowError is a method calling itself without exit condition. The following Room class overrides toString method to produce more meaningful string representation, but is implemented wrong:

public class Room {
public static void main(String args[]) {
System.out.println("Created Room: " + new Room());
}

@Override public String toString() {
return "Room: " + this.toString();
//change to super.toString() to avoid StackOverflowError
}
}
Running Room class would fail with java.lang.StackOverflowError.